Overblog Follow this blog
Administration Create my blog
Balavardhan Reddy Narani

iTextSharp

June 6 2012 , Written by Balavardhan Reddy

Getting Started with iTextSharp

 

For the ASP.NET developers out there, if you need to generate PDF reports from your code, there is an open source library called iText# (iTextSharp) that is worth checking out. iTextSharp is a port of the Java iText library written entirely in C#. Source and binaries are available at http://sourceforge.net/projects/itextsharp/.
From what I’ve seen, it works well and only requires one .dll to be copied to your bin directory. Unfortunately, there is no documentation with the product, so I’ll share some of the code I used for a proof of concept that should hopefully get you started.
Using Visual Studio 2005 or greater, or your favorite text editor, create a page with a label called Label1 and a button called Button1. You can skip the label if you want, as I just used it to dump exception output, but I do have it referenced in code. The example will work with any of the Express (free) versions of Visual Studio as well.
First of all, ensure your page has references to ITextSharp.text, ITextSharp.text.PDF, System.IO, and System.Text.

PDFs in ASP.NET using iTextSharp

The "Portable Document Format" (PDF) is an open standard for document exchange. This file format, created by Adobe Systems in 1993, is used for representing documents in a manner independent of application software, hardware, and operating systems. Each PDF file encapsulates a complete description of a fixed-layout flat document, including the text, fonts, graphics, and other information needed to display it. There are many vendors that provide PDF readers across virtually all operating systems, and many proprietary programs, such as Microsoft Word, include a "Save as PDF" option. A person writing a document using Microsoft Word for Windows can save the document as a PDF, which can then be read by others whether or not they are using Windows and whether or not they have Microsoft Word installed. 

Due to their ubiquity and fixed-layout capabilities, it's not uncommon for a websites to use PDF technology. For example, when purchasing goods at an online store you may be offered the ability to download an invoice as a PDF file. PDFs also support form fields, which are user interface elements like textboxes, checkboxes, comboboxes, and the like. 

But unfortunately the .NET framework does not contain any native way to work with PDF files. So, if you want to generate or work with PDF files as part of your ASP.NET web application, you will have to rely on one of the many third party components that are available. One of the popular and free components is iTextSharp library, which is ported from famous open source java library 'iText' for PDF generation. iTextSharp is written entirely in C# for the .NET platform and has a separate codebase. 

In this and next few post i'll be explaining the features of iTextSharp library and that how to programmatically work with PDF files from an ASP.NET application. 

First thing to do is to download the iTextSharp from here (used in this tutorial). You will be presented with a .zip file containing itextsharp.dll. Unzip this, and save it somewhere on your machine. Now create a new Web Site from within Visual Studio or Visual Web Developer. Make sure that you have added the Bin folder from the options in the Add ASP.NET Folder option. 




Right-click on the Bin folder and select Add Reference. The dialogue box should appear. Choose the Browse tab, and locate the itextsharp.dll you saved earlier. 



The dll will be copied to your Bin directory, and is now available to the web site or project. Make sure your solution explorer looks similar to mine. 

Now to start with, it is best to add a couple of using statements to the default ones in your code-behind to avoid typing full references to the dll. Also you would need to reference  System.IO, as you will be creating, opening and closing files, and classes in this namespace are required. And if your PDF would contain ASCII or Unicode character encodings, you'll need to add System.Text namespace too.


using System.IO;
using System.Text;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.
simpleparser;



After adding these namespaces to your code behind file let's start creating a PDF document programmatically from the ground up level. 
The principal object within iTextSharp is the Document object. You need to create an instance of this to be able to work with your PDF in memory. So, the first thing to do is to instantiate one. (Here it's important to decide that upon what event whether on a new page load or on a button click you want to generate the PDF.)


//Create a Document object in memory with following settings, which models the PDF you are creating
Document pdfDoc = new Document(PageSize.A4, 50f, 50f, 50f, 50f);

 //Create a PdfWriter object which is responsible for serializing the PDF document you create to some store, such as in memory or to disk PdfWriter.GetInstance(pdfDoc, Response.OutputStream); //Set some header stuff in the PDF pdfDoc.AddTitle("Some Name"); pdfDoc.AddSubject("Some Subject"); pdfDoc.AddCreator("iTextSharp_v5.3.1"); pdfDoc.AddAuthor("M.Rashid Khan"); //Open the Document pdfDoc.Open();  
 //Add any paragraph text (OPTIONAL) Paragraph myParagraph = new Paragraph("Lorem ipsum dolor sit amet, consectetuer adipiscing elit."); pdfDoc.Add(myParagraph); 
   
 //Put any image in PDF (OPTIONAL) iTextSharp.text.Image myImage = iTextSharp.text.Image.GetInstance(Request.MapPath("~/Balu.jpg")); myImage.Alignment = iTextSharp.text.Image.MIDDLE_ALIGN; myImage.ScalePercent(24f); pdfDoc.Add(myImage); 
   
 //Create a table in PDF (OPTIONAL) PdfPTable myTable = new PdfPTable(3); //Actual width of table in points myTable.TotalWidth = 484f; //fix the absolute width of the table myTable.LockedWidth = true; //Leave a gap before and after the table myTable.SpacingBefore = 20f; myTable.SpacingAfter = 30f; //Set the column widths float[] widths = new float[] { 2f, 2f, 2f }; myTable.SetWidths(widths); //Horizontal alignment 0=Left, 1=Centre, 2=Right myTable.HorizontalAlignment = 1; 
   
 //Create the cells in table PdfPCell cell = new PdfPCell(new Phrase("New Table")); cell.Colspan = 3; cell.HorizontalAlignment = 1; myTable.AddCell(cell); myTable.AddCell("Col 1 Row 1"); myTable.AddCell("Col 2 Row 1"); myTable.AddCell("Col 3 Row 1"); myTable.AddCell("Col 1 Row 2"); myTable.AddCell("Col 2 Row 2"); myTable.AddCell("Col 3 Row 2");  
 
 pdfDoc.Add(myTable);  
 
 //Following code closes the Document object and the PDF is streamed back to the visitor's browser pdfDoc.Close(); Response.ContentType = "application/pdf"; Response.AddHeader("Content-Disposition", "attachment;" + "filename=Simple.pdf"); Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.Write(pdfDoc); Response.End(); 
 
 So this was a basic tutorial for creating simple PDFs in ASP.NET. For advance and more professional features in PDFs like the one which can fetch data and tables directly from database, or PDFs with advance formatting, I'll probably write another advance tutorial later on PDFs creation in ASP.NET using iTesxtSharp.  
 
Read more