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;
stamper.Close();

//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();
ms.Flush();
ms.Close();
Response.BufferOutput = true;
Response.Clear();
Response.ClearHeaders();
string timestamp = DateTime.Now.ToString(“MMddyyyy_HHmmss”);
Response.AddHeader(“Content-Disposition”, “attachment; filename=PDF_” + timestamp + “.pdf”);
Response.ContentType = “application/pdf”;
Response.BinaryWrite(byteArray);
Response.End();