Saturday, 9 March 2013

ASP.Net : Export Gridview in PDF | Neha Sharma



Introduction:

Export your daily report in pdf is daily need for any reporting software or application. The same happened when I was working on a project the project was about to finished but sudden anyhow a requirement came to export whole data/report which is displaying in gridview in to pdf.
I was shocked how to add.. when it’s about to finish, but after many try I got the reply that is here :

Requirement:

The only requirement is to add dll of “ITextSharp”  in to the software  to export  the gridview in pdf.

Code:

In code behind add below name spaces :


using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;


Add a gridview and bind that with the database. Add a button to “export in pdf”.
Double click on the button “export in pdf” and write below 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 below override method to override your control because in this case when you click to export gridview in to pdf complier never find your gridview in to the form tag :
public override void VerifyRenderingInServerForm(Control control)
    {
        /* Verifies that the control is rendered */
    }

Now save all work and run the code it ll look better.

For any query or need dll you can commment here.

Thanks

1 comment:

  1. Hi Neha,

    How to display Announcement or comments using database without using gridview?

    --selvi

    ReplyDelete

Which Game Engine you should choose | Neha Sharma

Unity3D and Unreal Engine are only 2 Game engine which executes an indispensable position in Game Industry. The choice of the engine must ...