Combining XFA with PDFBox

后端 未结 5 1662
面向向阳花
面向向阳花 2020-12-14 14:09

I would like to fill a PDF form with the PDFBox java library. The PDF form is created with Adobe Live Designer, so it uses the XFA format.

I try to find resources ab

5条回答
  •  青春惊慌失措
    2020-12-14 14:21

    The question specifically identifies the PDFBox library in the subject; you do not need iText, the XFA manipulation can be done using the PDXFA object available in PDFBox 1.8.

    Many thanks to Maruan Sahyoun for his great work on PDFBox + XFA.

    This code only works when you remove all security on the PDDocument.
    It also assumes the COS object in PDXFA is a COSStream. The simplistic example below reads the xml stream and writes it back into the PDF.

     PDDocument doc = PDDocument.load("filename");
     doc.setAllSecurityToBeRemoved(true);
    
     PDDocumentCatalog docCatalog = doc.getDocumentCatalog();
     PDAcroForm form = docCatalog.getAcroForm();
    
     PDXFA xfa = form.getXFA();
     COSBase cos = xfa.getCOSObject();
     COSStream coss = (COSStream) cos;
     InputStream cosin = coss.getUnfilteredStream();
     Document document = documentBuilder.parse(cosin);
    
     COSStream cosout = new COSStream(new RandomAccessBuffer());
     OutputStream out = cosout.createUnfilteredStream();
    
     TransformerFactory tFactory = TransformerFactory.newInstance();
     Transformer transformer = tFactory.newTransformer();
     DOMSource source = new DOMSource(xmlDoc);
     StreamResult result = new StreamResult(out);
     transformer.transform(source, result);
    
     PDXFA xfaout = new PDXFA(cosout);
     form.setXFA(xfaout);
    

提交回复
热议问题