tirsdag den 16. april 2013

iTextSharp - multi-line form filling

For those of us using iTextSharp to generate dynamic PDF documents, one caveat I found was in controlling line breaks. In as much as the PDF standard has supported RTF since version 6.1, I was trying to add line breaks via RTF-code - "\par", i.e. Yet it turns out the iTextSharp parser appreciates the ever reliable System.Environment.Newline.

So format your PDF form field thus...:

... and you'll be able to reference your field and add line breaks thus:

PdfReader reader = null;
AcroFields af = null;

PdfStamper ps = null;

reader = new PdfReader(new RandomAccessFileOrArray(Request.MapPath(@"~/App_Data/your_pdf_document.pdf")), null);

ps = new PdfStamper(reader, stream);

AcroFields af = ps.AcroFields;

af.SetField("Your PDF form field name", @"This line is " + System.Environment.Newline + "broken");

// make resultant PDF read-only for end-user
ps.FormFlattening = true;

// forget to close() PdfStamper, you end up with
// a corrupted file!

That's all there is to it.

Ingen kommentarer:

Send en kommentar