csharp

Export GridView to PDF in ASP.Net Using C#

In this blog, we will learn Export GridView to PDF in ASP.Net C#.
Complete Demo

I decided to write this article especially for Beginners and those who want how to export GridView to PDF in ASP.Net Using C# and also explain export GridView with paging enabled to PDF file in ASP.Net.No need to worry simple way to learn Export GridView to PDF in ASP.Net Using C# with the help of iTextSharp.dll.

Step 1:Before creating the application first create the database and use this database.

create database GridViewExportPdf
use GridViewExportPdf

Step 2: After that create a table named tblEmployee in a database to form we show the records in a Gridview.

create table tblEmployee(
EmployeeId int primary key identity(1,1),
EmployeeName varchar(30),
EmployeeAge int,
EmployeeAddress varchar(40)
)

Step 3: After creating a table enter data into table “tblEmployee”.this screenshot show the record after inserted data into table.

Important PointFirst download the iTextSharp.dll file from given linkDownload iTextSharp.dll file link
This itextsharp.dll which provides some methods to Export Grid view into the pdf file,after that click on your Reference folder and then select add reference after that click on Browse button and add two dll file.
1.itextSharp.dll
2.itextSharp.xmlworker

Step 4: Now create the project as:
“Start” –> “All Programs”- “Microsoft Visual Studio 2012”.
“File” – “New Project” – “C#” – “Empty Project” (to avoid adding a master page).
Give the Project name such as GridViewExportPdf or another as you wish and specify the location.
Then right-click on Solution Explorer – “Add New Item” – “ExportToPdf.aspx” page.
Step 5:Open Default.aspx page and write this code.
Note:First set the EnableEventValidation equal to false.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ExportToPdf.aspx.cs" EnableEventValidation="false" Inherits="GridviewExportPdf.ExportToPdf" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:GridView ID="gridExportToPdf" runat="server" AllowPaging="True" OnPageIndexChanging="gridExportToPdf_PageIndexChanging" HeaderStyle-ForeColor="Blue"
        AlternatingRowStyle-BackColor="Red" AlternatingRowStyle-ForeColor="green" >
        </asp:GridView>

        <br />
        <asp:Button ID="btnExportToPdf" runat="server" Text="Export To PDF" OnClick ="btnExportToPdf_Click" />
    </div>
    </form>
</body>
</html>

Step 6: Open web.config file and Establish a connection with database

Note

  • In initial catalog write Database Name
  • In data source you can simply write (.) /your server name/(local)
  • Integrated security for Authentication
<connectionStrings>
  <add name="DBCS" connectionString="data source=.;initial catalog=GridViewExportPdf;integrated security=true"/>
</connectionStrings>

Step 7: Open “ExportToPdf.aspx.cs” page.Need to import the following NameSpaces.

using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;

Step 8:Write this complete code for bind Gridview and Export GridView to PDF on “ExportToPdf.aspx.cs” page.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
//need to import namespaces
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;

namespace GridviewExportPdf
{
    public partial class ExportToPdf : System.Web.UI.Page
    {

        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString);
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindGrid();

            }
           
        }
        public override void VerifyRenderingInServerForm(Control control)
        {
            //base.VerifyRenderingInServerForm(control);
        }
       //Binding The GridView
        public void BindGrid() 
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("select * from tblEmployee",con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
            con.Close();
            if (ds.Tables[0].Rows.Count > 0)
            {
                gridExportToPdf.DataSource = ds;
                gridExportToPdf.DataBind();
            }
        }
       //Implementing Paging in GridView
        protected void gridExportToPdf_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gridExportToPdf.PageIndex = e.NewPageIndex;
            BindGrid();
        }
     // create the following Method to Export the Grid view to PDF as
     //Below is the code to Export GridView to PDF file with Paging enabled.
         private void ExportGridToPDF()  
         {
              Response.ContentType = "application/pdf";
              Response.AddHeader("content-disposition", "attachment;filename=GridExporttoPdf.pdf");
              Response.Cache.SetCacheability(HttpCacheability.NoCache);
              StringWriter sw = new StringWriter();
              HtmlTextWriter hw = new HtmlTextWriter(sw);
              //To Export all pages
              //GridView is again popoulated after set allowpaging is false
              gridExportToPdf.AllowPaging = false;
              this.BindGrid();
               gridExportToPdf.RenderControl(hw);
                StringReader sr = new StringReader(sw.ToString());
                Document pdfDoc = new Document(PageSize.A2, 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();
                 
             }
       //Now double click on Export button and call the above function on "onclick"as
        protected void btnExportToPdf_Click(object sender, EventArgs e)
        {
            ExportGridToPDF();
        }
    }
}

Screenshot describe result after run the project.
export-gridview-pdf-asp-net-using-c#
export-gridview-pdf-asp-net-using-c#
I hope this article is helpful. Any question and suggestion related to this blog please Contact me.

Leave a Reply

Your email address will not be published. Required fields are marked *