Friday, January 8, 2010

Generate iTextSharp PDF Direct from Memory

If you need to dynamically generate a PDF using iTextSharp and you don't want to write to the disk, use the MemoryStream and PdfWriter.


using System;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using iTextSharp.text;
using iTextSharp.text.pdf;

public partial class GetPDF : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
byte[] pdf = GetPdfDocument();

Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment;filename=MyDocument.pdf");
Response.OutputStream.Write(pdf, 0, pdf.Length);
}

private byte[] GetPdfDocument() {
byte[] result;

using (MemoryStream ms = new MemoryStream()) {
Document doc = new Document();
PdfWriter.GetInstance(doc, ms);
doc.AddTitle("Document Title");
doc.Open();
doc.Add(new Paragraph("My paragraph."));
doc.Close();
result = ms.GetBuffer();
}

return result;
}
}

No comments: