In this article I will explain with an example, how to export
GridView to PDF with custom columns widths using
iTextSharp in
ASP.Net using C# and VB.Net.
For exporting GridView to PDF iTextSharp library is used.
Download iTextSharp Library
You can download the iTextSharp library from the following link.
Note: You will need to add the reference of
iTextSharp library in your project.
Database
For this article I am making use of the Microsoft’s Northwind Database. You can download it from here.
HTML Markup
The HTML Markup consists of following controls:
GridView – For displaying data.
Columns
GridView consists of three BoundField columns.
Properties
AllowPaging – For enabling paging in the GridView control.
Events
The GridView has been assigned with an OnPageIndexChanging event handler.
RadioButtonList – For capturing user input.
The RadioButtonList consists of two ListItem.
Button – For exporting GridView data to PDF.
The Button has been assigned with an OnClick event handler.
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false"
AllowPaging="true" OnPageIndexChanging="OnPaging">
<Columns>
<asp:BoundField ItemStyle-Width="200px" DataField="CustomerID" HeaderText="Customer Id" />
<asp:BoundField ItemStyle-Width="100px" DataField="City" HeaderText="City" />
<asp:BoundField ItemStyle-Width="50px" DataField="Country" HeaderText="Country" />
</Columns>
</asp:GridView>
<br />
<asp:RadioButtonList ID="rbPaging" runat="server">
<asp:ListItem Text="Yes" Value="true">Print Current Page</asp:ListItem>
<asp:ListItem Text="No" Value="false" Selected="True">Print All Pages</asp:ListItem>
</asp:RadioButtonList>
<br />
<asp:Button ID="btnExportPDF" runat="server" Text="Export To PDF" OnClick="ExportToPDF" />
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using iTextSharp.text;
using iTextSharp.text.pdf;
VB.Net
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Binding the GridView
Inside the Page_Load event handler, the BindGrid method is called.
BindGrid
Inside the
BindGrid method,
GridView is populated with records fetched from the
Customers Table of the
Northwind database.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid()
{
string query = "SELECT CustomerID, City, Country FROM Customers";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlDataAdapter sda = new SqlDataAdapter(query, con))
{
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 query As String = "SELECT CustomerID, City, Country FROM Customers"
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(constr)
Using sda As SqlDataAdapter = New SqlDataAdapter(query, con)
Using dt As DataTable = New DataTable()
sda.Fill(dt)
gvCustomers.DataSource = dt
gvCustomers.DataBind()
End Using
End Using
End Using
End Sub
Implement Paging in GridView
Inside the
OnPageIndexChanging event handler, the
PageIndex property of the
GridView is updated with the new Page Number which was clicked.
Finally, the
GridView is populated using the
BindGrid method which in-turn displays the new
GridView page.
C#
protected void OnPaging(object sender, GridViewPageEventArgs e)
{
gvCustomers.PageIndex = e.NewPageIndex;
this.BindGrid();
}
VB.Net
Protected Sub OnPaging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
gvCustomers.PageIndex = e.NewPageIndex
Me.BindGrid()
End Sub
Exporting GridView to PDF
When
Export button is clicked, the
AllowPaging property of the
GridView is set based on the RadioButton selection and the
BindGrid method is called.
Then, the PdfPTable class object is created and new table is created.
A FOR EACH loop is executed over the GridView columns and the content of
GridView HeaderRow cells are set to the dynamically created cell using
PdfPCell object.
The Width and BackgroundColor are also set and each cell is added to the Table.
Another FOR EACH loop is executed over the
GridView columns and a check is performed if the
RowType is
DataRow.
And all the contents of DataRow cells are set to each cell and added to Table.
Then, the Document class object is created for creating PDF document and its properties are set.
After that the Response class properties are set.
1. Content-Disposition – It is a response header indicating, the download file is an attachment and allows setting the file name.
Finally, Document object is written to the Response which initiates the File download operation.
C#
protected void ExportToPDF(object sender, EventArgs e)
{
gvCustomers.AllowPaging = Convert.ToBoolean(rbPaging.SelectedItem.Value);
this.BindGrid();
//Create a table.
PdfPTable table = new PdfPTable(gvCustomers.Columns.Count);
//Set the column widths.
int[] widths = new int[gvCustomers.Columns.Count];
int i = 0;
foreach (DataControlField column in gvCustomers.Columns)
{
widths[i] = (int)gvCustomers.Columns[i].ItemStyle.Width.Value;
string cellText = Server.HtmlDecode(gvCustomers.HeaderRow.Cells[i].Text);
PdfPCell cell = new PdfPCell(new Phrase(cellText));
cell.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#008000"));
table.AddCell(cell);
i++;
}
table.SetWidths(widths);
//Transfer rows from GridView to table.
foreach (GridViewRow row in gvCustomers.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
int column = 0;
foreach (DataControlField cell in gvCustomers.Columns)
{
string cellText = Server.HtmlDecode(row.Cells[column].Text);
table.AddCell(new PdfPCell(new Phrase(cellText)));
column++;
}
}
}
//Create the PDF Document.
using (Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f))
{
using (PdfWriter.GetInstance(pdfDoc,Response.OutputStream))
{
pdfDoc.Open();
pdfDoc.Add(table);
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)
gvCustomers.AllowPaging = Convert.ToBoolean(rbPaging.SelectedItem.Value)
Me.BindGrid()
'Create a table.
Dim table As PdfPTable = New PdfPTable(gvCustomers.Columns.Count)
'Set the column widths.
Dim widths As Integer() = New Integer(gvCustomers.Columns.Count - 1) {}
Dim i As Integer = 0
For Each column As DataControlField In gvCustomers.Columns
widths(i) = CInt(gvCustomers.Columns(i).ItemStyle.Width.Value)
Dim cellText As String = Server.HtmlDecode(gvCustomers.HeaderRow.Cells(i).Text)
Dim cell As PdfPCell = New PdfPCell(New Phrase(cellText))
cell.BackgroundColor = New BaseColor(System.Drawing.ColorTranslator.FromHtml("#008000"))
table.AddCell(cell)
i += 1
Next
table.SetWidths(widths)
'Transfer rows from GridView to table.
For Each row As GridViewRow In gvCustomers.Rows
If row.RowType = DataControlRowType.DataRow Then
Dim column As Integer = 0
For Each cell As DataControlField In gvCustomers.Columns
Dim cellText As String = Server.HtmlDecode(row.Cells(column).Text)
table.AddCell(New PdfPCell(New Phrase(cellText)))
column += 1
Next
End If
Next
'Create the PDF Document.
Using pdfDoc As Document = New Document(PageSize.A4, 10.0F, 10.0F, 10.0F, 0F)
Using PdfWriter.GetInstance(pdfDoc,Response.OutputStream)
pdfDoc.Open()
pdfDoc.Add(table)
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
Error
The following error occurs when you tries to render a control such as GridView to HTML using the RenderControl method.
Server Error in '/ASP.Net' Application.
Control gvCustomers of type 'GridView' must be placed inside a form tag with runat=server.
Description:An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.Exception Details:System.Web.HttpException: Control 'gvCustomers ' of type 'GridView' must be placed inside a form tag with runat=server.
Solution
The solution to this problem is to override VerifyRenderingInServerForm event handler.
Screenshots
The Form
Current page
All pages
Demo
Downloads