Search Code Guru

Easily Export Html to PDF using iTextSharp(now iText) in C#

ASP.NET is an open-source server-side web-application framework designed for web development to produce dynamic web pages developed by Microsoft to allow programmers to build dynamic web sites, applications and services.

iTextSharp (now iText) is a library for creating and manipulating PDF files in Java and .NET. iText was written by Bruno Lowagie. The source code was initially distributed as open source under the Mozilla Public License.

In this article, I will show you how to convert ASP.NET GridView control to pdf at runtime.


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Pdf.aspx.cs" Inherits="Pdf" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
  <div>
      <asp:GridView ID="GridView1" runat="server">
      </asp:GridView>
      <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Pdf" /></div>
</form>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
using iTextSharp.text.html;

public partial class Pdf : MyPage
{
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        GridView1.DataSource = GetData();
        GridView1.DataBind();
    }

}
protected void Button1_Click(object sender, EventArgs e)
{
    MyPage tmpPage = new MyPage();
    HtmlForm form = new HtmlForm();
    form.Controls.Add(GridView1);
    tmpPage.Controls.Add(form);
    StringWriter sw = new StringWriter();
    HtmlTextWriter htmlWriter = new HtmlTextWriter(sw);
    form.Controls[0].RenderControl(htmlWriter);
    string htmlContent = sw.ToString();
    Document document = new Document();
    // step 2:
    // we create a writer that listens to the document
    // and directs a PDF-stream to a file
    PdfWriter.GetInstance(document, new FileStream("c:\\Chap0101.pdf", FileMode.Create));

    // step 3: we open the document
    document.Open();

    // step 4: we add a paragraph to the document
    //document.Add(new Paragraph(htmlContent.ToString()));

    System.Xml.XmlTextReader _xmlr = new System.Xml.XmlTextReader(new StringReader(htmlContent));

    HtmlParser.Parse(document, _xmlr);

    // step 5: we close the document
    document.Close();

    ShowPdf("c:\\Chap0101.pdf");

}

private void ShowPdf(string s)
{
    Response.ClearContent();
    Response.ClearHeaders();
    Response.AddHeader("Content-Disposition", "inline;filename=" + s);
    Response.ContentType = "application/pdf";
    Response.WriteFile(s);
    Response.Flush();
    Response.Clear();
}
public DataSet GetData()
{
    DataSet ds = new DataSet();
    DataTable dt = new DataTable("Product");
    DataRow dr;
    dt.Columns.Add(new DataColumn("Price", typeof(Int32)));
    dt.Columns.Add(new DataColumn("DisCount", typeof(Int32)));
    dt.Columns.Add(new DataColumn("SellPrice", typeof(Int32)));
    for (int i = 1; i <= 10; i++)
    {
        dr = dt.NewRow();
        dr[0] = i;
        dr[1] = i * 2;
        dr[2] = 1 * 3;
        dt.Rows.Add(dr);
    }
    ds.Tables.Add(dt);
    Session["dt"] = dt;
    return ds;
}
}

Create a new clas Mypage.cs in app_code folder.

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

/// <summary>
/// Summary description for MyPage
/// </summary>
public class MyPage : Page
{
 public override void VerifyRenderingInServerForm(Control control)
 {
     GridView grid = control as GridView;
     if (grid != null && grid.ID == "GridView1")
         return;
     else
         base.VerifyRenderingInServerForm(control);

 }
}

Post a Comment

36 Comments

  1. You have a way of explaining things that is easy for me to understand. Not everyone has such a gift

    ReplyDelete
  2. The code I have copied and tried in my system.
    But It was showing the following error:
    "The type or namespace name 'iTextSharp' could not be found (are you missing a using directive or an assembly reference)"

    What to do...Can u help me?

    ReplyDelete
  3. Hi,
    Just download iTextsharp lib. from

    http://sourceforge.net/projects/itextsharp/

    and add reference to your project.

    ReplyDelete
  4. When paging is enable he code wont work, can u help me on that ?

    ReplyDelete
  5. Hey.... I was lookin for somethin like this n quite surprisingly there's not much of it over there...
    The tutorials put up are missing the first basic step of integration and tellin you how to do advance stuff without gettin to the basic.
    Thanks for this n for puttin it so simply

    ReplyDelete
  6. Man... thanks a lot man.. you are the MAN.... wow... your code works wonders... and i wonder how much you earn with your top notch skills... definitely millions.... good man

    ReplyDelete
  7. hello... if i need to put a WebUserControl, im trying to do this but i getting an error saying thate: Unable to cast object of type 'iTextSharp.text.Paragraph' to type 'iTextSharp.text.Table'. What should i do?

    ReplyDelete
  8. Hi Mauricio
    check out therse links
    http://forums.asp.net/t/1286980.aspx
    http://netpl.blogspot.com/2008/02/unable-to-cast-object-of-type-to-type.html
    http://aspdotnetcodebook.blogspot.com/2009/04/how-to-convert-web-page-to-pdf.html

    ReplyDelete
  9. The file generated is corrupt...anything to do?

    ReplyDelete
  10. A most excellent article. Thanks. Is there something that can be added to the ShowPDF method to make the resulting pDF appear in a new window instead of in the existing window? Thanks.

    ReplyDelete
  11. Man... i loved it!!! thanks a lot a lot a lot you save my month!

    ReplyDelete
  12. Hi,

    I would like first to fill some PDF form fields and then add a table to the same document. Any ideas how this can be done?

    ReplyDelete
  13. Hi

    chk this url
    http://aspdotnetcodebook.blogspot.com/2009/12/how-to-fill-pdf-form-field-using.html

    ReplyDelete
  14. I know a lot of tools for work with pdf files. But couple days ago I was in unpleasant situation and entered in the Internet,where I noticed - recover pdf. It solved my issue for seconds and for free as I bore in mind.

    ReplyDelete
  15. i have an error named HTMLPARSER Error...
    after adding the itextsharp.

    can u give a solution

    The name 'HtmlParser' does not exist in the current context

    ReplyDelete
  16. This link gives a solution to the HtmlParser:
    http://www.dotnetfunda.com/forums/thread2353-solution--htmlparser-doesnt-exsits-in-itextsharp-5020-free-net.aspx

    the output's not as nice as converting with Adobe's objects (which I can't get running on a server), but it does work.

    Problems seen thus far: script tags, img src's trying to load from C:\
    font size is way too big (loss of style info?)

    ReplyDelete
  17. string a = "hello";
    MemoryStream MStream = new MemoryStream();
    Document document = new Document(PageSize.A4, 80, 50, 30, 65);
    try
    {
    PdfWriter writer = PdfWriter.GetInstance(document, MStream);
    document.Open();
    document.Add(new iTextSharp.text.Paragraph(strContent));
    document.Close();
    }
    catch (Exception eg)
    {
    throw eg;
    }
    HttpContext.Current.Response.Buffer = true;
    HttpContext.Current.Response.ClearContent();
    HttpContext.Current.Response.ClearHeaders();
    HttpContext.Current.Response.ContentType = "application/pdf";
    HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=myPDFNew.pdf");
    HttpContext.Current.Response.BinaryWrite(MStream.GetBuffer());
    HttpContext.Current.Response.End();

    ReplyDelete
  18. http://www.dotnetfunda.com/forums/thread2353-solution--htmlparser-doesnt-exsits-in-itextsharp-5020-free-net.aspx does indeed give a solution but, I don't understand how to apply it to this article can someone assist ?

    ReplyDelete
  19. Getting compile time error on VerifyRenderingInServerForm as No suitable method found to override

    ReplyDelete
  20. @Rima Gandhi:Inherit your base page class with newly created class MyPage

    ReplyDelete
  21. The above code is good enough to convert a HTML code but i guess you can easily use the new itextShapr library's HTML worker class to make the task even easier. It automatically parses all HML and gives you the PDF. The main loophole is the IMG tag;s relative URLs and it can be taken care by your code. I have written the code and ahred it here (if anybody would like to use it):
    http://am22tech.com/s/22/Blogs/post/2011/09/28/HTML-To-PDF-using-iTextSharp.aspx

    ReplyDelete
  22. public partial class Pdf : MyPage...pls tell me how to call this am new to asp.net

    ReplyDelete
  23. how to create class in asp.net c#

    ReplyDelete
  24. i am getting below error, please resolve it,
    The number of columns in PdfPTable constructor must be greater than zero.

    ReplyDelete
  25. I'm having problems with HtmlParser. VS says that: "The name 'HtmlParser' does not exist in the current context".

    Any suggestions?

    Currently using itextsharp version 5.3.3.0 and VS 2012.

    ReplyDelete
  26. try this link

    http://www.dotnetfunda.com/forums/thread2353-solution-htmlparser-doesnt-exsits-in-itextsharp-5020-free-net.aspx

    ReplyDelete
  27. Response.ContentType = "application/pdf"
    Response.AddHeader("content-disposition", "attachment;filename=TestPage.pdf")
    Response.Cache.SetCacheability(HttpCacheability.NoCache)
    Dim sw As New StringWriter()
    Dim hw As New HtmlTextWriter(sw)
    Me.Page.RenderControl(hw)
    Dim sr As New StringReader(sw.ToString())
    Dim pdfDoc As New Document(PageSize.A4, 10.0F, 10.0F, 100.0F, 0.0F)
    Dim htmlparser As New HTMLWorker(pdfDoc)
    PdfWriter.GetInstance(pdfDoc, Response.OutputStream)
    pdfDoc.Open()
    htmlparser.Parse(sr)
    pdfDoc.Close()
    Response.Write(pdfDoc)
    Response.[End]()

    ReplyDelete
  28. How to convert Html page to Pdf...with images.....i can try the above code ...i am getting error....kindly help plz.....

    ReplyDelete
  29. how to convert html page with image to pdf converter....i am trying when the above code ...im getting error...plz help.....

    ReplyDelete
  30. Hey Gyss Check out this...

    Softpro Learning Center (SLC)is the training wing of Softpro India Computer Technologies Pvt.
    Limited. SLC established itself in the year 2008.
    SLC offer an intensive and extensive range of training/internship programs for B.Tech, BCA, MCA & Diploma students.
    Softpro Learning Center is a best Summer training institute in Lucknow extends in depth knowledge of technology like .Net, Java, PHP and Android and also an opportunity to practically apply their fundamentals. SLC’s objective is to provide skilled manpower to support the vast development programs.

    ReplyDelete
  31. How to manage the width of each column. I need custom width. itextsharp make default 100% table width without colspan.

    ReplyDelete
  32. I accept there are numerous more pleasurable open doors ahead for people that took a gander at your site.we are providing ReactJs training in Chennai.
    For more details: ReactJs training in Velachery | ReactJs training in chennai

    ReplyDelete

Please do not post any spam link in the comment box😊