FDF and XFDF

This is a code example of iText PDF, discover more.

6th November 2015
admin-marketing

Switch code for this example

ImportXFDF.java
  1. /*
  2.  * This example was written by Bruno Lowagie in answer to the following question:
  3.  * http://stackoverflow.com/questions/30508966/saving-xfdf-as-pdf
  4.  */
  5. package sandbox.acroforms;
  6.  
  7. import com.itextpdf.text.DocumentException;
  8. import com.itextpdf.text.pdf.AcroFields;
  9. import com.itextpdf.text.pdf.PdfReader;
  10. import com.itextpdf.text.pdf.PdfStamper;
  11. import com.itextpdf.text.pdf.XfdfReader;
  12.  
  13. import java.io.File;
  14. import java.io.FileInputStream;
  15. import java.io.FileOutputStream;
  16. import java.io.IOException;
  17.  
  18. /**
  19.  * @author iText
  20.  */
  21. public class ImportXFDF {
  22.  
  23.     public static final String SRC = "resources/pdfs/Requisition_Fillable.pdf";
  24.     public static final String XFDF = "resources/pdfs/data.xfdf";
  25.     public static final String DEST = "results/acroforms/xfdf_merged.pdf";
  26.  
  27.     public static void main(String[] args) throws DocumentException, IOException {
  28.         File file = new File(DEST);
  29.         file.getParentFile().mkdirs();
  30.         new ImportXFDF().fillXfdf(SRC, XFDF, DEST);
  31.     }
  32.  
  33.     protected void fillXfdf(String SRC, String XFDF, String DEST) throws IOException, DocumentException {
  34.         // We receive the XML bytes
  35.         XfdfReader xfdf = new XfdfReader(new FileInputStream(XFDF));
  36.         // We get the corresponding form
  37.         PdfReader reader = new PdfReader(SRC);
  38.         // We create an OutputStream for the new PDF
  39.         FileOutputStream baos = new FileOutputStream(DEST);
  40.         // Now we create the PDF
  41.         PdfStamper stamper = new PdfStamper(reader, baos);
  42.         // We alter the fields of the existing PDF
  43.         AcroFields fields = stamper.getAcroFields();
  44.         fields.setFields(xfdf);
  45.         // take away all interactivity
  46.         stamper.setFormFlattening(true);
  47.         // close the stamper
  48.         stamper.close();
  49.         reader.close();
  50.     }
  51. }
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