Friday, July 01, 2005

Streaming PDF using iTextSharp and ASP.NET

I've been looking at iTextSharp and iTextDotNet for a while now and I must say I'm very impressed with both.

One thing you may want to do if you're doing dynamic PDF generation is stream a PDF back from an ASP.NET page. The following simple example shows the basic elements using iTextSharp v3.0.3.


using iText = iTextSharp.text;
....

Response.Clear();
Response.ContentType = "application/pdf";
System.IO.MemoryStream m = new System.IO.MemoryStream();
iText.Document document = new iText.Document();
iText.pdf.PdfWriter writer = iText.pdf.PdfWriter.GetInstance(document, m);
document.Open();

document.Add(new iText.Paragraph(DateTime.Now.ToString()));
document.NewPage();
document.Add(new iText.Paragraph("Hello World"));
document.Close();

writer.Flush();
Response.OutputStream.Write(m.GetBuffer(), 0, m.GetBuffer().Length);
Response.OutputStream.Flush();
Response.OutputStream.Close();
Response.End();