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.

25th October 2015
admin-marketing

Here is my 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 that I think it's better to use the example from the book:

public byte[] ManipulatePdf(String src, String xml) {
    PdfReader reader = new PdfReader(src);
    using (MemoryStream ms = new MemoryStream()) {
        using (PdfStamper stamper = new PdfStamper(reader, ms)) {
            AcroFields form = stamper.AcroFields;
            XfaForm xfa = form.Xfa;
            xfa.FillXfaForm(XmlReader.Create(new StringReader(xml)));
        }
        return ms.ToArray();
    }
}

As you can see, it's not necessary to replace the whole XFA XML. If you use the FillXfaForm method, the data is sufficient.



Contact

Still have questions? 

We're happy to answer your questions. Reach out to us and we'll get back to you shortly.

Contact us
Stay updated

Join 11,000+ subscribers and become an iText PDF expert by staying up to date with our new products, updates, tips, technical solutions and happenings.

Subscribe Now