Thursday, August 28, 2008

Server-side PDF form generation with OpenOffice Writer and iTextSharp

OpenOffice.org Writer has the ability to create PDF forms:

Create a form in Writer with textboxes.















Be sure to give each of your fields unique names (LastName, etc) - these will be needed later when we reference the fields in the PDF from iTextSharp.

When the form is ready, choose File | Export as PDF to create the PDF file.

iTextSharp is an open-source .Net library that allows you to reference the form fields from ASP.Net.

In Visual Studio, add a reference to the iTextSharp dll.


using iTextSharp.text.pdf;

...

string template = HttpContext.Current.Server.MapPath("../PDF/Template.pdf");

PdfReader pdfReader = new PdfReader(template);
MemoryStream pdfResponse = new MemoryStream();
PdfStamper pdfStamper = new PdfStamper(pdfReader, pdfResponse);

AcroFields pdfFormFields = pdfStamper.AcroFields;

// in real life, this value comes from a database
string lastName = "Bloggs";

pdfFormFields.SetField("LastName", lastName);

...

pdfStamper.FormFlattening = true;
pdfStamper.Writer.CloseStream = false;
pdfStamper.Close();

// in this case we're streaming the PDF without saving to disk.
HttpContext.Current.Response.ContentType = "application/pdf";
HttpContext.Current.Response.AddHeader("Content-disposition", "attachment; filename=FileName.pdf");
pdfResponse.WriteTo(HttpContext.Current.Response.OutputStream);

pdfResponse.Close();


In the above example, the PDF is generated on the fly.

The way it works is: I have a page (PrintDocument.aspx) with no html in it; all it has is the iTextSharp code in the code behind.

On my main page, I have a link to PrintDocument.aspx. When the user clicks this link, the PDF is sent to them as a download.