Creating PDF/3-A compliant PDF and attaching ZUGFeRD invoice in Java

Use the Document and FileSpecification APIs when you need to package invoice XML inside a PDF for ZUGFeRD-style workflows.

Attach ZUGFeRD invoice XML to a PDF

  1. Open the source PDF Document.
  2. Create the FileSpecification for the XML invoice file.
  3. Set the embedded file metadata, including MIME type and AFRelationship.
  4. Add the FileSpecification to the document embedded file collection.
  5. Convert the document to PdfFormat PDF_A_3A.
  6. Save the updated PDF Document.
public static void attachInvoiceZugferdFormat(Path inputFile, Path invoiceFile, Path outputFile) {
        try (Document document = new Document(inputFile.toString())) {
            String description = "Invoice metadata conforming to ZUGFeRD standard";
            FileSpecification fileSpecification = new FileSpecification(invoiceFile.toString(), description);

            fileSpecification.setMIMEType("text/xml");
            fileSpecification.setAFRelationship(AFRelationship.Alternative);

            document.getEmbeddedFiles().add("factur", fileSpecification);

            String outputFileName = outputFile.toString();
            String logPath = outputFileName.replace(".pdf", "_log.xml");
            document.convert(logPath, PdfFormat.PDF_A_3A, ConvertErrorAction.Delete);
            document.save(outputFile.toString());
        }
        System.out.println("ZUGFeRD invoice attached to " + outputFile);
    }