In this article I will explain with an example, how to export selected (checked)
GridView Rows to
PDF in
ASP.Net.
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
The
GridView consists of three
BoundField columns and one
TemplateField columns.
TemplateField – The TemplateField consists of an ItemTemplate.
ItemTemplate – The
ItemTemplate consists of a
CheckBox.
The Button has been assigned with a OnClick event handler.
<asp:GridView ID="gvCustomers" HeaderStyle-BackColor="#3AC0F2"
RowStyle-BackColor="#A1DCF2"
runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<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 namespace.
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 TOP 10 * 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(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Me.BindGrid()
End If
End Sub
Private Sub BindGrid()
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Dim sql As String = "SELECT TOP 10 * FROM Customers"
Using con As SqlConnection = New SqlConnection(constr)
Using cmd As SqlCommand = New SqlCommand(sql)
Using sda As SqlDataAdapter = New SqlDataAdapter()
cmd.Connection = con
sda.SelectCommand = cmd
Using dt As DataTable = New DataTable()
sda.Fill(dt)
gvCustomers.DataSource = dt
gvCustomers.DataBind()
End Using
End Using
End Using
End Using
End Sub
Exporting selected (checked) GridView Rows to PDF in ASP.Net
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.
Then, FOR Each loop is executed over the
GridView Rows and all the rows for which the corresponding
CheckBox is not checked are hidden by setting the Visible property to False.
Here, 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))
{
//Hide the Column containing CheckBox
gvCustomers.Columns[0].Visible = false;
foreach (GridViewRow row in gvCustomers.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
//Hide the Row if CheckBox is not checked
row.Visible = (row.FindControl("chkSelect")as CheckBox).Checked;
}
}
gvCustomers.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4, 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();
}
}
}
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
VB.Net
Protected Sub ExportToPDF(ByVal sender As Object, ByVal e As EventArgs)
Using sw As StringWriter = New StringWriter()
Using hw As HtmlTextWriter = New HtmlTextWriter(sw)
gvCustomers.Columns(0).Visible = False
For Each row As GridViewRow In gvCustomers.Rows
If row.RowType = DataControlRowType.DataRow Then
row.Visible = (TryCast(row.FindControl("chkSelect"), CheckBox)).Checked
End If
Next
gvCustomers.RenderControl(hw)
Dim sr As StringReader = New StringReader(sw.ToString())
Dim pdfDoc As Document = New Document(PageSize.A4, 10.0F, 10.0F, 10.0F, 0F)
Using memoryStream As MemoryStream = 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
Public Overrides Sub VerifyRenderingInServerForm(control As Control)
' Verifies that the control is rendered
End Sub
Possible Errors
The following error when you click on the Export Button.
RegisterForEventValidation can only be called during Render();
Solution
Screenshots
The Form
Exported PDF
Demo
Downloads