Search This Blog

Thursday 31 July 2014

How to export GridView data to PDF document in ASP.NET with C#



You could download iTextSharp.dll class library here

http://sourceforge.net/projects/itextsharp/

Then open your project and include that iTextSharp.dll class library.


Designer source code:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default"
                                                          EnableEventValidation="false" %> 
<!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 align="center"><h2><b>Export Gridview to PDF document</b></h2></div>
            <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Export" />
    <br />
    <div>
        <asp:GridView ID="gvExport" runat="server" EnableViewState="False" Width="60%" AllowPaging="false" AutoGenerateColumns="false">
            <HeaderStyle BackColor="#93a31d" Width="200px" ForeColor="White" Height="25px" />
            <AlternatingRowStyle BackColor="#dce0bc"/>
            <Columns>
            <asp:BoundField DataField="ProductID" HeaderText="Product ID" />
            <asp:BoundField DataField="ProductName" HeaderText="Product Name" />
            <asp:BoundField DataField="SupplierID" HeaderText="Supplier ID" />
            <asp:BoundField DataField="CategoryID" HeaderText="Category ID" />
            <asp:BoundField DataField="QuantityPerUnit" HeaderText="Quantity Per Unit" />
            </Columns>
         </asp:GridView>

    </div>
    </form>
</body>
</html>

Here you have to use following namespaces
using System.IO;
using System.Net;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;

C# code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Net;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser; 
public partial class _Default : System.Web.UI.Page
{
    SqlConnection conn = new SqlConnection("Data Source=SPIDER;Initial Catalog=Northwind;Integrated Security=True"); 
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindData();
        }
    } 
    private  void BindData()
    {
        DataSet ds = new DataSet();
        conn.Open();
        string cmdstr = " Select Top 10 ProductID, ProductName, SupplierID, CategoryID,  QuantityPerUnit from Products ";
        SqlDataAdapter adp = new SqlDataAdapter(cmdstr,conn);
        adp.Fill(ds);
        gvExport.DataSource = ds;
        gvExport.DataBind();
        conn.Close();
    }
     
    protected void Button1_Click(object sender, EventArgs e)
    {      
iTextSharp.text.Table table = new iTextSharp.text.Table(gvExport.Columns.Count);
        table.Cellpadding = 2;
        table.Width = 100;
        BindData();
        //Transfer rows from GridView to table
        for (int i = 0; i < gvExport.Columns.Count; i++)
        {
            string cellText = Server.HtmlDecode
                                      (gvExport.Columns[i].HeaderText); 
            iTextSharp.text.Cell cell = new iTextSharp.text.Cell(cellText);
            cell.BackgroundColor = new Color(System.Drawing
                                           .ColorTranslator.FromHtml("#93a31d"));
            table.AddCell(cell);
        }

        for (int i = 0; i < gvExport.Rows.Count; i++)
        {
            if (gvExport.Rows[i].RowType == DataControlRowType.DataRow)
            {
                for (int j = 0; j < gvExport.Columns.Count; j++)
                {
                    string cellText = Server.HtmlDecode
                                      (gvExport.Rows[i].Cells[j].Text);
                    iTextSharp.text.Cell cell = new iTextSharp.text.Cell(cellText);

                    //Set Color of Alternating row
                    if (i % 2 != 0)
                    {
                        cell.BackgroundColor = new Color(System.Drawing.ColorTranslator.FromHtml("#dce0bc"));
                    }
                    table.AddCell(cell);
                }
            }
        }

        Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
        PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
        pdfDoc.Open();
        pdfDoc.Add(table);
        pdfDoc.Close();
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition""attachment;" +
                                       "filename=GridView.pdf");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.Write(pdfDoc);
        Response.End();
    } 
}


No comments:

Post a Comment