Thursday, 18 October 2012

Exporting Data from Database to PDF

 

Exporting Data from Database to PDF


This a technique to export data from Database to PDF file. Here is the code snippet to achieve this .. 
Use the following code snippet inside the button click event in a webpage..

You have to download a free Tool called Itextsharp from here

Note: In case of any error include the proper namespace.


using System.Data.SqlClient;

using System.IO;

using iTextSharp.text;

using iTextSharp.text.pdf;

using iTextSharp.text.html.simpleparser;


Code Snippet:


    protected void Button1_Click(object sender, EventArgs e)

    {

    Response.ContentType = "application/pdf";

    Response.AddHeader("content-disposition", "attachment;filename=XYZ.pdf");

    Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);

    StringWriter sw = new StringWriter();

    HtmlTextWriter hw = new HtmlTextWriter(sw);

    //Generating Dynamic Gridview..

    GridView grd = new GridView();

    // Specify the DataSource of the Gridview...

    grd.DataSource = objMaterial.SelectDetails();

    grd.DataBind();

    grd.RenderControl(hw);

    StringReader sr = new StringReader(sw.ToString());

    Document pdfDoc = new Document(PageSize.A2, 8f, 8f, 8f, 8f);

    HTMLWorker htmlparser = new HTMLWorker(pdfDoc);

    PdfWriter.GetInstance(pdfDoc, Response.OutputStream);

    pdfDoc.Open();

    htmlparser.Parse(sr);

    pdfDoc.Close();

    Response.Write(pdfDoc);

    Response.End();

    }

No comments:

Post a Comment

Thank You for Your Comments. We will get back to you soon.

back to top