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);
}
}
36 Comments
You have a way of explaining things that is easy for me to understand. Not everyone has such a gift
ReplyDeleteThe code I have copied and tried in my system.
ReplyDeleteBut 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?
Hi,
ReplyDeleteJust download iTextsharp lib. from
http://sourceforge.net/projects/itextsharp/
and add reference to your project.
When paging is enable he code wont work, can u help me on that ?
ReplyDeleteHey.... I was lookin for somethin like this n quite surprisingly there's not much of it over there...
ReplyDeleteThe 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
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
ReplyDeletehello... 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?
ReplyDeleteHi Mauricio
ReplyDeletecheck 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
The file generated is corrupt...anything to do?
ReplyDeleteI love you!
ReplyDeleteA 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.
ReplyDeletethanks dude
ReplyDeleteYour tutorials are helping me very much to expertise in ASP.net code book,your valuable effort is appreciated.
DeleteMan... i loved it!!! thanks a lot a lot a lot you save my month!
ReplyDeleteHi,
ReplyDeleteI 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?
Hi
ReplyDeletechk this url
http://aspdotnetcodebook.blogspot.com/2009/12/how-to-fill-pdf-form-field-using.html
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.
ReplyDeletei have an error named HTMLPARSER Error...
ReplyDeleteafter adding the itextsharp.
can u give a solution
The name 'HtmlParser' does not exist in the current context
This link gives a solution to the HtmlParser:
ReplyDeletehttp://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?)
string a = "hello";
ReplyDeleteMemoryStream 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();
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 ?
ReplyDeleteGetting compile time error on VerifyRenderingInServerForm as No suitable method found to override
ReplyDelete@Rima Gandhi:Inherit your base page class with newly created class MyPage
ReplyDeleteThe 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):
ReplyDeletehttp://am22tech.com/s/22/Blogs/post/2011/09/28/HTML-To-PDF-using-iTextSharp.aspx
Font size too small: 0 error :(
ReplyDeletepublic partial class Pdf : MyPage...pls tell me how to call this am new to asp.net
ReplyDeletehow to create class in asp.net c#
ReplyDeletei am getting below error, please resolve it,
ReplyDeleteThe number of columns in PdfPTable constructor must be greater than zero.
I'm having problems with HtmlParser. VS says that: "The name 'HtmlParser' does not exist in the current context".
ReplyDeleteAny suggestions?
Currently using itextsharp version 5.3.3.0 and VS 2012.
try this link
ReplyDeletehttp://www.dotnetfunda.com/forums/thread2353-solution-htmlparser-doesnt-exsits-in-itextsharp-5020-free-net.aspx
Response.ContentType = "application/pdf"
ReplyDeleteResponse.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]()
How to convert Html page to Pdf...with images.....i can try the above code ...i am getting error....kindly help plz.....
ReplyDeletehow to convert html page with image to pdf converter....i am trying when the above code ...im getting error...plz help.....
ReplyDeleteHey Gyss Check out this...
ReplyDeleteSoftpro 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.
How to manage the width of each column. I need custom width. itextsharp make default 100% table width without colspan.
ReplyDeleteI 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.
ReplyDeleteFor more details: ReactJs training in Velachery | ReactJs training in chennai
Please do not post any spam link in the comment box😊