Export GridView to PDF Using iTextSharp Library

Here we will use a GridView with some fields and then export that GridView as a PDF using the iTextSharp library.

Initial Chamber

Step 1

Open Visual Studio 2010 and create an empty website, name it gridviewpdf_demo.

Step 2

In Solution Explorer you will get your empty website, then add a Web Form and SQL Server Database. Use the following procedure.

For Web Form:

    gridviewpdf_demo (your Empty Website): Right-click and Add New Item, Web Form. Name it as  gridviewpdf_demo.aspx.

For SQL Server Database:

    gridviewpdf_demo (your Empty Website): Right-click and Add New Item, then go to SQL Server Database and Add Database inside the App_Data_folder.

Database Chamber

Step 3

In Server Explorer, click on your database (Database.mdf), go to Tables and Add New Table. Create a table as in the following.

Go to Table, then tbl_data (don't Forget to make ID as IS Identity -- True).

design
Design Chamber

Step 4

Now make some design for your application by going to gridviewpdf_demo.aspx and try the following code.

gridviewpdf_demo.aspx

  1. <asp:GridView ID="GridView1" runat="server" AllowPaging="True"   
  2.             AutoGenerateColumns="False" BackColor="White" BorderColor="#999999"   
  3.             BorderStyle="None" BorderWidth="1px" CellPadding="3" DataKeyNames="id"   
  4.             GridLines="Vertical" onpageindexchanging="GridView1_PageIndexChanging1"   
  5.             PageSize="5">  
  6.             <AlternatingRowStyle BackColor="#DCDCDC" />  
  7.             <Columns>  
  8.                 <asp:TemplateField HeaderText="Name">  
  9.                     <EditItemTemplate>  
  10.                         <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("name") %>'></asp:TextBox>  
  11.                     </EditItemTemplate>  
  12.                     <ItemTemplate>  
  13.                         <asp:Label ID="Label1" runat="server" Text='<%# Bind("name") %>'></asp:Label>  
  14.                     </ItemTemplate>  
  15.                 </asp:TemplateField>  
  16.                 <asp:TemplateField HeaderText="Education">  
  17.                     <EditItemTemplate>  
  18.                         <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("education") %>'></asp:TextBox>  
  19.                     </EditItemTemplate>  
  20.                     <ItemTemplate>  
  21.                         <asp:Label ID="Label2" runat="server" Text='<%# Bind("education") %>'></asp:Label>  
  22.                     </ItemTemplate>  
  23.                 </asp:TemplateField>  
  24.                 <asp:TemplateField HeaderText="Email">  
  25.                     <EditItemTemplate>  
  26.                         <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("email") %>'></asp:TextBox>  
  27.                     </EditItemTemplate>  
  28.                     <ItemTemplate>  
  29.                         <asp:Label ID="Label3" runat="server" Text='<%# Bind("email") %>'></asp:Label>  
  30.                     </ItemTemplate>  
  31.                 </asp:TemplateField>  
  32.                 <asp:TemplateField HeaderText="Location">  
  33.                     <EditItemTemplate>  
  34.                         <asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("location") %>'></asp:TextBox>  
  35.                     </EditItemTemplate>  
  36.                     <ItemTemplate>  
  37.                         <asp:Label ID="Label4" runat="server" Text='<%# Bind("location") %>'></asp:Label>  
  38.                     </ItemTemplate>  
  39.                 </asp:TemplateField>  
  40.             </Columns>  
  41.             <FooterStyle BackColor="#CCCCCC" ForeColor="Black" />  
  42.             <HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />  
  43.             <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />  
  44.             <RowStyle BackColor="#EEEEEE" ForeColor="Black" />  
  45.             <SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />  
  46.             <SortedAscendingCellStyle BackColor="#F1F1F1" />  
  47.             <SortedAscendingHeaderStyle BackColor="#0000A9" />  
  48.             <SortedDescendingCellStyle BackColor="#CAC9C9" />  
  49.             <SortedDescendingHeaderStyle BackColor="#000065" />  
  50.         </asp:GridView>  

Your design will look something like the following:

gridview properties

You can show paging by going to GridView properties (press F4) then find Allow Paging and Make it True. Here I made the page size -5, you can select the page size depending on your data.

Code Chamber

Before this coding part you need to download the iTextSharp library from the Souceforge website, here is the link. Just download the file. The file is in Zip format, just unzip the files to a suitable location so that we can easily browse it.

iTextSharp Library download: itextsharp-all-5.5.6

download

After downloading the file, check that you have downloaded the right file or not. For that, look at the following image.

download the right file

Step 5

Now for the server-side coding so that our application works. Open the gridviewpdf_demo.aspx.cs file and write the following given code. But first you need to import the DLL of iTextSharp. For that, go to your empty website gridviewpdf_demo and right-click on it, then Add References.

Now browse to the iTextSharp Zip file and open it. Make sure you got all the unzipped DLL files into your application. See the following image to understand what DLL you need to import.

dll

Now import these namspaces, since it will be needed when we write the code for exporting the GridView to the PDF.

namspaces

It's time for the code. First we bind the GridView, then we will make the code for paging using the GridView event OnPageIndexChanging, then we will write the code for exporting the GridView to the PDF on button click.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using System.Data;  
  8. using System.Data.SqlClient;  
  9. using System.IO;  
  10. using System.Text;  
  11. using iTextSharp.text;  
  12. using iTextSharp.text.html;  
  13. using iTextSharp.text.html.simpleparser;  
  14. using iTextSharp.text.pdf;  
  15.   
  16. public partial class _Default : System.Web.UI.Page  
  17. {  
  18.     protected void Page_Load(object sender, EventArgs e)  
  19.     {  
  20.   
  21.         if (!Page.IsPostBack)  
  22.         {  
  23.             refreshdata();  
  24.         }  
  25.          
  26.   
  27.     }  
  28.   
  29.     // Bind the gridview here  
  30.     public void refreshdata()  
  31.     {  
  32.         SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");  
  33.         SqlCommand cmd = new SqlCommand("select * from tbl_data", con);  
  34.         SqlDataAdapter sda = new SqlDataAdapter(cmd);  
  35.         DataTable dt = new DataTable();  
  36.         sda.Fill(dt);  
  37.         GridView1.DataSource = dt;  
  38.         GridView1.DataBind();    
  39.       
  40.     }  
  41.   
  42.     // Gridview Paging code here  
  43.     protected void GridView1_PageIndexChanging1(object sender, GridViewPageEventArgs e)  
  44.     {  
  45.         GridView1.PageIndex = e.NewPageIndex;  
  46.   
  47.         refreshdata();  
  48.     }  
  49.   
  50.   
  51.     // Exporting Gridview to pdf code here  
  52.     protected void Button1_Click1(object sender, EventArgs e)  
  53.     {  
  54.         Response.ContentType = "application/pdf";  
  55.         Response.AddHeader("content-disposition""attachment;filename=GridViewExport.pdf");  
  56.         Response.Cache.SetCacheability(HttpCacheability.NoCache);  
  57.   
  58.         StringWriter swr = new StringWriter();  
  59.         HtmlTextWriter htmlwr = new HtmlTextWriter(swr);  
  60.         GridView1.AllowPaging = false;  
  61.          refreshdata();  
  62.         GridView1.RenderControl(htmlwr);  
  63.         StringReader srr = new StringReader(swr.ToString());  
  64.         Document pdfdoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);  
  65.         HTMLWorker htmlparser = new HTMLWorker(pdfdoc);  
  66.         PdfWriter.GetInstance(pdfdoc, Response.OutputStream);  
  67.   
  68.         pdfdoc.Open();  
  69.         htmlparser.Parse(srr);  
  70.         pdfdoc.Close();  
  71.   
  72.   
  73.         Response.Write(pdfdoc);  
  74.         Response.End();    
  75.     }  
  76.     public override void VerifyRenderingInServerForm(Control control)  
  77.     {  
  78.          
  79.     }  
  80.   
  81. }  
When you run your code, it will run perfectly, but when you click on the button you will get an error. This error generally occurs when we are exporting a GridView to Word, Excel or PDF because the compiler thinks that the control is not in the form.

error

To solve this problem we will  embed a code below the Button_click event like the following:

Button click

Now run your code, it will work perfectly.

Output Chamber

Now run your code

Output

I hope you will like this. Have a nice day. Thank you for reading.