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]
Related articles
- Export Gridview Data to Excel in ASP.NET (surajdeshpande.wordpress.com)
- Export Gridview Data to Word Document in ASP.NET (surajdeshpande.wordpress.com)
- Export Gridview Data to CSV File in ASP.NET (surajdeshpande.wordpress.com)
Very useful information. Keep it up…
LikeLike
Thanks Satish.
LikeLike
Loved this article very much. Thanks man.
LikeLike
nice article usefull
LikeLike
Thanks for this article , but i am getting this error “The document has no pages.”
LikeLike
Hi,
Did you try running the code from this post? Are you getting errors in it?
Regards,
Suraj
LikeLike
How to add image header and water mark ?
LikeLike
Please refer following link:
http://stackoverflow.com/questions/6041718/adding-image-watermark-to-pdf-while-creating-it-using-itextsharp
LikeLike