Thursday, March 6, 2008

Export Html to Pdf using iTextSharp

This is an example to export from html to pdf using iTextSharp. In this case I used a html template file with some token fields that are replaced and after exported to pdf.

private static void GeneratePDF()
{
// Set output folder to /pdf
string outputFolder = HttpContext.Current.Server.MapPath("pdf");
// Set output file name to a Guid based name
string pdfFileName = outputFolder + "\\" + Guid.NewGuid().ToString() + ".pdf";

Document iTextSharpDocument = new Document(new Rectangle(880, 700));
FileStream fs = new FileStream(pdfFileName, FileMode.CreateNew);
PdfWriter writer = PdfWriter.GetInstance(iTextSharpDocument, fs);
iTextSharpDocument.Open();

// Read the html template and replace values
string templatePath = HttpContext.Current.Server.MapPath("html/ReportTemplate.html");
TextReader templateReader = new StreamReader(templatePath);
StringBuilder sbTemplate = new StringBuilder(templateReader.ReadToEnd());
sbTemplate.Replace("[@title]", "Sales");
sbTemplate.Replace("
[@name]", "Jhon Smith");
sbTemplate.Replace("
[@date]", DateTime.Now.ToString());

XmlDocument htmlDoc = new XmlDocument();
htmlDoc.LoadXml(sbTemplate.ToString());

HtmlParser.Parse(iTextSharpDocument, htmlDoc);

// Release resources
templateReader.Close();

iTextSharpDocument.Close();
writer.Close();

writer = null;
iTextSharpDocument = null;

fs.Close();
fs.Dispose();
}

3 comments:

Anonymous said...

U nuts !!!
Where is the ReportTemplate.html file.
Guess what u r too busy solving ur own damn problems & then u miss out on such obvious things. go get a break.

Anonymous said...

Yea. I had the same problem. no html file.

Martin Olivares said...

Hi, you can create the ReportTemplate.html inside the folder html with the content (and tokens) that you want use.