Java tutorial
/* * This example was written by Bruno Lowagie, author of the book * 'iText in Action' by Manning Publications (ISBN: 1932394796). * You can use this example as inspiration for your own applications. * The following license applies: * http://www.1t3xt.com/about/copyright/index.php?page=MIT */ package questions.forms; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import com.lowagie.text.DocumentException; import com.lowagie.text.pdf.PdfReader; import com.lowagie.text.pdf.PdfStamper; import com.lowagie.text.pdf.XfaForm; public class FillDynamicXfa2 { public static final String RESOURCE_PDF = "resources/questions/forms/dynamic.pdf"; public static final String RESOURCE_DATA = "resources/questions/forms/datasets.xml"; public static final String RESULT = "results/questions/forms/filled_xfa2.pdf"; public static void main(String[] args) { try { // getting new data from a "datasets" XML snippet File file = new File(RESOURCE_DATA); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); Document newdoc = db.parse(file); Element element = newdoc.getDocumentElement(); NodeList nodelist = element.getElementsByTagNameNS("http://www.xfa.org/schema/xfa-data/1.0/", "data"); Node newdata = nodelist.item(0); // replacing the XFA in an existing document PdfReader reader = new PdfReader(RESOURCE_PDF); XfaForm xfa = new XfaForm(reader); Document doc = xfa.getDomDocument(); NodeList list = doc.getElementsByTagNameNS("http://www.xfa.org/schema/xfa-data/1.0/", "datasets"); list.item(0).replaceChild(doc.importNode(newdata, true), list.item(0).getFirstChild()); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT)); xfa.setDomDocument(doc); xfa.setChanged(true); XfaForm.setXfa(xfa, stamper.getReader(), stamper.getWriter()); stamper.close(); } catch (IOException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } } }