# 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">
<title>Untitled Page</title>
<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();
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

HtmlParser.Parse(document, _xmlr);

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

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

}

private void ShowPdf(string s)
{
Response.ClearContent();
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;
for (int i = 1; i <= 10; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = i * 2;
dr[2] = 1 * 3;
}
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);

}
}


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

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?

3. Hi,

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

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

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

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

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?

8. Hi Mauricio
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

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

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.

11. thanks dude

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

13. 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?

14. Hi

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

15. 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.

16. i have an error named HTMLPARSER Error...

can u give a solution

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

17. This link gives a solution to the HtmlParser:

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?)

18. 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.Close();
}
catch (Exception eg)
{
throw eg;
}
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ContentType = "application/pdf";
HttpContext.Current.Response.BinaryWrite(MStream.GetBuffer());
HttpContext.Current.Response.End();

19. 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 ?

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

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

22. 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

23. Font size too small: 0 error :(

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

25. how to create class in asp.net c#

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

27. 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.

29. Response.ContentType = "application/pdf"
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Dim sw As New StringWriter()
Dim hw As New HtmlTextWriter(sw)
Me.Page.RenderControl(hw)
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]()

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

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

32. 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.

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

34. 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