Download iTextSharp and XmlWorkerHelper Libraries
In order to install
iTextSharp and
XmlWorkerHelper library from
Nuget, please refer the following articles.
Database
This example uses Northwind database. You can download it using the link given below.
HTML Markup
The following HTML Markup consists of:
GridView - For displaying data.
Columns
There are three BoundField columns for displaying the fields.
Button – For exporting the GridView to
PDF file.
The Button has been assigned with a OnClick event handler.
<asp:GridView ID="gvCustomers" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
RowStyle-BackColor="#A1DCF2" AlternatingRowStyle-BackColor="White" AlternatingRowStyle-ForeColor="#000"
runat="server" AutoGenerateColumns="false" AllowPaging="true" OnPageIndexChanging="OnPageIndexChanging">
<Columns>
<asp:BoundField DataField="ContactName" HeaderText="Contact Name" ItemStyle-Width="150px" />
<asp:BoundField DataField="City" HeaderText="City" ItemStyle-Width="100px" />
<asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-Width="100px" />
</Columns>
</asp:GridView>
<br />
<asp:Button ID="btnExport" runat="server" Text="Export To PDF" OnClick="ExportToPDF" />
Namespaces
You will need to import the following namespaces.
C#
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;
VB.Net
Imports System.IO
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Imports iTextSharp.tool.xml
Binding the GridView
Inside the Page_Load event handler, the BindGrid method is called which populates the GridView with the records from Customers table of the Northwind database.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
string sql = "SELECT * FROM Customers";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(sql))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
gvCustomers.DataSource = dt;
gvCustomers.DataBind();
}
}
}
}
}
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not IsPostBack Then
Me.BindGrid()
End If
End Sub
Private Sub BindGrid()
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Dim sql As String = "SELECT * FROM Customers"
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand(sql)
Using sda As New SqlDataAdapter()
cmd.Connection = con
sda.SelectCommand = cmd
Using dt As New DataTable()
sda.Fill(dt)
gvCustomers.DataSource = dt
gvCustomers.DataBind()
End Using
End Using
End Using
End Using
End Sub
Implement Paging in GridView
Inside the OnPageIndexChanging event handler, the PageIndex property of the GridView is set with the new PageIndex and the BindGrid method is called.
C#
protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvCustomers.PageIndex = e.NewPageIndex;
this.BindGrid();
}
VB.Net
Protected Sub OnPageIndexChanging(sender As Object, e As GridViewPageEventArgs)
gvCustomers.PageIndex = e.NewPageIndex
Me.BindGrid()
End Sub
Exporting GridView with Paging Enabled to PDF
When
Export button is clicked, the
PDF is exported.
The
StringWriter and
HtmlTextWriter class objects are created and the
GridView is exported to an
HTML string using
StringReader class.
Here, the
GridView is again populated with data from database after setting
AllowPaging to false.
Then, the
GridView is rendered into an
HTML string using
RenderControl which accepts
HtmlTextWriter class object as parameter.
After that, the generated
HTML is added to the
iTextSharp PDF document using
Document class.
Finally,
PDF document is opened and the
GridView data is written using
ParseXHtml method of
XmlWorkerHelper class which converts it to
PDF document and saves it to the
MemoryStream class object.
C#
protected void ExportToPDF(object sender, EventArgs e)
{
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter hw = new HtmlTextWriter(sw))
{
//To Export all pages
gvCustomers.AllowPaging = false;
this.BindGrid();
gvCustomers.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A2, 10f, 10f, 10f, 0f);
using (MemoryStream memoryStream = new MemoryStream())
{
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, sr);
pdfDoc.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Write(pdfDoc);
Response.End();
}
}
}
}
VB.Net
Protected Sub ExportToPDF(ByVal sender As Object, ByVal e As EventArgs)
Using sw As New StringWriter()
Using hw As New HtmlTextWriter(sw)
'To Export all pages
gvCustomers.AllowPaging = False
Me.BindGrid()
gvCustomers.RenderControl(hw)
Dim sr As New StringReader(sw.ToString())
Dim pdfDoc As New Document(PageSize.A2, 10.0F, 10.0F, 10.0F, 0F)
Using memoryStream As New MemoryStream()
Dim writer As PdfWriter = PdfWriter.GetInstance(pdfDoc, Response.OutputStream)
pdfDoc.Open()
XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, sr)
pdfDoc.Close()
Response.ContentType = "application/pdf"
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf")
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.Write(pdfDoc)
Response.End()
End Using
End Using
End Using
End Sub
Screenshots
The Form
Exported PDF
Demo
Downloads