connectseekers.com

Monday, 9 June 2014

Code to Export GridView to PDF in Asp.Net Using C# and Vb.Net

6/09/2014 - By Pranav Singh 19

Today’s time PDF is playing one of the most important role in our life. So whenever we develop any asp.net application on that case we always face some situation where we needed to export our data in PDS format.
So in this article I will show you how you can export the GridView bind data in PDF format using third party control iTextsharp.


So for this article first you needed to download the iTextsharplibrary. Download iTextsharp and extract the zip file. In this file you will three dll files. So for completing the task add the reference of itextsharp-dll-core directory dll.

Now after this create a new asp.net application and add the blow code in your .aspx page.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="PDFExport.aspx.cs" Inherits="ProjectDemo_Asp.et.PDFExport" %>

<!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>Code to Export GridView to PDF in Asp.Net Using C# and Vb.Net</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
            BorderStyle="Solid" EmptyDataText="There are no data records to display.">
            <Columns>
                <asp:BoundField DataField="author_name" HeaderText="NAME" />
                <asp:BoundField DataField="publisher_name" HeaderText="PUBLISHER NAME" />
                <asp:BoundField DataField="publication_year" HeaderText="PUBLISH YEAR" />
                <asp:BoundField DataField="retail_price" HeaderText="PRICE" />
            </Columns>
            <HeaderStyle BackColor="#66CCFF" />
        </asp:GridView>
        <br />
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click"
            Text="Export To PDF" />
   
    </div>
    </form>
</body>
</html>

Now we will go to code page and add the below code.

C#.Net
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.OleDb;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;//This name space present in "itextsharp-dll-core"
namespace ProjectDemo_Asp.et
{
    public partial class PDFExport : System.Web.UI.Page
    {
        public string connectionstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\bookstore.mdb;Persist Security Info=False;";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                DataTable _objdt = new DataTable();
                _objdt = GetDataFromDataBase();
                if (_objdt.Rows.Count > 0)
                {
                    GridView1.DataSource = _objdt;
                    GridView1.DataBind();
                }
            }
        }

        /// <summary>
        /// Function for binding retribing the data from database
        /// </summary>
        /// <returns></returns>
        public DataTable GetDataFromDataBase()
        {
            DataTable _objdt = new DataTable();
            string querystring = "select * from Books;";
            OleDbConnection _objcon = new OleDbConnection(connectionstring);
            OleDbDataAdapter _objda = new OleDbDataAdapter(querystring, _objcon);
            _objcon.Open();
            _objda.Fill(_objdt);
            return _objdt;
        }
        /// <summary>
        /// Click event to export the grivview data into pdf format
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Button1_Click(object sender, EventArgs e)
        {
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment;filename=report_grid.pdf");
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            StringWriter s_w = new StringWriter();
            HtmlTextWriter h_w = new HtmlTextWriter(s_w);
            GridView1.AllowPaging = false;
            /*binding data to grid view*/
            DataTable _objdt = new DataTable();
            _objdt = GetDataFromDataBase();
            GridView1.DataSource = _objdt;
            GridView1.DataBind();
            GridView1.RenderControl(h_w);
            GridView1.HeaderRow.Style.Add("width", "15%");
            GridView1.HeaderRow.Style.Add("font-size", "10px");
            GridView1.Style.Add("text-decoration", "none");
            GridView1.Style.Add("font-family", "Arial, Helvetica, sans-serif;");
            GridView1.Style.Add("font-size", "8px");
            StringReader sr = new StringReader(s_w.ToString());
            Document pdfDoc = new Document(PageSize.A2, 7f, 7f, 7f, 0f);
            HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
            PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
            pdfDoc.Open();
            htmlparser.Parse(sr);
            pdfDoc.Close();
            Response.Write(pdfDoc);
            Response.End();
        }
        public override void VerifyRenderingInServerForm(Control control)
        {
            /* Verifies that the control is rendered */

        }
    }
}

VB.Net
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Data
Imports System.Data.OleDb
Imports System.IO
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Imports iTextSharp.text.html.simpleparser
'This name space present in "itextsharp-dll-core"
Namespace ProjectDemo_Asp.et
    Partial Public Class PDFExport
        Inherits System.Web.UI.Page
        Public connectionstring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\bookstore.mdb;Persist Security Info=False;"
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
            If Not IsPostBack Then
                Dim _objdt As New DataTable()
                _objdt = GetDataFromDataBase()
                If _objdt.Rows.Count > 0 Then
                    GridView1.DataSource = _objdt
                    GridView1.DataBind()
                End If
            End If
        End Sub

        ''' <summary>
        ''' Function for binding retribing the data from database
        ''' </summary>
        ''' <returns></returns>
        Public Function GetDataFromDataBase() As DataTable
            Dim _objdt As New DataTable()
            Dim querystring As String = "select * from Books;"
            Dim _objcon As New OleDbConnection(connectionstring)
            Dim _objda As New OleDbDataAdapter(querystring, _objcon)
            _objcon.Open()
            _objda.Fill(_objdt)
            Return _objdt
        End Function
        ''' <summary>
        ''' Click event to export the grivview data into pdf format
        ''' </summary>
        ''' <param name="sender"></param>
        ''' <param name="e"></param>
        Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
            Response.ContentType = "application/pdf"
            Response.AddHeader("content-disposition", "attachment;filename=report_grid.pdf")
            Response.Cache.SetCacheability(HttpCacheability.NoCache)
            Dim s_w As New StringWriter()
            Dim h_w As New HtmlTextWriter(s_w)
            GridView1.AllowPaging = False
            'binding data to grid view

            Dim _objdt As New DataTable()
            _objdt = GetDataFromDataBase()
            GridView1.DataSource = _objdt
            GridView1.DataBind()
            GridView1.RenderControl(h_w)
            GridView1.HeaderRow.Style.Add("width", "15%")
            GridView1.HeaderRow.Style.Add("font-size", "10px")
            GridView1.Style.Add("text-decoration", "none")
            GridView1.Style.Add("font-family", "Arial, Helvetica, sans-serif;")
            GridView1.Style.Add("font-size", "8px")
            Dim sr As New StringReader(s_w.ToString())
            Dim pdfDoc As New Document(PageSize.A2, 7.0F, 7.0F, 7.0F, 0.0F)
            Dim htmlparser As New HTMLWorker(pdfDoc)
            PdfWriter.GetInstance(pdfDoc, Response.OutputStream)
            pdfDoc.Open()
            htmlparser.Parse(sr)
            pdfDoc.Close()
            Response.Write(pdfDoc)
            Response.[End]()
        End Sub
        Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
            ' Verifies that the control is rendered


        End Sub
    End Class
End Namespace

Now run the application without adding the below mention code function.

        public override void VerifyRenderingInServerForm(Control control)
        {
            /* Verifies that the control is rendered */

        }



Click on export button, you will get below mention error.



Now add the code and run the application



DOWNLOAD



About the Author

We are the group of people who are expertise in different Microsoft technology like Asp.Net,MVC,C#.Net,VB.Net,Windows Application,WPF,jQuery,Javascript,HTML. This blog is designed to share the knowledge.

Get Updates

Subscribe to our e-mail newsletter to receive updates.

Share This Post

19 comments:

  1. Dear Reader Please let me know you comment.

    ReplyDelete
  2. Thanks sir.,
    very helpful for me. This explanation must be provided by microsoft ...

    ReplyDelete
  3. Really useful and I am glad and appreciate that shared your valuable knowledge

    ReplyDelete
  4. Its always interesting to know about some different ideas

    ReplyDelete
  5. Nice post with lot of information and it is very helpful..Thanks for sharing

    ReplyDelete
  6. This comment has been removed by a blog administrator.

    ReplyDelete
  7. Excellent post with useful information..And the combination of elements are very different and unique

    ReplyDelete
    Replies
    1. Thanks for your valuable comment. keep visiting

      Delete
  8. This comment has been removed by a blog administrator.

    ReplyDelete
  9. This comment has been removed by a blog administrator.

    ReplyDelete
  10. Nice article. I like this post. it is very useful.Thanks for sharing.
    digital marketing training in chennai

    ReplyDelete
  11. This comment has been removed by a blog administrator.

    ReplyDelete
  12. This comment has been removed by a blog administrator.

    ReplyDelete
  13. This comment has been removed by a blog administrator.

    ReplyDelete
  14. This comment has been removed by a blog administrator.

    ReplyDelete

Please let me know your view

Free Ebooks


About Us

We are the group of people who are expertise in different Microsoft technology like Asp.Net,MVC,C#.Net,VB.Net,Windows Application,WPF,jQuery,Javascript,HTML. This blog is designed to share the knowledge.

Contact Us

For writing article in this website please send request by your

GMAIL ID: dotnetpools@gmail.com
Email Id : contact@aspdotnet-pools.com

Bugs and Suggestions

As we all know that this website is for sharing knowledge and providing proper solution. So while reading the article is you find any bug or if you have any suggestion please mail us at contact@aspdotnet-pools.com.

Partners


Top jQuery Plugins

Global Classified : Connectseekers.com
© 2014
back to top