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 Chamber
Step 4
Now make some design for your application by going to gridviewpdf_demo.aspx and try the following code.
gridviewpdf_demo.aspx
- <asp:GridView ID="GridView1" runat="server" AllowPaging="True"
- AutoGenerateColumns="False" BackColor="White" BorderColor="#999999"
- BorderStyle="None" BorderWidth="1px" CellPadding="3" DataKeyNames="id"
- GridLines="Vertical" onpageindexchanging="GridView1_PageIndexChanging1"
- PageSize="5">
- <AlternatingRowStyle BackColor="#DCDCDC" />
- <Columns>
- <asp:TemplateField HeaderText="Name">
- <EditItemTemplate>
- <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("name") %>'></asp:TextBox>
- </EditItemTemplate>
- <ItemTemplate>
- <asp:Label ID="Label1" runat="server" Text='<%# Bind("name") %>'></asp:Label>
- </ItemTemplate>
- </asp:TemplateField>
- <asp:TemplateField HeaderText="Education">
- <EditItemTemplate>
- <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("education") %>'></asp:TextBox>
- </EditItemTemplate>
- <ItemTemplate>
- <asp:Label ID="Label2" runat="server" Text='<%# Bind("education") %>'></asp:Label>
- </ItemTemplate>
- </asp:TemplateField>
- <asp:TemplateField HeaderText="Email">
- <EditItemTemplate>
- <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("email") %>'></asp:TextBox>
- </EditItemTemplate>
- <ItemTemplate>
- <asp:Label ID="Label3" runat="server" Text='<%# Bind("email") %>'></asp:Label>
- </ItemTemplate>
- </asp:TemplateField>
- <asp:TemplateField HeaderText="Location">
- <EditItemTemplate>
- <asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("location") %>'></asp:TextBox>
- </EditItemTemplate>
- <ItemTemplate>
- <asp:Label ID="Label4" runat="server" Text='<%# Bind("location") %>'></asp:Label>
- </ItemTemplate>
- </asp:TemplateField>
- </Columns>
- <FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
- <HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
- <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
- <RowStyle BackColor="#EEEEEE" ForeColor="Black" />
- <SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
- <SortedAscendingCellStyle BackColor="#F1F1F1" />
- <SortedAscendingHeaderStyle BackColor="#0000A9" />
- <SortedDescendingCellStyle BackColor="#CAC9C9" />
- <SortedDescendingHeaderStyle BackColor="#000065" />
- </asp:GridView>
Your design will look something like the following:
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
After downloading the file, check that you have downloaded the right file or not. For that, look at the following image.
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.
Now import these namspaces, since it will be needed when we write the code for exporting the GridView to the PDF.
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.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using System.Data;
- using System.Data.SqlClient;
- using System.IO;
- using System.Text;
- using iTextSharp.text;
- using iTextSharp.text.html;
- using iTextSharp.text.html.simpleparser;
- using iTextSharp.text.pdf;
-
- public partial class _Default : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
-
- if (!Page.IsPostBack)
- {
- refreshdata();
- }
-
-
- }
-
-
- public void refreshdata()
- {
- SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");
- SqlCommand cmd = new SqlCommand("select * from tbl_data", con);
- SqlDataAdapter sda = new SqlDataAdapter(cmd);
- DataTable dt = new DataTable();
- sda.Fill(dt);
- GridView1.DataSource = dt;
- GridView1.DataBind();
-
- }
-
-
- protected void GridView1_PageIndexChanging1(object sender, GridViewPageEventArgs e)
- {
- GridView1.PageIndex = e.NewPageIndex;
-
- refreshdata();
- }
-
-
-
- protected void Button1_Click1(object sender, EventArgs e)
- {
- Response.ContentType = "application/pdf";
- Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf");
- Response.Cache.SetCacheability(HttpCacheability.NoCache);
-
- StringWriter swr = new StringWriter();
- HtmlTextWriter htmlwr = new HtmlTextWriter(swr);
- GridView1.AllowPaging = false;
- refreshdata();
- GridView1.RenderControl(htmlwr);
- StringReader srr = new StringReader(swr.ToString());
- Document pdfdoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
- HTMLWorker htmlparser = new HTMLWorker(pdfdoc);
- PdfWriter.GetInstance(pdfdoc, Response.OutputStream);
-
- pdfdoc.Open();
- htmlparser.Parse(srr);
- pdfdoc.Close();
-
-
- Response.Write(pdfdoc);
- Response.End();
- }
- public override void VerifyRenderingInServerForm(Control control)
- {
-
- }
-
- }
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.
To solve this problem we will embed a code below the Button_click event like the following:
Now run your code, it will work perfectly.
Output Chamber I hope you will like this. Have a nice day. Thank you for reading.