Grid View to Pdf Exporting using ITextSharp dll


Introduction:

In one of the previous articles we demonstrated how to export a GridView to excel. In this article we will demonstrate how to export GridView to PDF format using the ITextSharp library.

Creating the Entity Class:

Let's create a simple entity class "Customer" and populate it with some dummy data. The Customer class looks like the following:

01  public class Customer
02     {
03         private string _firstName;
04         private string _lastName;
05         private string _email;
06         public string FirstName
07         {
08             get { return _firstName; }
09             set { _firstName = value; }
10         }
11         public string LastName
12         {
13             get { return _lastName; }
14             set { _lastName = value; }
15         }
16         public string FullName
17         {
18             get { return _firstName + " " + _lastName; }
19         }
20         public string Email
21         {
22             get { return _email; }
23             set { _email = value; }
24         }
25     }


Now, let's create a GridView control and poppulate it with the dummy Customer objects.

01 <asp:GridView BackColor="Green" ID="gvCustomers" runat="server" />
02  private void BindData()
03         {
04             gvCustomers.DataSource = GetCustomers();
05             gvCustomers.DataBind();
06         }
07         private List<Customer> GetCustomers()
08         {
09             List<Customer> customers = new List<Customer>();
10             for (int i = 1; i <= 20; i++)
11             {
12                 Customer customer = new Customer();
13                 customer.FirstName = "FirstName" + i;
14                 customer.LastName = "LastName" + i;
15                 customer.Email = "Email" + i;
16                 customers.Add(customer);
17             }
18             return customers;
19         }


The above code will populate the GridView with dummy Customers. Take a look at the screenshot of the GridView below:



Now, let's try to export this GridView to PDF.

How *NOT* to Export a GridView to PDF:

Here is the code which is used to export GridView to PDF.

01   protected void WrongExportGridViewToPDF(object sender, EventArgs e)
02         {
03             Response.Clear();
04              
05             StringWriter sw = new StringWriter();
06             HtmlTextWriter htw = new HtmlTextWriter(sw);
07             gvCustomers.RenderControl(htw);
08              
09             Response.ContentType = "application/pdf";
10             Response.AddHeader("content-disposition", "attachment; filename=MypdfFile.pdf");
11             Response.Write(sw.ToString());
12             Response.End();
13         }


When you export the GridView to PDF using the above code it will seem that the export is taking place correctly but when you try to open the file you will realize that the file is corrupted. Although this particular code works when exporting to Excel or Text files this code will fail when exporting to PDF files. To export GridView to PDF we will need to use a third party library ITextSharp. Let's see how we can use this library.

Downloading the ITextSharp Library:

You can download the ITextSharp library using the following link:

ITextSharp Library

The library is also included in the download sample files.

Exporting the GridView to Excel Using ITextSharp and ResponseOutputStream:

We are going to use the ITextSharp library to write the document to the ResponeOutputStream. Let's take a look at the code:

01  protected void ExportToPDFClick(object sender, EventArgs e)
02         {
03             Response.Clear();
04             StringBuilder sb = new StringBuilder();
05             StringWriter sw = new StringWriter(sb);
06             HtmlTextWriter htw = new HtmlTextWriter(sw);
07             gvCustomers.RenderControl(htw);
08             Response.ContentType = "application/pdf";
09             Response.AddHeader("content-disposition", "attachment; filename=MypdfFile.pdf");
10             Document document = new Document();
11             PdfWriter.GetInstance(document, Response.OutputStream);
12             document.Open();
13             string html = sb.ToString();
14             XmlTextReader reader = new XmlTextReader(new StringReader(html));
15             HtmlParser.Parse(document, reader);
16             document.Close();
17             sw.Close();
18             Response.Flush();
19             Response.End();
20         }


The above code is using the Document object which represents a Pdf document. The GridView is rendered into the HtmlTextWriter. The HtmlTextWriter uses the support of StringWriter and StringBuilder to get the HTML for the GridView control. The PdrWriter.getInstance is used to set the Document instance to the Stream which in this case is the Response Stream. The HtmlParser class is responsible for parsing the rendered GridView HTML. This is responsible for creating a table display for the PDF document. If we omit the use of HtmlParser then the raw HTML will be displayed in the Pdf document.

Take a look at the screenshot below which shows the GridView as a Pdf Document:



As, you can see the Pdf document is poorly styled and the table cells are of variable length. Let's see how we can improve the Table cell rendering.

Creating Pdf Document Using ITextSharp Tables:

The ITextSharp library includes the Table class which is used to create Tables in PdfDocuments. We will use the Table class to improve our display.

The button click will fire the following event:

1   protected void ExportCollectionToPDFClick(object sender,EventArgs e)
2         {
3             ExportToPDFCollection(new string[] { "FirstName", "LastName", "FullName" });
4         }


The ExportToPDFCollection method is responsible for creating the Table using the Customer collection. It takes a single parameter which is the names of the columns we will want to export to the Pdf document.

Here is the implementation of the ExportToPDFCollection method:

01  private void ExportToPDFCollection(string[] columnNames)
02         {
03             List<Customer> customers = GetCustomers();
04             int noOfColumns = columnNames.Length;
05             int noOfRows = customers.Count;
06             string propertyValue = String.Empty;
07              
08             iTextSharp.text.Table table = new iTextSharp.text.Table(noOfColumns, noOfRows);
09             table.BackgroundColor = new iTextSharp.text.Color(gvCustomers.BackColor);
10              
11             table.AutoFillEmptyCells = true;
12             for (int rowNo = 0; rowNo < noOfRows; rowNo++)
13             {
14                 for (int columnNo = 0; columnNo < noOfColumns; columnNo++)
15                 {
16                     propertyValue = GetPropertyValue(customers[rowNo], columnNames[columnNo]);
17                     table.AddCell(propertyValue, new Point(rowNo, columnNo));
18                 }
19             }
20             Document document = new Document();
21             PdfWriter.GetInstance(document, Response.OutputStream);
22             document.Open();
23             document.Add(table);
24             document.Close();
25             Response.ContentType = "application/pdf";
26             Response.AddHeader("content-disposition", "attachment; filename=MypdfFile.pdf");
27             Response.End();
28         }


The above code creates the Table and append cells to the Table. Each cell is populated with the particular propertyname of the Customer class. The GetPropertyValue method uses reflection to get the value from the property.

1   private string GetPropertyValue(Customer customer,string propertyName)
2         {
3             PropertyInfo property = customer.GetType().GetProperty(propertyName);
4             return property.GetValue(customer, null).ToString();
5         }


Here is the result:



Although the resultant Pdf document is not pretty but you can always make adjustments to make it better. Also note that the cells are property listed.

Conclusion:

In this article we learned how to export GridView to Pdf. We discussed different ways of performing this operation. In the future articles we will try to demonstrate how to customize the display of the exported Pdf document.

[Download Sample]

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites