Instructions
1
Open a C# editor.
2
Create a C# file and add the following code.
3
Use a name space to call the iTextSharp library:
using iTextSharp.text;
using iTextSharp.text.pdf;
4
Call an inbuilt class in iTextSharp and set the StringBuilder to empty:
Document document = new Document(PageSize.A4, 80, 50, 30, 65);
StringBuilder strData = new StringBuilder(string.Empty);
5
Add a Path for the Aspx to be generated from GridView content:
string strASPXpath = Server.MapPath("MyASPX.aspx");
6
Set the path for the PDF file to build:
string strPDFpath = Server.MapPath("MyPDF.pdf");
7
Call the data from the HTML file and render the file:
StringWriter sw = new StringWriter();
sw.WriteLine(Environment.NewLine);
sw.WriteLine(Environment.NewLine);
sw.WriteLine(Environment.NewLine);
sw.WriteLine(Environment.NewLine);
HtmlTextWriter htw = new HtmlTextWriter(sw);
gvSerchResult.AllowPaging = false;
gvSerchResult.AllowSorting = false;
BindGridView();
gvSerchResult.RenderControl(htw);
StreamWriter strWriter = new StreamWriter(strASPXpath, false, Encoding.UTF8);
strWriter.Write("<html><head></head><body>" + htw.InnerWriter.ToString() + "</body></html>");
strWriter.Close();
strWriter.Dispose();
8
Use the parser to convert the ASPX content to a PDF:
iTextSharp.text.html.simpleparser.
StyleSheet styles = new iTextSharp.text.html.simpleparser.StyleSheet();
styles.LoadTagStyle("ol", "leading", "16,0");
PdfWriter.GetInstance(document, new FileStream(strPDFpath, FileMode.Create));
document.Open();
9
Set the font styles for the elements on page and add the page items:
ArrayList objects;
styles.LoadTagStyle("li", "face", "garamond");
styles.LoadTagStyle("span", "size", "8px");
styles.LoadTagStyle("body", "font-family", "times new roman");
styles.LoadTagStyle("body", "font-size", "12px");
document.NewPage();
objects = iTextSharp.text.html.simpleparser.
HTMLWorker.ParseToList(new StreamReader(strASPXpath, Encoding.Default), styles);
for (int k = 0; k < objects.Count; k++)
{
document.Add((IElement)objects[k]);
}
10
Clear all the variables used from memory and close:
{
document.Close();
Response.Write(Server.MapPath("~/" + strPDFpath));
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "attachment; filename=" + strPDFpath);
Response.ContentType = "application/octet-stream";
Response.WriteFile(Server.MapPath("~/" + strPDFpath));
Response.Flush();
Response.Close();
if (File.Exists(Server.MapPath("~/" + strPDFpath)))
{
File.Delete(Server.MapPath("~/" + strPDFpath));
}
}
11
Run the C# file to create the PDF file from the ASPX file.