Hi smile,
Please refer below sample.
HTML
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="ContactName" HeaderText="Contact Name" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="Country" HeaderText="Country" />
</Columns>
</asp:GridView>
<br />
<asp:Button ID="btnExport" runat="server" Text="Export To PDF" OnClick="ExportToPDF" />
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;
Code
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();
}
}
}
}
}
protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
this.BindGrid();
}
protected void ExportToPDF(object sender, EventArgs e)
{
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter hw = new HtmlTextWriter(sw))
{
GridView1.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A2, 20, 20, 25, 25);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter write = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
write.PageEvent = new Footer();
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 partial class Footer : PdfPageEventHelper
{
public override void OnEndPage(PdfWriter writer, Document doc)
{
Paragraph footer = new Paragraph("Computer Generated Report", FontFactory.GetFont(FontFactory.TIMES_BOLD, 15, iTextSharp.text.Font.BOLD));
footer.Alignment = Element.ALIGN_MIDDLE;
PdfPTable footerTbl = new PdfPTable(1);
footerTbl.TotalWidth = 250;
footerTbl.HorizontalAlignment = Element.ALIGN_LEFT;
footerTbl.AddCell(footer);
footerTbl.WriteSelectedRows(0, -1, 400, 150, writer.DirectContent);
}
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
Screenshot