How to fill out a PDF file programmatically? (Dynamic XFA)
I have a dynamic XFA Form that I can fill out manually using Adobe Acrobat on my computer. Using iTextSharp I can read what the XFA XML data is and see the structure of the data. I am essentially trying to mimic that with iText using the following code:
PdfReader pdfReader = new PdfReader(sourceFilePath);
using (MemoryStream ms = new MemoryStream()) {
using (PdfStamper stamper = new PdfStamper(pdfReader, ms)) {
XfaForm xfaForm = new XfaForm(pdfReader);
XmlDocument doc = new XmlDocument();
doc.Load(replacementXmlFilePath);
xfaForm.DomDocument = doc;
xfaForm.Changed = true;
XfaForm.SetXfa(xfaForm, stamper.Reader, stamper.Writer);
}
var bytes = ms.ToArray();
File.WriteAllBytes(destinationtFilePath, bytes);
}
For some reason this code doesn't work.
Posted on StackOverflow on May 11, 2013 by jon333
This question was answered by the person who posted the question:
I found the issue. The replacement DomDocument needs to be the entire merged XML of the new document, not just the data or datasets portion.
I upvoted this answer, because it's not incorrect, but now I think it's better to use the example from the book:
public void manipulatePdf2(String src, String xml, String dest)
throws IOException {
PdfReader reader = new PdfReader(src);
PdfDocument pdfDoc = new PdfDocument(reader, new PdfWriter(dest));
PdfAcroForm form = PdfAcroForm.getAcroForm(pdfDoc, true);
XfaForm xfa = form.getXfaForm();
xfa.fillXfaForm(new FileInputStream(xml));
xfa.write(pdfDoc);
pdfDoc.close();
}
public void manipulatePdf2(String src, String xml, String dest)
{
PdfReader reader = new PdfReader(src);
PdfDocument pdfDoc = new PdfDocument(reader, new PdfWriter(dest));
PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true);
XfaForm xfa = form.GetXfaForm();
xfa.FillXfaForm(new FileStream(xml, FileMode.Open, FileAccess.Read));
xfa.Write(pdfDoc);
pdfDoc.Close();
}
As you can see, it's not necessary to replace the whole XFA XML. If you use the fillXfaForm()
method, the data is sufficient.
Click this link if you want to see how to answer this question in iText 5.
Creating XFA forms required the use of Adobe LiveCycle Designer, however, Adobe LiveCycle was discontinued in March 2018. In addition, XFA forms were deprecated with the publication of the ISO PDF 2.0 specification in 2017.
We developed the pdfXFA add-on for iText Core to assist with existing XFA workflows. However, for new workflows we recommend alternative solutions such as Fluent, which offers dynamic data-driven document generation in a wide range of document formats, including PDF, PDF/A and PDF/UA.
If you need to process XFA documents, we have a related blog post that may be interesting to you: