iTextSharp – Removing Fields from PDF templates

Sometimes the iTextSharp RemoveField() method won’t work. This is likely because the PDF template was created in Adobe LiveCycle. LiveCycle saves the file in XFA format. iTextSharp functionality against XfA files are limited to get and set. RemoveField(), at least for now, only works on AcroForm templates created in Adobe Acrobat.

BTW, here’s the code to read from a template, edit a field and save to a new file…or output to the browser.

string templateFile = Server.MapPath(“pdf/FSSTemplate.pdf”);
string newFile = Server.MapPath(“pdf/FSS.pdf”);

PdfReader reader = new PdfReader(templateFile);
PdfStamper stamper = new PdfStamper(reader, new FileStream(newFile, FileMode.Create));

//Use the two lines below to write the pdf to the browser
//MemoryStream ms = new System.IO.MemoryStream();
//PdfStamper stamper = new PdfStamper(reader, ms);

AcroFields fields = stamper.AcroFields;
fields.SetField(“field1”, “Hello World!”);

//Flatten and close
stamper.FormFlattening = true;

//If you’re writing to a file, you’re done here. If you want to write to the browser, use the code below.

Byte[] byteArray = ms.ToArray();
Response.BufferOutput = true;
string timestamp = DateTime.Now.ToString(“MMddyyyy_HHmmss”);
Response.AddHeader(“Content-Disposition”, “attachment; filename=PDF_” + timestamp + “.pdf”);
Response.ContentType = “application/pdf”;


2 thoughts on “iTextSharp – Removing Fields from PDF templates

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s