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.
To use iTextSharp , we need to add these namspaces in the code behind and itextsharp.dll in Bin folder of Application
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
In next lines of code i m creating a new Document in specified location and opening it for writing
The complete code looks like this
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
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:
Really useful post..But how can I set the font of the document content?
The code did'nt work when we apply paging to the gridview,can u help me on that ?
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 .
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?
nice post
Thanks ur information
it very useful
Small business website design
@Anonymous: read my post here for the paging enabled gridview solution
Here is another article which also includes images:
http://highoncoding.com/Articles/483_Exporting_GridView_to_PDF_Document.aspx
refer
http://www.ashfk.blogspot.com/ click follower ramky
http://www.ashfk.blogspot.com/
Thank's. Really very usefull.
This comment has been removed by a blog administrator.
How to make this to work with datalist?
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!
Thanks. Really good work! I am trying to look deep into the code you provided. Happy Programming!
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!
@ 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
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!
@Jasmine:
Hi
Check html source of your aspx page and check whether runat="server" is present in the asp:GridView tags
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
@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
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
@ 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
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...
@ Talib Ali Khan:
Hi talib , for positioning of columns you can read this article
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?
@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#
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.
@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.
thanks
this is really very helpfull............
Its Really good article...
Thanks -- Vijaya Kadiyala
www.DotNetVJ.com
where i paste the DLL File?
@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
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.
@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"
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.
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
This comment has been removed by a blog administrator.
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!
@noncelafaccio:
Hi noncelafaccio , please refer my below mentioned article to overcome this formatting issue of PDF
Export paging enabled gridview to pdf using iTextSharp
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.
@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();
}
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
@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
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!
your download code does not work. can u rectify?
Thanks!
@Above:
You Can Download the source code from here
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...
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.
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.
nice post mate.....
web design
There is a execelent free component for entire gridview export, print etc. Following link will help.
http://www.softsona.com/SonaGridToolBarPage.aspx
If I want the PDF should have Page Header in every page, What should i do?
Thanks in advance,
Mohamed
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.
hi master, I've tried your code, but I've a cast exception @ the line "HtmlParser.Parse(doc, xmlReader)"
please, can u help me?
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
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
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
Use iTextSharp v4. v5 does not contain HtmlParser.
HtmlParser.Parse(Doc, xmlReader);
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.
I use masterpage.master and inherit from it.The asp page have no tag form and error happen .Can you help me?
i have trouble with the asp page inherit from Masterpage.Master .So it doesn't have any form tag.
Thanks. This code is working properly. It helpful to do my task in the project
hello. thank you very much for letting me comment. very good article I would like more information on this item
You are right.
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...
Thanks for the nice information. I am sure, I will tweet this to my twitter account. This will help a lot of users.
Certainly. I agree with you.
Exact phrase
hii i have a lot of coloumn, what about to make a margin in every header?
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
Hi, its really good article. can anyone help me how to export a nested grid to PDF.
I’ve been visiting your blog for a while now and I always find a gem in your new posts. Thanks for sharing.
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.
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.
THX for sharing
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
@ above : hi, this code only works when gridview is visible, btw u can change the visibility on button click
Does itextsharp.dll work in .net framework 1.0?
@Above : iTextSharp version 4 works with .net 1 or 1.1
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.
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
@kathy:
Have you added these namespace?
using iTextSharp.text;
using iTextSharp.text.html;
thnq........itz working
:)
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.
This comment has been removed by a blog administrator.
I pay a quick visit each day some websites and websites to read posts, however this blog gives quality based content.
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..
nice post by http://csharpdotnetfreak.blogspot.com
Export GridView to pdf in C#
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
Post a Comment