Export Gridview to PDF in ASP.NET using iTextSharp Library


To export gridview to PDF, we need to refer third party library called “iTextSharp”.

About iTextSharp:

iTextSharp is is a C# port of iText, an open source Java library for PDF generation and manipulation. It can be used to create PDF documents from scratch, to convert XML to PDF  etc.

It can be downloaded from here:

https://sourceforge.net/projects/itextsharp/

Let’s start coding part now.

1. Once you download iTextSharp library, add a reference to your project as shown below.

I have used version “5.4.3” of iTextSharp in this example.

2. Here is a sample aspx code snippet for gridview. I have used “Northwind” sample database as an example. It can be downloaded from here. Also make sure to set the page attribute EnableEventValidation=”false” otherwise you will see error message like

“RegisterForEventValidation can only be called during Render()”


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ITextSharpPDFGeneration.Default" EnableEventValidation="false"  %>


<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" AutoGenerateColumns="False" DataKeyNames="EmployeeID" AllowPaging="True" AllowSorting="True" HeaderStyle-ForeColor="blue">
 <Columns>
 <asp:BoundField DataField="EmployeeID" HeaderText="EmployeeID" ReadOnly="True" InsertVisible="False" SortExpression="EmployeeID"></asp:BoundField>
 <asp:BoundField DataField="FirstName" HeaderText="FirstName" SortExpression="FirstName"></asp:BoundField>
 <asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName"></asp:BoundField>
 <asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address"></asp:BoundField>
 <asp:BoundField DataField="City" HeaderText="City" SortExpression="City"></asp:BoundField>
 <asp:BoundField DataField="Country" HeaderText="Country" SortExpression="Country"></asp:BoundField>
 </Columns>
 </asp:GridView>
 <asp:SqlDataSource runat="server" ID="SqlDataSource1" ConnectionString='<%$ ConnectionStrings:NorthwindConnectionString %>' SelectCommand="SELECT [EmployeeID], [Title], [FirstName], [LastName], [BirthDate], [Address], [City], [Country] FROM [Employees]"></asp:SqlDataSource>

3. Set the connection string in the web.config file.


<connectionStrings>
 <add name="NorthwindConnectionString" connectionString="Data Source=localhost;Initial Catalog=Northwind;Persist Security Info=True;User ID=sa;Password=123456"
 providerName="System.Data.SqlClient" />
 </connectionStrings>

4. Add reference to following namespaces in the code behind.


using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;

5. Add an asp button control to aspx page and on the “onClick” event of the button, write the following code.


 Response.ClearContent();
 Response.ContentType = "application/pdf";
 Response.AddHeader("content-disposition", "attachment; filename=PDFDoc.pdf");
 Response.Cache.SetCacheability(HttpCacheability.NoCache);

 StringWriter stringWriter = new StringWriter();
 HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);

 GridView1.AllowPaging = false;
 GridView1.AllowCustomPaging = false;
 GridView1.AllowSorting = false;
 GridView1.DataBind();

 GridView1.RenderControl(htmlTextWriter);

 StringReader stringReader = new StringReader(stringWriter.ToString());
 Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
 HTMLWorker htmlWorker = new HTMLWorker(pdfDoc);
 PdfWriter.GetInstance(pdfDoc, Response.OutputStream);

 pdfDoc.Open();
 htmlWorker.Parse(stringReader);
 pdfDoc.Close();

 Response.Write(pdfDoc);
 Response.End();

6. Once it’s done, you need to add a special method to code behind page called “VerifyRenderingInServerForm”.
It is used to avoid the exception like “Control of type must be placed inside a form tag with runat=server.”.
“VerifyRenderingInServerForm” method will make sure that the control is rendered.


public override void VerifyRenderingInServerForm(Control control)
 {
 /* Verifies that the control is rendered */
 }

7. Once all done, rebuild the solution and run it. On the page, When you click on the button, it will export the gridview data to PDF file.

Source Code Download

Github [Repository link]

Box.com [Direct Link to Rar file]

Advertisements

13 thoughts on “Export Gridview to PDF in ASP.NET using iTextSharp Library

  1. Pingback: Export Gridview Data to Excel in ASP.NET | A Programming Blog

  2. Pingback: Export Gridview Data to Word Document in ASP.NET | A Programming Blog

  3. Pingback: Export Gridview Data to CSV File in ASP.NET | A Programming Blog

  4. Pingback: Import/Insert Excel file into SQL Server using ASP.NET | Satish Ratnaparkhi's blog

  5. Pingback: Import / Insert Excel file into SQL Server using ASP.NET | Satish Ratnaparkhi's blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s