Pages

Sunday, June 3, 2012

GridView to Pdf using iTextSharp

Just Download iTextsharp lib. from http://sourceforge.net/projects/itextsharp/
Add 1 form in your project named as "pdf" then copy following design & Code behind code &  replace it in your code.





Currently we have taken 1 gridview & button on form.
You can bind your data to gridview as you required. I have just created dataset manually & assign it to gridview

Design Form
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="pdf.aspx.cs" Inherits="pdf" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
   <form id="form1" runat="server">
  <div>
      <asp:GridView ID="GridView1" runat="server">
      </asp:GridView>
      <asp:Button ID="btnExportToPdf" runat="server" OnClick="btnExportToPdf_Click"
          Text="Pdf" /></div>
</form>
</body>
</html>

Code Behind File
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
using System.Collections.Generic;

public partial class pdf : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GridView1.DataSource = GetData();
            GridView1.DataBind();
        }
    }

    public DataSet GetData()
    {
        DataSet ds = new DataSet();
        DataTable dt = new DataTable("Product");
        DataRow dr;
        dt.Columns.Add(new DataColumn("Price", typeof(Int32)));
        dt.Columns.Add(new DataColumn("DisCount", typeof(Int32)));
        dt.Columns.Add(new DataColumn("SellPrice", typeof(Int32)));
        for (int i = 1; i <= 10; i++)
        {
            dr = dt.NewRow();
            dr[0] = i;
            dr[1] = i * 2;
            dr[2] = 1 * 3;
            dt.Rows.Add(dr);
        }
        ds.Tables.Add(dt);
        Session["dt"] = dt;
        return ds;
    }

    protected void btnExportToPdf_Click(object sender, EventArgs e)
    {
        MyPage tmpPage = new MyPage();
        HtmlForm form = new HtmlForm();

        form.Controls.Add(GridView1);

        tmpPage.Controls.Add(form);
        StringWriter sw = new StringWriter();
        HtmlTextWriter htmlWriter = new HtmlTextWriter(sw);
        form.Controls[0].RenderControl(htmlWriter);
        string htmlContent = sw.ToString();
        Document document = new Document();
        // step 2:
        // we create a writer that listens to the document
        // and directs a PDF-stream to a file
        PdfWriter.GetInstance(document, new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.Desktop)+ "\\Sample.pdf", FileMode.Create));
       

        // step 3: we open the document
        document.Open();

        // step 4: we add a paragraph to the document

        //document.Add(new Paragraph(htmlContent.ToString()));

        System.Xml.XmlTextReader _xmlr = new System.Xml.XmlTextReader(new StringReader(htmlContent));

        //HtmlParser.Parse(document, _xmlr);
        using (TextReader sReader = new StringReader(sw.ToString()))
        {
            List<IElement> list = HTMLWorker.ParseToList(sReader, new StyleSheet());
            foreach (IElement elm in list)
            {
                document.Add(elm);
            }
        }

        // step 5: we close the document
        document.Close();

        //  Response.Write(document);
        string Path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\Sample.pdf";
        ShowPdf(Path);
    }

    private void ShowPdf(string strS)
    {
        Response.ClearContent();
        Response.ClearHeaders();
        Response.ContentType = "application/pdf";
        Response.AddHeader("Content-Disposition", "attachment; filename=" + strS);
        Response.TransmitFile(strS);
        Response.End();
        Response.Flush();
        Response.Clear();
    }

}

 We have created 1 more class file
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

/// <summary>
/// Summary description for MyPage
/// </summary>
public class MyPage : Page
{
    public override void VerifyRenderingInServerForm(Control control)
    {
        GridView grid = control as GridView;
        if (grid != null && grid.ID == "GridView1")
            return;
        else
            base.VerifyRenderingInServerForm(control);

    }
}

 Happy Coding !!

No comments:

Post a Comment