How to flatten a XFA PDF Form using iTextSharp?
Posted on StackOverflow on Nov 21, 2014 by Chuck
You didn't insert a code sample to show how you are currently flattening the XFA form. I assume your code looks like this:
var reader = new PdfReader(existingFileStream);
var stamper = new PdfStamper(reader, newFileStream);
var form = stamper.AcroFields;
var fieldKeys = form.Fields.Keys;
foreach (string fieldKey in fieldKeys) {
form.SetField(fieldKey, "X");
}
stamper.FormFlattening = true;
stamper.Close();
reader.Close();
This code will work when trying to flatten forms based on AcroForm technology, but it can't be used for forms based on the XML Forms Architecture (XFA)!
A dynamic XFA form usually consists of a single page PDF (the one with the "Please wait..." message) that is shown in viewer that do not understand XFA. The actual content of the document is stored as an XML file.
The process of flattening an XFA form to an ordinary PDF requires that you parse the XML and convert the XML syntax into PDF syntax. This can be done using iText's XFA Worker.
Suppose that you have a file in memory (ms
) that consists of an XFA form that is filled out, then you can use the following code to flatten that form:
Document document = new Document();
PdfWriter writer =
PdfWriter.GetInstance(document, new FileStream(dest, FileMode.Create));
XFAFlattener xfaf = new XFAFlattener(document, writer);
ms.Position = 0;
xfaf.Flatten(new PdfReader(ms));
document.Close();
You can download a zip file containing the DLLs for XFA Worker as well as an example from the iText web site.