Sunday, 18 September 2016

How to export GridView data into PDF using iTextSharp in asp.net with C#

In this article, we are going to learn how to export GridView data into PDF file using itextsharp in asp.net with C#. First, you need to download iTextSharp dll from the internet. Click on the below link to download the dll.

https://github.com/itext/itextsharp

Related Article

  1. How to generate PDF file using iTextSharp in C#
  2. Insert an image into PDF using iTextSharp with C# (C-Sharp)
  3. How to add meta information of PDF file using iTextSharp with C-Sharp
  4. How to extract images from a pdf file using C#.Net

Once file is downloaded, extract it, now you will find 6 more .rar file. Again extract itextsharp-dll-core.rar file, after that add reference of itextsharp.dll to your project.

In Designer File

In designer file create a GridView control to display data and two Button control for exporting GridView data in PDF file. First button will export complete GridView data and second button export current page data. Below is the designer file code.

Gridview designer for exporting data into pdf
<asp:GridView ID="grdStudent" runat="server" CellPadding="4" BackColor="#CCCCCC"
    BorderColor="#999999" BorderStyle="Solid" BorderWidth="2px" CellSpacing="2" ForeColor="Black"
    AutoGenerateColumns="false" AllowPaging="true" PageSize="3" OnPageIndexChanging="grdStudent_PageIndexChanging">
    <FooterStyle BackColor="#CCCCCC" />
    <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
    <PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />
    <RowStyle BackColor="White" ForeColor="Black" />
    <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
    <SortedAscendingCellStyle BackColor="#F1F1F1" />
    <SortedAscendingHeaderStyle BackColor="#808080" />
    <SortedDescendingCellStyle BackColor="#CAC9C9" />
    <SortedDescendingHeaderStyle BackColor="#383838" />
    <Columns>
        <asp:BoundField DataField="StudentName" HeaderText="Student Name" />
        <asp:BoundField DataField="Physics" HeaderText="Physics" />
        <asp:BoundField DataField="Chemistry" HeaderText="Chemistry" />
        <asp:BoundField DataField="Maths" HeaderText="Maths" />
    </Columns>
</asp:GridView>
<br />
<asp:Button ID="btnExportAll" runat="server" Text="Export To PDF" BackColor="#990000"
    BorderStyle="Solid" BorderWidth="2px" Font-Bold="True" ForeColor="White" Height="30px"
    BorderColor="#333333" OnClick="btnExportAll_Click" />
<asp:Button ID="btnExportCurrent" runat="server" Text="Export Current Page" BackColor="#990000"
    BorderStyle="Solid" BorderWidth="2px" Font-Bold="True" ForeColor="White" Height="30px"
    BorderColor="#333333" OnClick="btnExportCurrent_Click" />

In Code-Behind File

Add below nampespaces.

using System.Data;
using iTextSharp.text;
using iTextSharp.text.pdf;

DataSource to Bind GridView

Below is the BindGrid method to bind GridView on Page_load event.

public DataTable BindGrid()
{
    //Creating a DataTable
    DataTable dt = new DataTable();
    //adding Columns to DataTable
    dt.Columns.Add("StudentName", typeof(string));
    dt.Columns.Add("Physics", typeof(Int32));
    dt.Columns.Add("Chemistry", typeof(Int32));
    dt.Columns.Add("Maths", typeof(Int32));
    //Adding rows to DataTable
    dt.Rows.Add("Vijay", 90, 80, 85);
    dt.Rows.Add("Rahul", 75, 85, 88);
    dt.Rows.Add("John", 75, 85, 95);
    dt.Rows.Add("Mary", 95, 85, 90);
    return dt;
}

Complete C# Code

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        grdStudent.DataSource = BindGrid();
        grdStudent.DataBind();
    }
}

public DataTable BindGrid()
{
    //Creating a DataTable
    DataTable dt = new DataTable();
    //adding Columns to DataTable
    dt.Columns.Add("StudentName", typeof(string));
    dt.Columns.Add("Physics", typeof(Int32));
    dt.Columns.Add("Chemistry", typeof(Int32));
    dt.Columns.Add("Maths", typeof(Int32));
    //Adding rows to DataTable
    dt.Rows.Add("Vijay", 90, 80, 85);
    dt.Rows.Add("Rahul", 75, 85, 88);
    dt.Rows.Add("John", 75, 85, 95);
    dt.Rows.Add("Mary", 95, 85, 90);
    return dt;
}

protected void btnExportAll_Click(object sender, EventArgs e)
{
    grdStudent.AllowPaging = false;
    grdStudent.DataSource = BindGrid();
    grdStudent.DataBind();
    GeneratePDF();
}

public void GeneratePDF()
{
    PdfPTable table = new PdfPTable(grdStudent.Columns.Count);

    for (int i = 0; i < grdStudent.Columns.Count; i++)
    {
        string cellText = Server.HtmlDecode(grdStudent.Columns[i].HeaderText);
        PdfPCell cell = new PdfPCell();
        cell.Phrase = new Phrase(cellText, new Font(Font.FontFamily.TIMES_ROMAN, 10, 1, new BaseColor(System.Drawing.ColorTranslator.FromHtml("#ffffff"))));
        cell.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#990000"));
        //cell.Phrase = new Phrase(cellText, new Font(Font.FontFamily.TIMES_ROMAN, 10, 1, new BaseColor(grdStudent.HeaderStyle.ForeColor)));
        //cell.BackgroundColor = new BaseColor(grdStudent.HeaderStyle.BackColor);
        cell.HorizontalAlignment = Element.ALIGN_CENTER;
        cell.PaddingBottom = 5;
        table.AddCell(cell);
    }
    for (int i = 0; i < grdStudent.Rows.Count; i++)
    {
        if (grdStudent.Rows[i].RowType == DataControlRowType.DataRow)
        {
            for (int j = 0; j < grdStudent.Columns.Count; j++)
            {
                string cellText = Server.HtmlDecode(grdStudent.Rows[i].Cells[j].Text);
                PdfPCell cell = new PdfPCell();
                //cell.Phrase = new Phrase(cellText, new Font(Font.FontFamily.TIMES_ROMAN, 10, 1, new BaseColor(grdStudent.RowStyle.ForeColor)));
                //cell.BackgroundColor = new BaseColor(grdStudent.RowStyle.BackColor);
                cell.Phrase = new Phrase(cellText, new Font(Font.FontFamily.TIMES_ROMAN, 10, 1, new BaseColor(System.Drawing.ColorTranslator.FromHtml("#000000"))));
                cell.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#ffffff"));
                cell.BackgroundColor = new BaseColor(grdStudent.RowStyle.BackColor);
                cell.HorizontalAlignment = Element.ALIGN_CENTER;
                cell.PaddingBottom = 5;
                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=Student_Grid_pdf.pdf");
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.Write(pdfDoc);
    Response.End();
}

protected void btnExportCurrent_Click(object sender, EventArgs e)
{
    GeneratePDF();
}

protected void grdStudent_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    grdStudent.PageIndex = e.NewPageIndex;
    grdStudent.DataSource = BindGrid();
    grdStudent.DataBind();
}

Below is the pdf file generated.

Exported gridview into pdf
Share:

0 comments:

Post a Comment

Email Subscription

Subscribe to our newsletter to get the latest articles directly into your inbox

Blog Archive

BUY FROM AMAZON

Ads By Chitika