Thursday 14 November 2013

Export Gridview to PDF

Sometimes we need to export the gridview as pdf. I am using iTextShart to export the gridview to PDF.
Click Here to download iTextSharp.

First add attribute
EnableEventValidation="false"
 to your @Page directive in aspx page.


Second add the following method to your code behind page.

public override void VerifyRenderingInServerForm(Control control)
        {
            /* Verifies that the control is rendered */
        }


Third now add the following code on your Export button click.

                Response.ContentType = "application/pdf";
                Response.AddHeader("content-disposition", "attachment;filename=InstituteReport.pdf");
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                StringWriter sw = new StringWriter();
                HtmlTextWriter hw1 = new HtmlTextWriter(sw);
                Label lblHead = new Label();
                lblHead.Text = "<img src='" + Server.MapPath("~/images/logo.png") + "' height='25'
                width='75'></img>
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                lblHead.RenderControl(hw1);
                HtmlTextWriter hw2 = new HtmlTextWriter(sw);
                Label lblBr = new Label();
                lblBr.Text = "report";
                lblBr.ForeColor = System.Drawing.Color.White;
                lblBr.RenderControl(hw2);
                HtmlTextWriter hw = new HtmlTextWriter(sw);
                GvInstitute.AllowPaging = false;
                GvInstitute.AllowSorting = false;
                GvInstitute.GridLines = GridLines.Both;
                GvInstitute.HeaderRow.Style.Add("font-size", "10px");
                GvInstitute.Style.Add("text-decoration", "none");
                GvInstitute.Style.Add("font-family", "Arial, Helvetica, sans-serif;");
                GvInstitute.Style.Add("font-size", "8px");
                GvInstitute.Columns[0].ItemStyle.Width = Unit.Pixel(10);
                GvInstitute.Columns[0].HeaderStyle.Width = Unit.Pixel(10);
                BindInstitutes(); // To bind the data to Gridview
                GvInstitute.RenderControl(hw);
                StringReader sr = new StringReader(sw.ToString());
                Document pdfDoc = new Document(PageSize.A4, 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();


 

1 comment: