In this web programming tutorial we will learn that how we can export grid view data into a pdf file in asp.net using c#.
For exporting the GridView to PDF I am using the iTextSharp Library. You will need to Add Reference for the iTextSharp Library in your Website.
Then import the following Namespaces
By default the iTextSharp Library does not support background color of table cells or table rows
Hence when you render it as PDF your GridView is rendered without any formatting.
Recently I read an article on hamang.net where the author has provided the snippet to modify the iTextSharp so that it exports the HTML with background color.
For this tutorial, I have already modified the iTextSharp Library DLL so that the GridView is rendered with all the background color used. You can refer the code for exporting GridView to PDF below
To avoid the error you will need to add this event which ensures that the GridView is Rendered before exporting.
For exporting the GridView to PDF I am using the iTextSharp Library. You will need to Add Reference for the iTextSharp Library in your Website.
Then import the following Namespaces
using iTextSharp.text; using iTextSharp.text.pdf; using iTextSharp.text.html; using iTextSharp.text.html.simpleparser;code for .cs file
By default the iTextSharp Library does not support background color of table cells or table rows
Hence when you render it as PDF your GridView is rendered without any formatting.
Recently I read an article on hamang.net where the author has provided the snippet to modify the iTextSharp so that it exports the HTML with background color.
For this tutorial, I have already modified the iTextSharp Library DLL so that the GridView is rendered with all the background color used. You can refer the code for exporting GridView to PDF below
protected void btnExportPDF_Click(object sender, EventArgs e) { Response.ContentType = "application/pdf"; Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf"); Response.Cache.SetCacheability(HttpCacheability.NoCache); StringWriter sw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(sw); GridView1.AllowPaging = false; GridView1.DataBind(); GridView1.RenderControl(hw); StringReader sr = new StringReader(sw.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(sr); pdfDoc.Close(); Response.Write(pdfDoc); Response.End(); }
To avoid the error you will need to add this event which ensures that the GridView is Rendered before exporting.
public override void VerifyRenderingInServerForm(Control control) { /* Verifies that the control is rendered */ }
1 comment:
Export GridView data to Excel spreadsheet
Post a Comment