vb.net

Export GridView to PDF in ASP.Net Using VB.Net

In this blog, we will learn Export GridView to PDF in ASP.Net using VB.Net.
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 VB.Net 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 VB.Net 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.



<!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.

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.SqlClient
Imports System.Configuration
Imports System.IO
Imports iTextSharp.text
Imports iTextSharp.text.html.simpleparser
Imports iTextSharp.text.pdf
Imports iTextSharp.tool.xml

Step 8:Write this complete code for bind Gridview and Export GridView to PDF.

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.SqlClient
Imports System.Configuration
Imports System.IO
Imports iTextSharp.text
Imports iTextSharp.text.html.simpleparser
Imports iTextSharp.text.pdf
Imports iTextSharp.tool.xml

Namespace GridviewExportPdf
    Public Partial Class ExportToPdf
        Inherits System.Web.UI.Page

        Private con As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("DBCS").ConnectionString)

        Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
            If Not IsPostBack Then
                BindGrid()
            End If
        End Sub

        Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
        End Sub

        Public Sub BindGrid()
            con.Open()
            Dim cmd As SqlCommand = New SqlCommand("select * from tblEmployee", con)
            Dim da As SqlDataAdapter = New SqlDataAdapter(cmd)
            Dim ds As DataSet = New DataSet()
            da.Fill(ds)
            con.Close()

            If ds.Tables(0).Rows.Count > 0 Then
                gridExportToPdf.DataSource = ds
                gridExportToPdf.DataBind()
            End If
        End Sub

        Protected Sub gridExportToPdf_PageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
            gridExportToPdf.PageIndex = e.NewPageIndex
            BindGrid()
        End Sub

        Private Sub ExportGridToPDF()
            Response.ContentType = "application/pdf"
            Response.AddHeader("content-disposition", "attachment;filename=GridExporttoPdf.pdf")
            Response.Cache.SetCacheability(HttpCacheability.NoCache)
            Dim sw As StringWriter = New StringWriter()
            Dim hw As HtmlTextWriter = New HtmlTextWriter(sw)
            gridExportToPdf.AllowPaging = False
            Me.BindGrid()
            gridExportToPdf.RenderControl(hw)
            Dim sr As StringReader = New StringReader(sw.ToString())
            Dim pdfDoc As Document = New Document(PageSize.A2, 10F, 10F, 10F, 0F)
            Dim htmlparser As HTMLWorker = New HTMLWorker(pdfDoc)
            PdfWriter.GetInstance(pdfDoc, Response.OutputStream)
            pdfDoc.Open()
            htmlparser.Parse(sr)
            pdfDoc.Close()
            Response.Write(pdfDoc)
            Response.[End]()
        End Sub

        Protected Sub btnExportToPdf_Click(ByVal sender As Object, ByVal e As EventArgs)
            ExportGridToPDF()
        End Sub
    End Class
End Namespace

Screenshot describe result after run the project.
export-gridview-pdf-asp-net-using-vb-net
export-gridview-pdf-asp-net-using-vb-net
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 *