Generate PDF with ASP.NET and iTextSharp

 

PDF is a popular file format for documents. Due to their ubiquity and layout capabilities, it's not uncommon for a websites to use PDF technology. There are a variety of .NET libraries available to programmatically create PDF documents. Perhaps the most popular is iTextSharp, which is also a free to use API.

Using iTextSharp we can print the any kind of html, CSS & images on the PDF Document. I am using the iTextSharp to Print the the DataList in PDF format. DataList is Loaded Dynamically By Value Which Contain Text and images to print on the PDF Document . Below is the code to convert DataList Into a PDF Document.

Below is the code:

Web Form : PDF.aspx

Below is the datalist which is used for rendering the content directly to HTMLTextWriter object. Sometimes you may need to display datalist differently on web page and pdf. In that case you can have a duplicate datalist control with visibility set to none. In this duplicate control, you can have html format as you want in the PDF.

<asp:DataList ID="m_ctlPdfGuide_DataList" runat="server">

<ItemTemplate>

<asp:Label CssClass="largeName" runat="server" ID="m_ctlHotelName" Text='<%#Eval("BrochureItemName")%>'> </asp:Label>

<asp:Image ID="m_ctlBrochureItemImage" Height="50px" Width="100px" ImageUrl='<%#GetImageUrlPDF(Eval("BrochureItemImageName"))%>' Visible="true" runat="server" />

<asp:Label ID="Label1" CssClass="address" runat="server" Text='<%#Eval("BrochureItemAddress")%>'></asp:Label>

<asp:Label ID="Label2" CssClass="description" runat="server" Text='<%#Eval("BrochureItemDescription")%>'></asp:Label>

</ItemTemplate>

</asp:DataList>

<asp:Button ID="m_ctlPrintGuide_Button" CssClass="search_btn" runat="server" Text="Save Guide" OnClick="m_ctlPrintGuide_Button_Click" ToolTip="Save Guide To Your Desktop" />

 

Code-Behind: PDF.CS

On Button Click We create a pdf document and save any where on our Desktop.

protected void m_ctlPrintGuide_Button_Click(object sender, EventArgs e)

{

string attachment = "attachment; filename=TravelGuide.pdf";

Response.ClearContent();

Response.AddHeader("content-disposition", attachment);

Response.ContentType = "application/pdf";

// Rendering DataList into HTMLTextWriter

StringWriter swHtml = new StringWriter();

HtmlTextWriter hTextWriter = new HtmlTextWriter(swHtml);

m_ctlPdfGuide_DataList.RenderControl(hTextWriter);

try

{

using (Document doc = new Document(PageSize.A4))

{

using (PdfWriter w = PdfWriter.GetInstance(doc, Response.OutputStream))

{

doc.Open();

// Getting City Name From Session

string cityName = string.Empty;

if (!string.IsNullOrEmpty(SessionUtil.GetCurrentCityNameFromSession()))

cityName = " to " + SessionUtil.GetCurrentCityNameFromSession();

//add guide header

Chunk c = new Chunk("Your Guide" + cityName + "\n", FontFactory.GetFont("Verdana", 15));

Paragraph p = new Paragraph();

p.Alignment = Element.HEADER;

p.Add(c);

doc.Add(p);

//add columns

MultiColumnText columns = new MultiColumnText();

columns.AddRegularColumns(36f, doc.PageSize.Width - 36f, 25f, 2);

// Set margin to document

doc.SetMargins(0f, 8f, 8f, 10f);

// Apply CSS to DataList for style

StyleSheet style = new StyleSheet();

style.LoadTagStyle(HtmlTags.IMG, HtmlTags.WIDTH, "220px");

style.LoadTagStyle(HtmlTags.IMG, HtmlTags.HEIGHT, "80px");

style.LoadStyle("address", "style", "font-size: 8px; text-align: justify; font-family: Arial, Helvetica, sans-serif;");

style.LoadStyle("largeName", "style", "font-size: 10px; text-align: justify; font-family: Arial, Helvetica, sans-serif;");

style.LoadStyle("description", "style", "font-size: 8px; text-align: justify; font-family: Arial, Helvetica, sans-serif;");

// Reading value Of DataList to write on the PDF Document

using (StringReader sr = new StringReader(swHtml.ToString()))

{

List<IElement> list = HTMLWorker.ParseToList(sr, style);

foreach (IElement elm in list)

{

columns.AddElement(elm);

doc.Add(columns);

}

}

doc.Close();

Response.Write(doc);

Response.End();

}

}

}

catch

{

//throw new ApplicationException("Oops! Error occurred while downloading the Travel Guide! "+ ex.ToString());

}

finally

{

swHtml = null;

hTextWriter = null;

}

}

When Document Is Created it looks like This:

Below is the screen shot of the document

clip_image001

Happy Coding!!