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();

1 comment:

Raman Basu said...

This is the VB version of Alan's code. Only enhancement is that it shows open/save dialog in IE.

Response.Clear()
Response.ContentType = "application/pdf"
Response.AddHeader("Content-Disposition", "attachment; filename=file.pdf")
Dim m As System.IO.MemoryStream = New System.IO.MemoryStream()
Dim Document As iText.Document = New iText.Document()
Dim writer As iText.pdf.PdfWriter = 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()