Sunday, February 5, 2012

1. Code doesn't work if paging is enabled in GridView

2. Columns become of variable width in PDF documnt as shown in the image below




To fix these problems we need to write code without using xmlTextReader and HtmlParser.
for this we need to create a table in PDF document and then fill the cells of table from GridView
And the new html and codebehind would become like this

<%@ Page Language="C#" AutoEventWireup="true"CodeFile="Default.aspx.cs"
Inherits="_Default" %><!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
><head runat="server"><title>Untitled Page</title>
</head><body><form id="form1" runat="server">
<div>

<asp:GridView ID="GridView1"
runat="server"AutoGenerateColumns="False"AllowPaging="true"
PageSize="5"DataSourceID="SqlDataSource1"><
Columns><asp:BoundField DataField="Name
"HeaderText="Name"SortExpression="Name" />
<asp:BoundField DataField="Location"HeaderText="Location"
SortExpression="Location" /></Columns></asp:GridView>

<asp:SqlDataSource ID="SqlDataSource1"runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>
"SelectCommand="SELECT [Name], [Location] FROM [Test]">
</asp:SqlDataSource></div><br />

<asp:Button ID="btnExport" runat="server"
OnClick="btnExport_Click"Text="Export to PDF" />
</form></body></html>


And the code behind goes like this
protected void btnExport_Click(object sender, EventArgs e)
{
int columnCount = GridView1.Columns.Count;
int rowCount = GridView1.Rows.Count;
int tableRows = rowCount + 3;
iTextSharp.text.Table grdTable=
new iTextSharp.text.Table(columnCount, tableRows);
grdTable.BorderWidth = 1;
grdTable.BorderColor = new Color(0, 0, 255);
grdTable.Cellpadding = 5;
grdTable.Cellspacing = 5;
Cell c1 = new Cell("Exporting paging enabled GridView to PDF example");
c1.Header = true;c1.Colspan = 2;
grdTable.AddCell(c1);
Cell c2 = new Cell("By amiT jaiN , amit_jain_online@yahoo.com");
c2.Colspan = 2;
grdTable.AddCell(c2);
grdTable.AddCell("Name");
grdTable.AddCell("Location");
for (int rowCounter = 0;
rowCounter < rowCount; rowCounter++)
{for (int columnCounter = 0;columnCounter < columnCount; columnCounter++)
{string strValue =GridView1.Rows[rowCounter].Cells[columnCounter].Text;
grdTable.AddCell(strValue);
}
}
Document Doc = new Document();
PdfWriter.GetInstance(Doc, Response.OutputStream);
Doc.Open();Doc.Add(grdTable);
Doc.Close();
Response.ContentType = "application/pdf";
Response.AddHeader
("content-disposition", "attachment; filename=AmitJain.pdf");
Response.End();


PDF created would be like this


0 comments:

Post a Comment