Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Export gridview to pdf in asp.net - Part 58

Suggested Videos 
Part 55 - Custom sorting and paging in gridview
Part 56 - Gridview paging using a dropdownlist
Part 57 - Export gridview to excel in asp.net



In this video, we will discuss about exporting gridview data to PDF. We will be using tblEmployee table for this demo. Please refer to Part 13 by clicking here, if you need the sql script to create and populate these tables.



Step 1: Create an asp.net web application project. 

Step 2: Drag and drop a gridview control and a button control on webform1.aspx. Autoformat the gridview control to use "BrownSugar" scheme. Double click on the button control, to generate click event handler method.

At this point the HTML on webform1.aspx should be as shown below.
<asp:GridView ID="GridView1" runat="server" BackColor="#DEBA84" 
    BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" 
    CellPadding="3" CellSpacing="2">
    <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
    <HeaderStyle BackColor="#A55129" Font-Bold="True" 
        ForeColor="White" />
    <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
    <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
    <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" 
        ForeColor="White" />
    <SortedAscendingCellStyle BackColor="#FFF1D4" />
    <SortedAscendingHeaderStyle BackColor="#B95C30" />
    <SortedDescendingCellStyle BackColor="#F1E5CE" />
    <SortedDescendingHeaderStyle BackColor="#93451F" />
</asp:GridView>
<asp:Button ID="Button1" runat="server" Text="Button" 
onclick="Button1_Click" />

Step 3: To generate PDF documents we will be using open source assembly - iTextSharp.dll. This assembly can be downloaded from http://sourceforge.net/projects/itextsharp.

After you download the assembly, add a reference to it, from your web application.

a) In Solution Explorer, right click on the "References" folder and select "Add Reference"
b) Browse to the folder where you have downloaded the assembly and Click OK.

Step 4: Add the following "USING" statements, in your code-behind file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;

Step 5: Copy and paste the following code. The code is well commented and is self-explanatory.
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        BindGridViewData();
    }
}

// ADO.NET code to retrieve data from database
private void BindGridViewData()
{
    string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
    using (SqlConnection con = new SqlConnection(CS))
    {
        SqlDataAdapter da = new SqlDataAdapter("Select * from tblEmployee", con);
        DataSet ds = new DataSet();
        da.Fill(ds);
        GridView1.DataSource = ds;
        GridView1.DataBind();
    }
}

protected void Button1_Click(object sender, EventArgs e)
{
    int columnsCount = GridView1.HeaderRow.Cells.Count;
    // Create the PDF Table specifying the number of columns
    PdfPTable pdfTable = new PdfPTable(columnsCount);

    // Loop thru each cell in GrdiView header row
    foreach(TableCell gridViewHeaderCell in GridView1.HeaderRow.Cells)
    {
        // Create the Font Object for PDF document
        Font font = new Font();
        // Set the font color to GridView header row font color
        font.Color = new BaseColor(GridView1.HeaderStyle.ForeColor);

        // Create the PDF cell, specifying the text and font
        PdfPCell pdfCell = new PdfPCell(new Phrase(gridViewHeaderCell.Text, font));

        // Set the PDF cell backgroundcolor to GridView header row BackgroundColor color
        pdfCell.BackgroundColor = new BaseColor(GridView1.HeaderStyle.BackColor);

        // Add the cell to PDF table
        pdfTable.AddCell(pdfCell);
    }

    // Loop thru each datarow in GrdiView
    foreach (GridViewRow gridViewRow in GridView1.Rows)
    {
        if (gridViewRow.RowType == DataControlRowType.DataRow)
        {
            // Loop thru each cell in GrdiView data row
            foreach (TableCell gridViewCell in gridViewRow.Cells)
            {
                Font font = new Font();
                font.Color = new BaseColor(GridView1.RowStyle.ForeColor);

                PdfPCell pdfCell = new PdfPCell(new Phrase(gridViewCell.Text, font));

                pdfCell.BackgroundColor = new BaseColor(GridView1.RowStyle.BackColor);

                pdfTable.AddCell(pdfCell);
            }
        }
    }

    // Create the PDF document specifying page size and margins
    Document pdfDocument = new Document(PageSize.A4, 10f, 10f, 10f, 10f);
    
    PdfWriter.GetInstance(pdfDocument, Response.OutputStream);

    pdfDocument.Open();
    pdfDocument.Add(pdfTable);
    pdfDocument.Close();

    Response.ContentType = "application/pdf";
    Response.AppendHeader("content-disposition", 
        "attachment;filename=Employees.pdf");
    Response.Write(pdfDocument);
    Response.Flush();
    Response.End();
}

At this point, run the application and click on the button. The data gets exported to PDF as expected. If you are using Google chrome as your browser, you may get a browser warning stating - this type of file can harm your computer do you want to keep Employees.pdf anyway? This is a know issue with Google chrome. Internet explorer, works fine.

9 comments:

  1. how to set caption or title to the pdf

    ReplyDelete
  2. It work as expected.
    How can I specify some static text on the page that is exported as pdf.
    I want some static information as like header.
    How can I achieve the same.
    Thanks in Advance

    ReplyDelete
  3. i have multiple pages as i did pageindex but while exporting i am getting only 1st page not all pages in export

    ReplyDelete
  4. After applying this code and after creation of pdf sucessfully i cant see data in that pdf file only table is created in that file, just i can see is only EMPTY rows and columns

    ReplyDelete
    Replies
    1. comment this line
      font.Color = new BaseColor(GridView1.RowStyle.ForeColor);

      Delete
  5. Hi This code is working fine when there is plane text in Gridview. But when there is Image in Gridview This is downloading blank PDF File. Is There any solution to Download Gridview with Image.

    ReplyDelete
  6. Hi Venkat,
    How to get all the records when i implement paging on Gridview. Please help me to do this..

    Thanks in Advance...!

    ReplyDelete
  7. Hello, I am using the 2 gridview controls on my page. I have exported them to PDF using PDFPTable along with some chunks and phrases using ITextsharp. Can any one help in making me understand that how can i make a common header and footer in PDF if the data in the PDFPTable exceeds page height.

    Thanks in advance

    ReplyDelete
  8. hello,When I was trying this Header Cell is shown but the Rows cell are not displayed in Converted PDF file, how to resolve it,
    please help me.

    ReplyDelete

It would be great if you can help share these free resources