Reader Level:
ARTICLE

Export Gridview Into PDF in ASP.NET

Posted by Neha Sharma Articles | ASP.NET Programming April 06, 2013
Here I will explain how to export a GridView into PDF in ASP.NET.
  • 0
  • 0
  • 17474

Introduction
 
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.
 
Requirement
 
The only requirement is to add the DLL of "ITextSharp" into the software to export the GridView in PDF.
 
Code
 
In code behind add the following namespaces:
 
 
using iTextSharp.text;
 
using iTextSharp.text.pdf;
 
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:
 
 
Response.ContentType = "application/pdf";
 
Response.AddHeader("content-disposition", "attachment;filename=report_grid.pdf");
 
Response.Cache.SetCacheability(HttpCacheability.NoCache);
 
StringWriter s_w = new StringWriter();
 
HtmlTextWriter h_w = new HtmlTextWriter(s_w);
 
gvdetails.AllowPaging = false;
 gvdetails.DataBind();
 
gvdetails.RenderControl(h_w);
 
gvdetails.HeaderRow.Style.Add(
"width", "15%");
 
gvdetails.HeaderRow.Style.Add(
"font-size", "10px");
 
gvdetails.Style.Add(
"text-decoration", "none");
 
gvdetails.Style.Add(
"font-family", "Arial, Helvetica, sans-serif;");
 
gvdetails.Style.Add(
"font-size", "8px");
 
StringReader sr = new StringReader(s_w.ToString());
 Document pdfDoc =
new Document(PageSize.A2, 7f, 7f, 7f, 0f);
 
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
 
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
 
pdfDoc.Open();
 
htmlparser.Parse(sr);
 
pdfDoc.Close();
 
Response.Write(pdfDoc);
 
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:
 
 
public override void VerifyRenderingInServerForm(Control control)
 {
 
    /* Verifies that the control is rendered */
 
}
 
Now save all the work and run the code; it will work better.

Article Extensions
Contents added by javed shaikh on Apr 17, 2013
COMMENT USING

Trending up