In this article I will explain how to export selected (checked) GridView Rows to PDF file in ASP.Net using C# and VB.Net.
The GridView consists of a CheckBox column to select / check the GridView Rows and when the Button is clicked then only the selected (checked) Rows are exported to PDF file.
 
Database
For this article I am making use of the Microsoft’s Northwind Database. Download and install instructions are provided in the link below
 
HTML Markup
The HTML Markup consists of an ASP.Net GridView and a Button. The first column is a TemplateField consisting of a CheckBox to select rows.
<asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White" 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 namespaces
C#
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
 
VB.Net
Imports System.IO
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports iTextSharp.text
Imports iTextSharp.text.html.simpleparser
Imports iTextSharp.text.pdf
 
 
Binding the GridView
Below is the code to bind the GridView with records from the Customers table of the Northwind database
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        this.BindGrid();
    }
}
 
private void BindGrid()
{
    string strConnString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(strConnString))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT TOP 10 * FROM Customers"))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
                    GridView1.DataSource = dt;
                    GridView1.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 strConnString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As New SqlConnection(strConnString)
        Using cmd As New SqlCommand("SELECT TOP 10 * FROM Customers")
            Using sda As New SqlDataAdapter()
                cmd.Connection = con
                sda.SelectCommand = cmd
                Using dt As New DataTable()
                    sda.Fill(dt)
                    GridView1.DataSource = dt
                    GridView1.DataBind()
                End Using
            End Using
        End Using
    End Using
End Sub
 
Exported selected (checked) GridView Rows to PDF in ASP.Net
 
Export selected (checked) GridView Rows to PDF in ASP.Net
Below is the code for exporting selected (checked) GridView rows to PDF file.
First a 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.
Finally the GridView is rendered into an HTML string using HtmlTextWriter and then the generated HTML is added to the iTextSharp PDF Document, which is then export to PDF through the Response Stream.
Note: The iTextSharp DLL supplied with the code sample of this article has been modified to allow GridView Styles, Colors and Formatting. Thus if you use any other copy of iTextSharp, the GridView Styles, Colors and Formatting won’t be rendered in the exported PDF.
 
C#
protected void ExportToPDF(object sender, EventArgs e)
{
    using (StringWriter sw = new StringWriter())
    {
        using (HtmlTextWriter hw = new HtmlTextWriter(sw))
        {
 
            //Hide the Column containing CheckBox
            GridView1.Columns[0].Visible = false;
            foreach (GridViewRow row in GridView1.Rows)
            {
                if (row.RowType == DataControlRowType.DataRow)
                {
                    //Hide the Row if CheckBox is not checked
                    row.Visible = (row.FindControl("chkSelect") as CheckBox).Checked;
                }
            }
 
            GridView1.RenderControl(hw);
            StringReader sr = new StringReader(sw.ToString());
            Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
            HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
            PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
            pdfDoc.Open();
            htmlparser.Parse(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(sender As Object, e As EventArgs)
    Using sw As New StringWriter()
        Using hw As New HtmlTextWriter(sw)
 
            'Hide the Column containing CheckBox
            GridView1.Columns(0).Visible = False
            For Each row As GridViewRow In GridView1.Rows
                If row.RowType = DataControlRowType.DataRow Then
                    'Hide the Row if CheckBox is not checked
                    row.Visible = TryCast(row.FindControl("chkSelect"), CheckBox).Checked
                End If
            Next
 
            GridView1.RenderControl(hw)
            Dim sr As New StringReader(sw.ToString())
            Dim pdfDoc As New Document(PageSize.A4, 10.0F, 10.0F, 10.0F, 0.0F)
            Dim htmlparser As New HTMLWorker(pdfDoc)
            PdfWriter.GetInstance(pdfDoc, Response.OutputStream)
            pdfDoc.Open()
            htmlparser.Parse(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 Sub
 
Public Overrides Sub VerifyRenderingInServerForm(control As Control)
    ' Verifies that the control is rendered
End Sub
 
Exported selected (checked) GridView Rows to PDF in ASP.Net
 
If you get the following error, please refer my article RegisterForEventValidation can only be called during Render()
RegisterForEventValidation can only be called during Render();
 
Demo
 
Downloads

Download Code