Export Paging Enabled GridView To PDF Using ITextSharp

Export Paging Enabled GridView To PDF Using ITextSharp C# VB.NET In ASP.NET. In my previous post Export GridView to pdf , i explained how to write Grid View contents to a PDF file , but this code has some bugs

1. Code doesn't work if paging is enabled in GridView

2. Columns become of variable width in PDF documnt as shown in the image below




To fix these problems we need to write code without using xmlTextReader and HtmlParser.
for this we need to create a table in PDF document and then fill the cells of table from GridView
And the new html and codebehind would become like this

<%@ Page Language="C#" AutoEventWireup="true"CodeFile="Default.aspx.cs"
Inherits="_Default" %><!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"AutoGenerateColumns="False"AllowPaging="true"
PageSize="5"DataSourceID="SqlDataSource1"><
Columns><asp:BoundField DataField="Name
"HeaderText="Name"SortExpression="Name" />
<asp:BoundField DataField="Location"HeaderText="Location"
SortExpression="Location" /></Columns></asp:GridView>

<asp:SqlDataSource ID="SqlDataSource1"runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>
"SelectCommand="SELECT [Name], [Location] FROM [Test]">
</asp:SqlDataSource></div><br />

<asp:Button ID="btnExport" runat="server"
OnClick="btnExport_Click"Text="Export to PDF" />
</form></body></html>


And the code behind goes like this
protected void btnExport_Click(object sender, EventArgs e)
{
int columnCount = GridView1.Columns.Count;
int rowCount = GridView1.Rows.Count;
int tableRows = rowCount + 3;
iTextSharp.text.Table grdTable=
new iTextSharp.text.Table(columnCount, tableRows);
grdTable.BorderWidth = 1;
grdTable.BorderColor = new Color(0, 0, 255);
grdTable.Cellpadding = 5;
grdTable.Cellspacing = 5;
Cell c1 = new Cell("Exporting paging enabled GridView to PDF example");
c1.Header = true;c1.Colspan = 2;
grdTable.AddCell(c1);
Cell c2 = new Cell("By amiT jaiN , amit_jain_online@yahoo.com");
c2.Colspan = 2;
grdTable.AddCell(c2);
grdTable.AddCell("Name");
grdTable.AddCell("Location");
for (int rowCounter = 0;
rowCounter < rowCount; rowCounter++)
{for (int columnCounter = 0;columnCounter < columnCount; columnCounter++)
{string strValue =GridView1.Rows[rowCounter].Cells[columnCounter].Text;
grdTable.AddCell(strValue);
}
}
Document Doc = new Document();
PdfWriter.GetInstance(Doc, Response.OutputStream);
Doc.Open();Doc.Add(grdTable);
Doc.Close();
Response.ContentType = "application/pdf";
Response.AddHeader
("content-disposition", "attachment; filename=AmitJain.pdf");
Response.End();


PDF created would be like this




If you like this post than join us or share

14 comments:

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

Anonymous said...

El link no funciona




LuisNet MCP.NET


Anonymous said...

Hi Amit

Am i wrong, or this code neither works when you have multiple pages?

Anyway, good work,

Tom


Anonymous said...

Hi amit, I had tried your code and other also, but when I click on button then in Adobe reader it shows that the file is damaged.. what to do?

Thanks..

Kaushal


0 said...

Hi,

this article is not work.


Anonymous said...

Hi,
Do you have sample code for export to microsoft word using c#?


Anonymous said...

Hi Amit,

Thanks a lot for your technical stuff.I really need this article.

In my scenario.From database i have to read data and i have to populate data into Microsoft word or Notepad.
For example User has submited his details into database(name,education details. professional career experience etc) from this i have to create like a CV or Resume .

Advanced thanks for your help.

Looking forward for your help.

Thanks
Raj


Anonymous said...

Hello amit, it is working properly but i am not getting the data of my gridview in pdf file. please help me.


Unknown said...

@Above: Plz let me know what error u r getting or if u can show me ur code to look into


Anonymous said...

Hello amit ,
i am not getting error ,bt it is not showing data of mygridview in pdf file, i am sending you the code:-

protected void btnPDF_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();

}


Unknown said...

@Above: What is your gridview id ? , is it gridView1 ?


Anonymous said...

yes it is GridView1....


Viki said...

hi amit,
im also facing the same prob.im able to open the pdf but my gridvalues are not displayed.plz help


Unknown said...

@Viki : Please email me your aspx page and aspx.cs page , so that i can look into the code and problem

csharpdotnetfreak@gmail.com


Find More Articles