Export Gridview Into PDF in ASP.NET

Exporting a daily report in PDF is a daily need for any reporting software or application. The same happened when I was working on a project; the project was about to finish but suddenly a requirement somehow was received to export the entire data/report being displayed in a GridView in to PDF.
I was shocked; how to add it when it's about to finish, but after many attempts I got the reply that is here.
The only requirement is to add the DLL of "ITextSharp" into the software to export the GridView in PDF.
In code behind add the following namespaces:

  1. using iTextSharp.text;  
  2. using iTextSharp.text.pdf;  
  3. using iTextSharp.text.html.simpleparser;
Add a GridView and bind with the database. Add a button to "Export in PDF".
Double-click on the button "Export in PDF" and write the following code there:
  1. Response.ContentType = "application/pdf";  
  2. Response.AddHeader("content-disposition""attachment;filename=report_grid.pdf");  
  3. Response.Cache.SetCacheability(HttpCacheability.NoCache);  
  4. StringWriter s_w = new StringWriter();  
  5. HtmlTextWriter h_w = new HtmlTextWriter(s_w);  
  6. gvdetails.AllowPaging = false;  
  7. gvdetails.DataBind();  
  8. gvdetails.RenderControl(h_w);  
  9. gvdetails.HeaderRow.Style.Add("width""15%");  
  10. gvdetails.HeaderRow.Style.Add("font-size""10px");  
  11. gvdetails.Style.Add("text-decoration""none");  
  12. gvdetails.Style.Add("font-family""Arial, Helvetica, sans-serif;");  
  13. gvdetails.Style.Add("font-size""8px");  
  14. StringReader sr = new StringReader(s_w.ToString());  
  15. Document pdfDoc = new Document(PageSize.A2, 7f, 7f, 7f, 0f);  
  16. HTMLWorker htmlparser = new HTMLWorker(pdfDoc);  
  17. PdfWriter.GetInstance(pdfDoc, Response.OutputStream);  
  18. pdfDoc.Open();  
  19. htmlparser.Parse(sr);  
  20. pdfDoc.Close();  
  21. Response.Write(pdfDoc);  
  22. Response.End();
And add the following override method to override your control because in this case when you click to export the GridView into PDF format the complier never finds your GridView in the form tag:
  1. public override void VerifyRenderingInServerForm(Control control)  
  2. {  
  3.     /* Verifies that the control is rendered */  
  4. }
Now save all the work and run the code; it will work better.

Similar Articles