Export GridView To Pdf-ASP.NET

In this example i'm explaining how to Export GridView To PDF Using iTextsharp In Asp.Net 2.0,3.5,4.0 Using C# VB.NET i am exporting Gridview populated with SqlDataSource to Pdf using iTextSharp in click event of Button

I have populated gridview with SqlDataSource and placed one button on the page to create pdf from gridview.






   1:  <asp:GridView ID="GridView1" runat="server" 
   2:                AutoGenerateColumns="False" 
   3:                DataSourceID="SqlDataSource1">
   4:  <Columns>
   5:  <asp:BoundField DataField="Name" HeaderText="Name"/>
   6:  <asp:BoundField DataField="Location" HeaderText="Location"/>
   7:  </Columns>
   8:  </asp:GridView>
   9:   
  10:  <asp:Button ID="btnExport" runat="server" 
  11:              OnClick="btnExport_Click" Text="Export to PDF" />
  12:              
  13:  <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
  14:  ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
  15:  SelectCommand="SELECT [Name], [Location] FROM [Test]">
  16:  </asp:SqlDataSource>

To use iTextSharp , we need to add these namspaces in the code behind and itextsharp.dll in Bin folder of Application
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using System.IO;
using System.Collections;
using System.Net;

Now in Click event of button i m creating a new HtmlForm and adding the gridview control to this form in code behind , than creating instance of StringWriter class and HtmlTextWriter to write strings and than rendernig these to form created earlier
protected void btnExport_Click
(object sender, EventArgs e)
{
HtmlForm form = new HtmlForm();
form.Controls.Add(GridView1);
StringWriter sw = new StringWriter();
HtmlTextWriter hTextWriter = new HtmlTextWriter(sw);
form.Controls[0].RenderControl(hTextWriter);
string html = sw.ToString();

In next lines of code i m creating a new Document in specified location and opening it for writing
Document Doc = new Document();

If u wanna save the pdf in application's root folder in server
than use Requesr.PhysicalApplicationPath

//PdfWriter.GetInstance
//(Doc, new FileStream(Request.PhysicalApplicationPath 
//+ "\\AmitJain.pdf", FileMode.Create));

And if u wanna save the PDF at users Desktop than use
Environment.GetFolderPath(Environment.SpecialFolder.Desktop

PdfWriter.GetInstance
(Doc, new FileStream(Environment.GetFolderPath
(Environment.SpecialFolder.Desktop)
+ "\\AmitJain.pdf", FileMode.Create));
Doc.Open();

Now i m adding a paragraph to this document to be used as
Header by creating a new chuck and adding it to paragraph

Chunk c = new Chunk
("Export GridView to PDF Using iTextSharp \n",
FontFactory.GetFont("Verdana", 15));
Paragraph p = new Paragraph();
p.Alignment = Element.ALIGN_CENTER;
p.Add(c);
Chunk chunk1 = new Chunk
("By Amit Jain, amit_jain_online@yahoo.com \n",
FontFactory.GetFont("Verdana", 8));
Paragraph p1 = new Paragraph();
p1.Alignment = Element.ALIGN_RIGHT;
p1.Add(chunk1);

Doc.Add(p);
Doc.Add(p1);

Now i m reading the html string created above through 
xmlTextReader and htmlParser to parse html elements

System.Xml.XmlTextReader xmlReader =
new System.Xml.XmlTextReader(new StringReader(html));
HtmlParser.Parse(Doc, xmlReader);

Doc.Close();
string Path = Environment.GetFolderPath
(Environment.SpecialFolder.Desktop)
+ "\\AmitJain.pdf";


ShowPdf(Path);


The complete code looks like this

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;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using System.IO;
using System.Collections;
using System.Net;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnExport_Click(object sender, EventArgs e)
{
HtmlForm form = new HtmlForm();
form.Controls.Add(GridView1);
StringWriter sw = new StringWriter();
HtmlTextWriter hTextWriter = new HtmlTextWriter(sw);
form.Controls[0].RenderControl(hTextWriter);
string html = sw.ToString();
Document Doc = new Document();

//PdfWriter.GetInstance
//(Doc, new FileStream(Request.PhysicalApplicationPath 
//+ "\\AmitJain.pdf", FileMode.Create));

PdfWriter.GetInstance
(Doc, new FileStream(Environment.GetFolderPath
(Environment.SpecialFolder.Desktop)
+ "\\AmitJain.pdf", FileMode.Create));
Doc.Open();

Chunk c = new Chunk
("Export GridView to PDF Using iTextSharp \n",
FontFactory.GetFont("Verdana", 15));
Paragraph p = new Paragraph();
p.Alignment = Element.ALIGN_CENTER;
p.Add(c);
Chunk chunk1 = new Chunk
("By Amit Jain, amit_jain_online@yahoo.com \n",
FontFactory.GetFont("Verdana", 8));
Paragraph p1 = new Paragraph();
p1.Alignment = Element.ALIGN_RIGHT;
p1.Add(chunk1);

Doc.Add(p);
Doc.Add(p1);

System.Xml.XmlTextReader xmlReader =
new System.Xml.XmlTextReader(new StringReader(html));
HtmlParser.Parse(Doc, xmlReader);

Doc.Close();
string Path = Environment.GetFolderPath
(Environment.SpecialFolder.Desktop)
+ "\\AmitJain.pdf";


ShowPdf(Path);


}

private void ShowPdf(string strS)
{
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.AddHeader
("Content-Disposition","attachment; filename=" + strS);
Response.TransmitFile(strS);
Response.End();
//Response.WriteFile(strS);
Response.Flush();
Response.Clear();

}

}

This code doesn't work if paging is enabled in GridView and the other this is cloumns become of variable width in PDF document , to fix these issues read my next Post Exporting Paging enabled GridView to PDF using iTextSharp

Download the sample Code


Other Gridview articles you would like to read:

1. Populating dropdown based on the selection of first drop down in DetailsView using FindControl and ItemTemplate

2. Pouplating Multiple DetailsView based on single GridView using DataKeyNames in ASP.NET

3. Merging GridView Headers to have multiple Headers in GridView using C# ASP.NET
If you like this post than join us or share

93 comments:

Anonymous said...

Really useful post..But how can I set the font of the document content?


Anonymous said...

The code did'nt work when we apply paging to the gridview,can u help me on that ?


tasksforceonline said...

Dont know yet whether code is helpfull or not but the coding is excellent i liked it upto a extent it gave us a great flexibility .thnks .


Unknown said...
This comment has been removed by the author.

Anonymous said...

Good one nice post and excellent example.Thanks for sharing.Apart from iTextSharp is there any other way to create pdf, I mean with C# native code can we achieve this?


Anonymous said...

nice post


Anonymous said...

Thanks ur information

it very useful



Small business website design


Unknown said...

@Anonymous: read my post here for the paging enabled gridview solution


azamsharp said...

Here is another article which also includes images:

http://highoncoding.com/Articles/483_Exporting_GridView_to_PDF_Document.aspx


Ashfaq Hussain said...

refer

http://www.ashfk.blogspot.com/ click follower ramky
http://www.ashfk.blogspot.com/


Тимонин Евгений said...

Thank's. Really very usefull.


Shakti Singh Dulawat said...

This comment has been removed by a blog administrator.


Unknown said...

How to make this to work with datalist?


Anonymous said...

why dont you use commercial PDF conversion .NET component.

with just couple lines of code...

i have the component you just needed.many functions! very easy to incorporate to the website.

ABCPdf Full version (Installer). (try to lookup on the web)

email me if you want at a very very cheap price.
xxkmx1@yahoo.com.ph

cheers!


Unknown said...

Thanks. Really good work! I am trying to look deep into the code you provided. Happy Programming!


Jasmine said...

however the following line of code shows error when i tried running my web application. what went wrong? any help people?

form.Controls[0].RenderControl(hTextWriter);


TIA!


Unknown said...

@ Jasmine :

Download the sample application from the download link above , run it and do let me know what error u r getting, u need to have itextsharp and VS 2005 for this ti run

amiT


Jasmine said...

Hi Amit thanks for the reply!
I tried the sample application using Visual Web Developer and it worked fine.
So I then tried to modift it and paste on my own application. when I tried to run it, this is the error code it gave me:

Control 'GridView1_ctl13_ctl05' of type 'DataControlLinkButton' must be placed inside a form tag with runat=server.

Why is it the error?
Thanks in advance!


Unknown said...

@Jasmine:

Hi

Check html source of your aspx page and check whether runat="server" is present in the asp:GridView tags


Sandesh said...

Hi

It working fine, but when the column size of the grid increases the data is displayed in a horizontal format. Can set the PDF page size using the above code.

Regards, Sandesh


Unknown said...

@sandesh :

Hi sandesh , for the column width problem i've write another article, it also deals with paging enabled gridview problem

read this

Exporting Paging enabled GridView to PDF using iTextSharp


Anonymous said...

Hi

This is really very useful but How do I download that itextSharp dll as i tried downloading it but getting some problem. If anyone can just send at my gmailId that wud be really appreciating.

Thanks in advance.

Shweta


Unknown said...

@ shweta :

You forgot to mention your e-mail id

any way you can download iTextsharp dll from this direct link

http://jaist.dl.sourceforge.net/sourceforge/itextsharp/itextsharp-4.1.2-dll.zip

Do let me know if you have any further problems in downloading this


Talib Ali Khan said...

Hi Amit ,

Nice post..... PLease keep up the good work..

BTW, one question i would like to ask you is , how can we set the positions for the columns appearing in the .pdf file...


Unknown said...

@ Talib Ali Khan:

Hi talib , for positioning of columns you can read this article


antilife said...

Great post. Quick question though... is there a way to serve up the PDF without saving it? i.e. straight from the stream in which you create it?


Unknown said...

@antilife:

Hi, Yes you can create pdf without saving it on the disk, for this you need to use response.outstream as one of the parameter in PdfWriter.GetInstance

Either Read this

Or read this article where i m not saving the pdf on disk
ASP.NET-Exporting paging enabled GridView to pdf using iTextSharp and C#


Unknown said...

how to save pdf file using itextsharp in c#,if users want to save it in particular folder but one thing it never save bydefault.


Unknown said...

@sachin:

Change this code according to the location you want to save file to

PdfWriter.GetInstance
(Doc, new FileStream(Environment.GetFolderPath
(Environment.SpecialFolder.Desktop)
+ "\\AmitJain.pdf", FileMode.Create));

using this code, i'm saving pdf at user's desktop, you can change it to ur preffered location.


sushil said...

thanks

this is really very helpfull............


Vijaya Kadiyala said...

Its Really good article...
Thanks -- Vijaya Kadiyala
www.DotNetVJ.com


Innovative Technology Solutions said...

where i paste the DLL File?


Unknown said...

@Innovative Technology Solutions:

Right click on solution explorer > add new ASP.NET folder > Bin

Now put iTextSharp.dll in this Bin folder

Add references to this dll , add namespaces in code behind (mentioned above in the article )

It should work

do let me know if you face any further problem


Anonymous said...

Hi: I am getting the: Control 'GridView2_ctl28_ctl01' of type 'DataControlLinkButton' must be placed inside a form tag with runat=server.

Error and my GridView does contain runat="server". Thanks for your help.


Unknown said...

@Anonymous:

Please make sure your gridview is having runat="server" attribute like the code mentioned below


<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False"


Bhanu said...

Hi Amit

I had few question.
I am exporting aspx panel to pdf and it has check boxes, everything gets exported to PDF other then check boxes, do u have solutions for it?
I want more generic kind of code, bcoz i have many panels/forms to export to pdf.
plus my application will keep adding more forms to export to pdf.


Bhanu said...

This code file has been removed, can u plz upload again?
Why don't u get a private hosting and domain name.
I can setup a blog for free for u on your personal, private hosting.
e-mail me bhanu@blisstechnologies.co.in
info@blisshosting.co.in


Anonymous said...

This comment has been removed by a blog administrator.


Anonymous said...

Very Good post. But i have a bad problem.
I got a GW with about 10 coloumns. The pdf extract works fine, but when i open it, i can see the FIRST coloum VERY VERY large, and the other colounms VERY tiny for example:

Have you got an idea? Thx in advance!


Unknown said...

@noncelafaccio:

Hi noncelafaccio , please refer my below mentioned article to overcome this formatting issue of PDF

Export paging enabled gridview to pdf using iTextSharp


Unknown said...

showPdf(); does not exist in my dll. :(
how to show my pdf created by ur code?
is there any otherway to view pdf?


and i have a aspx page, i want to convert this complete page into pdf. is this possible?
my page contains more controls like textbox, buttons,gridview. i want to view my page as it is in pdf formate.


Unknown said...

@Muhammad Kashif:

ShowPdf is not method of dll , it's a method i've to show pdf , check the code carefully

private void ShowPdf(string strS)
{
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.AddHeader
("Content-Disposition","attachment; filename=" + strS);
Response.TransmitFile(strS);
Response.End();
//Response.WriteFile(strS);
Response.Flush();
Response.Clear();

}


Anonymous said...

Hello!

I've tried your code, but I've a cast exception @ the line "HtmlParser.Parse(doc, xmlReader)"

Unable to cast object of type 'iTextSharp.text.Paragraph' to type 'iTextSharp.text.Table'.

I've exactly done what you've done, just to test...

Do you know where it come from?

thx a lot

Xavier


Unknown said...

@Xavier:

Have you added below mentioned namespaces in your code behind

using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using System.IO;
using System.Collections;
using System.Net;

do let me know


Regin said...

thanks so much. Really liked the way in which you described the different methods like saving on server, desktop etc. Keep writing and good luck!


Anonymous said...

your download code does not work. can u rectify?

Thanks!


Unknown said...

@Above:

You Can Download the source code from here


Anonymous said...

How would I go about making this open in a new window? As it is now, when the page loads it renders the PDF so that when you close the PDF the calling page is gone.

Thanks...


Anonymous said...

sir i want to convert .aspx page to pdf format which contains panel and some labels under the tables not gridview i have applied this code on it open pdf file bt without data that aspx page contains pls give me some ideas.
thanks.


Anonymous said...

sir i want to convert .aspx page to pdf format which contains panel and some labels under the tables not gridview i have applied this code on it open pdf file bt without data that aspx page contains pls give me some ideas.
thanks.


Anonymous said...

nice post mate.....


web design


Anonymous said...

There is a execelent free component for entire gridview export, print etc. Following link will help.
http://www.softsona.com/SonaGridToolBarPage.aspx


Anonymous said...

If I want the PDF should have Page Header in every page, What should i do?

Thanks in advance,
Mohamed


Ramakrishnan said...

Can i raise a event to pdf through button Click event.
raising events between Pdf and Html
Example:
I have several fields in my pdf.
While Clicking on the Submit buttom in aspx page i need to read all values and update in Database.
Could you Please Help me on this.
thanks in advance.


Anonymous said...

hi master, I've tried your code, but I've a cast exception @ the line "HtmlParser.Parse(doc, xmlReader)"

please, can u help me?


Anonymous said...

Hello !.
might , perhaps very interested to know how one can make real money .
There is no initial capital needed You may begin to get income with as small sum of money as 20-100 dollars.

AimTrust is what you thought of all the time
The firm incorporates an offshore structure with advanced asset management technologies in production and delivery of pipes for oil and gas.

Its head office is in Panama with structures around the world.
Do you want to become an affluent person?
That`s your chance That`s what you wish in the long run!

I feel good, I started to get income with the help of this company,
and I invite you to do the same. It`s all about how to choose a correct companion utilizes your savings in a right way - that`s it!.
I take now up to 2G every day, and my first investment was 500 dollars only!
It`s easy to join , just click this link http://wurudefyma.maddsites.com/irywywe.html
and go! Let`s take this option together to become rich


Anonymous said...

Hello Sir...

I am used ur code and it works.

I asking one question regarding blog writing. I create my blog in blogger.com and i want to post some asp.net source code with explanation.
It can shows my posted data except my asp.net source code.

Can you please tell me how to post asp.net code on my blog like your blog articles.

I tried lot but it couldn't be worked, plese help me.

Sagar Gupta
sara.gupta03@gmail.co


Anonymous said...

i have the problem with
HtmlParser.Parse(Doc, xmlReader);

i have add the reference iTextSharp.dll into my proyect... so i don't know what its the problem

if someone resolve this issue pls post it


Anonymous said...

Use iTextSharp v4. v5 does not contain HtmlParser.


Anonymous said...

HtmlParser.Parse(Doc, xmlReader);


Friends Company said...

hi all,
thanks for great example of exporting to pdf.
but my problem is how to export aspx page with online data, i mean at runtime aspx page using url and export to pdf file.
can any one knows than please help us and pls send the example code, I really appreciate all of you. my email id is ishk.shk@gmail.com.
if is it then send a sample code or link to my email id.

Thanks
Ishtiyaque.


Anonymous said...

I use masterpage.master and inherit from it.The asp page have no tag form and error happen .Can you help me?


An Vo-Hoai said...

i have trouble with the asp page inherit from Masterpage.Master .So it doesn't have any form tag.


Manula said...

Thanks. This code is working properly. It helpful to do my task in the project


homes for sale costa rica said...

hello. thank you very much for letting me comment. very good article I would like more information on this item


Anonymous said...

You are right.


Deepu said...

hiii...really nice to see much interesting postings on Ur blog. amith please guide me some help with itextsharp.. i checked out the method you posted about itextsharp to create pdf from grid-view.. im working on a pdf creation from HTML code which i made in a editor, i have to generate a pdf with all the styles and designs i made in the editor..i have generated pdf using itextsharp but the inline styles in HTML is not generated in the pdf..please help with valuable codes and guidance...


Custom Software Development said...

Thanks for the nice information. I am sure, I will tweet this to my twitter account. This will help a lot of users.


Anonymous said...

Certainly. I agree with you.


Anonymous said...

Exact phrase


rhiena said...

hii i have a lot of coloumn, what about to make a margin in every header?


Anonymous said...

Hi all,
I have a gridview with checkbox. If i select the multiple check box, the data shoud be export in word. As per my code, only last record is exported.
My code is foolowing:--
try
{
StringWriter sw = new StringWriter();
DataTable dt = getValues();
if (dt != null)
{
foreach(DataRow dr in dt.Rows)
{
//Response.Clear();

string strCaseStudyID = dr["Title"].ToString();
Response.ContentType = "application/vnd.ms-word";
HttpContext.Current.Response.AppendHeader("content-disposition", "attachment;filename=CaseStudy_Details.doc");
SPWeb web = SPContext.Current.Web;
//string strCaseStudyID = "CaseStudy-1";//Page.Request.QueryString["CaseStudyID"];
SPList oSPSList = web.Lists[Constants.lstProjectDetails];
SPQuery oQuery = new SPQuery();
oQuery.Query = "" + strCaseStudyID + "";
DataTable dtTable = oSPSList.GetItems(oQuery).GetDataTable();
dlCustomerDet.DataSource = dtTable;
dlCustomerDet.DataBind();
SPList oSPSListPD = web.Lists[Constants.lstProjectDetails];
SPQuery oSPImgQry = new SPQuery();
oSPImgQry.Query = "" + strCaseStudyID + "";
DataTable dtImg = oSPSListPD.GetItems(oSPImgQry).GetDataTable();

HtmlTextWriter hw = new HtmlTextWriter(sw);
dlCustomerDet.RenderControl(hw);

SPList oSPSListPO = web.Lists[Constants.lstProjectOverview];
SPQuery oSPTecQry = new SPQuery();
oSPTecQry.Query = "" + strCaseStudyID + "";
DataTable dtTec = oSPSListPO.GetItems(oSPTecQry).GetDataTable();

if (dtTec != null)
{
if (dtTec.Rows.Count > 0)
{
lblTechnologyList.Text = dtTec.Rows[0]["Primary"].ToString();
lblTechnologyList.RenderControl(hw);
}
}

if (dtImg != null)
{
imgCArch.ImageUrl = (dtImg.Rows[0]["ComArchDiag"].ToString()).Split(',')[0];
imgCArch.RenderControl(hw);
if (imgCArch.ImageUrl == "")
{
imgCArch.Visible = false;
}
}
if (dtImg != null)
{
imgFArch.ImageUrl = (dtImg.Rows[0]["ArchDiag"].ToString()).Split(',')[0];
imgFArch.RenderControl(hw);
if (imgFArch.ImageUrl == "")
{
imgFArch.Visible = false;
}
}
}
// Response.Output.Write(sw.ToString());
}
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
catch (Exception ex)
{
base.Render(writer);
}
Thanks


Joe said...

Hi, its really good article. can anyone help me how to export a nested grid to PDF.


Anonymous said...

I’ve been visiting your blog for a while now and I always find a gem in your new posts. Thanks for sharing.


Anonymous said...

I guess you will want to place a facebook icon to your website. I just bookmarked the url, but I must make it manually. Simply my 2 cents.


Anonymous said...

I get this:

Error 1 The name 'HtmlParser' does not exist in the current context C:\Users\ASHA\Documents\Visual Studio 2008\Projects\GeneratePDF_hn441mjr\GeneratePDF_hn441mjr\WebForm1.aspx.cs 78 13 GeneratePDF_hn441mjr. What could be the prob.


Anonymous said...

THX for sharing


Anonymous said...

Hi
I face a problem while exporting the data into PDF when i have set the grid "visible=false" coz i don't want to show the Grid as my manager is not interested but while exporting the details into PDF.
It gives me a error saying
No pages to display


Unknown said...

@ above : hi, this code only works when gridview is visible, btw u can change the visibility on button click


Anonymous said...

Does itextsharp.dll work in .net framework 1.0?


Unknown said...

@Above : iTextSharp version 4 works with .net 1 or 1.1


Anonymous said...

Resources these as the 1 you mentioned right here will be incredibly useful to myself! I will publish a hyperlink to this web page on my personal blog. I am certain my site guests will discover that fairly helpful.


Anonymous said...

Hi Amit,

Thanks for providing this code.
I get the following error "the name HTMLParser does not exist in the current context"

for this line:
HtmlParser.Parse(Doc, xmlReader);

I used the latest dll 5.1.2

Any help would be much appreciated,
Kathy@sanico.ca


Unknown said...

@kathy:

Have you added these namespace?

using iTextSharp.text;
using iTextSharp.text.html;


vidyasagarreddy said...

thnq........itz working


vidyasagarreddy said...

:)


krishna said...

Nice post, But this is not displaying proper columns when too much columns in my Datagrid. PDF page's width doesn't extending according to columns size. its reduce the columns size.

After all this is nice post can be helpful.


sajjad said...

This comment has been removed by a blog administrator.


Anonymous said...

I pay a quick visit each day some websites and websites to read posts, however this blog gives quality based content.


Anonymous said...

Hi Amit
Iam Vani,
a)when i use sort expression in Template field it is not working....????
getting error in
//form.Controls[0].RenderControl(hTextWriter);//
b)Removing sort expression in template field it is working fine..


Anonymous said...

nice post by http://csharpdotnetfreak.blogspot.com


Anonymous said...

Export GridView to pdf in C#


Anonymous said...

thank you for the code it work very nice, but if i add a new records with a nother language else english it Appears in the GridView but not Appears in the pdf exported file .

plz help


Find More Articles