Here’s two examples to dynamically create PDF’s using iTextSharps’ HTML Parser: in the browser and also a method to write the pdf to disk.
using System;
using System.Web;
using System.Web.UI;
using System.IO;
using System.Xml;
using iTextSharp.text;
using iTextSharp.text.html;
using iTextSharp.text.pdf;
namespace Web
{
public partial class iTextSharpDemo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Example HTML String
string html = "<html><p align='center'>Hello World!</p><newpage />Hello 2nd Page!</html>";
//Parse the HTML to PDF and Write PDF to disk
WritePdf(html, @"c:\temp\share\mypdf.pdf");
//Parse the HTML to PDF and write PDF bytes to browser via the outputstream
MemoryStream m = CreatePdf(html);
Response.ContentType = "application/pdf";
Response.OutputStream.Write(m.GetBuffer(), 0, m.GetBuffer().Length);
Response.OutputStream.Flush();
Response.OutputStream.Close();
}
protected void WritePdf(string html, string destination)
{
MemoryStream ms = CreatePdf(html);
FileStream fs = File.OpenWrite(destination);
fs.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
fs.Close();
ms.Close();
}
public static MemoryStream CreatePdf(string html)
{
MemoryStream m = new MemoryStream();
try
{
Document document = new Document(PageSize.LETTER);
PdfWriter.GetInstance(document, m);
StringReader sr = new StringReader(html);
XmlTextReader xtr = new XmlTextReader(sr);
document.Open();
HtmlParser.Parse(document, xtr);
xtr.Close();
document.Close();
}
catch (Exception ex)
{
System.Diagnostics.EventLog.WriteEntry("Application", ex.Message);
throw ex;
}
return m;
}
}
}