Export GridView to PDF Using Asp.net C#


Many times their is a need in a project's reporting module to Export Gridview into PDF, So by considering the above requirement I decided to write this article especially focusing on beginners and those who want to learn how Export GridView to PDF Using Asp.net C# with the help itextsharp dll.

  •  To Export the Grid view ,we need to use reference of  itextsharp.dll.
  • Download the itextsharp.dll from Internet.

The itextsharp.dll is the free dll available to downlaod which provides the some methods to Export Grid view into the pdf file,after adding the reference ,use following references of itextsharp.dll  as

using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;
 I hope ,you have done it
Now before creating the application, let us create a table named employee in a database to from we show the records in a Gridview ,the table having the following fields (shown in the following image):
I hope you have created the same type of table.
Now create the project as:
  1. "Start" - "All Programs" - "Microsoft Visual Studio 2010".
  2. "File" - "New Project" - "C#" - "Empty Project" (to avoid adding a master page).
  3. Give the Project name such as ExportGridToPDF or another as you wish and specify the location.
  4. Then right-click on Solution Explorer - "Add New Item" - Default.aspx page.
  5. one Buttons, one label and a grid view.

Now let us create function to bind the records to Grid view from Database, If you are beginner and don’t know in details how to bind Grid view from database then refer my following article.

now, for this article create the following function into the default.aspx.cs page to bind the Grid view

  1. private void Bindgrid()  
  2.   {  
  3.       connection();  
  4.       query = "select *from Employee";//not recommended this i have wrtten just for example,write stored procedure for security  
  5.       com = new SqlCommand(query, con);  
  6.       SqlDataReader dr = com.ExecuteReader();  
  7.       GridView1.DataSource = dr;  
  8.       GridView1.DataBind();  
  9.       con.Close();  
  11.   } 
now,call this function on page load as
  1. protected void Button1_Click(object sender, EventArgs e)  
  2.  {  
  3.      ExportGridToword();  
  4.  } 
now run the application,then we can see the following records in Grid view as
Now ,we have record to export into MS office word,let us start coding for our actual requirement..,add the VerifyRenderingInServerForm event after the page load which is required while exporting Grid view to Excel,word and PDF to avoid the run time error which is occurred like as "GridView' must be placed inside a form tag with runat=server."
  1. public override void VerifyRenderingInServerForm(Control control)  
  2.  {  
  3.      //required to avoid the runtime error "  
  4.      //Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server."  
  5.  } 
 Now before creating the function to Export the grid view to PDF add the reference of  itextsharp.dll  by right clicking of solution explorer,after adding the reference the solution explorer will be look like as
now create the following function to Export the Grid view to PDF as
  1. private void ExportGridToPDF()  
  2.   {  
  4.       Response.ContentType = "application/pdf";  
  5.       Response.AddHeader("content-disposition""attachment;filename=Vithal_Wadje.pdf");  
  6.       Response.Cache.SetCacheability(HttpCacheability.NoCache);  
  7.       StringWriter sw = new StringWriter();  
  8.       HtmlTextWriter hw = new HtmlTextWriter(sw);  
  9.       GridView1.RenderControl(hw);  
  10.       StringReader sr = new StringReader(sw.ToString());  
  11.       Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);  
  12.       HTMLWorker htmlparser = new HTMLWorker(pdfDoc);  
  13.       PdfWriter.GetInstance(pdfDoc, Response.OutputStream);  
  14.       pdfDoc.Open();  
  15.       htmlparser.Parse(sr);  
  16.       pdfDoc.Close();  
  17.       Response.Write(pdfDoc);  
  18.       Response.End();  
  19.       GridView1.AllowPaging = true;  
  20.       GridView1.DataBind();  
  21.   } 

Now double click on Export button and call the above function on "onclick"as

  1. protected void Button1_Click(object sender, EventArgs e)  
  2.   {  
  3.       ExportGridToPDF();  
  4.   } 
Now the whole code of Default.aspx.cs page will be as follows
  1. using System;  
  2. using System.Web.UI;  
  3. using System.Configuration;  
  4. using System.Data.SqlClient;  
  5. using System.IO;  
  6. using System.Web;  
  7. using iTextSharp.text;  
  8. using iTextSharp.text.pdf;  
  9. using iTextSharp.text.html.simpleparser;  
  11. public partial class _Default : System.Web.UI.Page  
  12. {  
  13.     private SqlConnection con;  
  14.     private SqlCommand com;  
  15.     private string constr, query;  
  16.     private void connection()  
  17.     {  
  18.         constr = ConfigurationManager.ConnectionStrings["getconn"].ToString();  
  19.         con = new SqlConnection(constr);  
  20.         con.Open();  
  22.     }  
  23.     protected void Page_Load(object sender, EventArgs e)  
  24.     {  
  25.         if (!IsPostBack)  
  26.         {  
  27.             Bindgrid();  
  29.         }  
  30.     }  
  32.     public override void VerifyRenderingInServerForm(Control control)  
  33.     {  
  34.         //required to avoid the runtime error "  
  35.         //Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server."  
  36.     }  
  38.     private void Bindgrid()  
  39.     {  
  40.         connection();  
  41.         query = "select *from Employee";//not recommended this i have wrtten just for example,write stored procedure for security  
  42.         com = new SqlCommand(query, con);  
  43.         SqlDataReader dr = com.ExecuteReader();  
  44.         GridView1.DataSource = dr;  
  45.         GridView1.DataBind();  
  46.         con.Close();  
  48.     }  
  49.     protected void Button1_Click(object sender, EventArgs e)  
  50.     {  
  51.         ExportGridToPDF();  
  52.     }  
  53.     private void ExportGridToPDF()  
  54.     {  
  56.         Response.ContentType = "application/pdf";  
  57.         Response.AddHeader("content-disposition""attachment;filename=Vithal_Wadje.pdf");  
  58.         Response.Cache.SetCacheability(HttpCacheability.NoCache);  
  59.         StringWriter sw = new StringWriter();  
  60.         HtmlTextWriter hw = new HtmlTextWriter(sw);  
  61.         GridView1.RenderControl(hw);  
  62.         StringReader sr = new StringReader(sw.ToString());  
  63.         Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);  
  64.         HTMLWorker htmlparser = new HTMLWorker(pdfDoc);  
  65.         PdfWriter.GetInstance(pdfDoc, Response.OutputStream);  
  66.         pdfDoc.Open();  
  67.         htmlparser.Parse(sr);  
  68.         pdfDoc.Close();  
  69.         Response.Write(pdfDoc);  
  70.         Response.End();  
  71.         GridView1.AllowPaging = true;  
  72.         GridView1.DataBind();  
  73.     }  

Now run the application and click on Export Button ,the following popup is appeared as
Now click on open with option ,then you can see that all Grid view records will be exported into PDF File  as
  • Download the zip file from the attachment for the full source code of an application.
  • change connection string from web.config file as per your server location.


I hope this article is useful for all readers, if you have any suggestion then please contact me including beginners also.

Up Next
    Ebook Download
    View all
    View all