Tuesday, 24 January 2012

Export asp.net gridview to pdf file in c#

Export gridview to pdf in c#
Download itextsharp.dll
.CS Code:
 

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using iTextSharp.text.pdf;

using iTextSharp.text.html;

using iTextSharp.text.html.simpleparser;
using System.IO;
using iTextSharp.text;


public partial class pdf_genration : System.Web.UI.Page
{
    DataSet ds=new DataSet();
    protected void Page_Load(object sender, EventArgs e)
    {
 
        
        ds.ReadXml(MapPath("Regis.xml"));
        GridView1.DataSource = ds;
        //DataGrid1.DataSource = ds;
        GridView1.DataBind();
    }
    public override void VerifyRenderingInServerForm(Control control)// this Event is must for Rendring
    {

    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Clear(); //this clears the Response of any headers or previous output
        Response.Buffer = true; //ma
        Response.ContentType = "application/pdf";

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

        Response.Cache.SetCacheability(HttpCacheability.NoCache);

        StringWriter sw = new StringWriter();

        HtmlTextWriter hw = new HtmlTextWriter(sw);

        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();  
    }
}


.aspx Code:
Output:
When You Click On ExportGridview Button All gridview Data is bind In pdffile
Like this:

No comments :