Outlining PDF/A-3 invoice generation with embedded XML
Detailed reasoning converged on using ReportLab to create a PDF/A-3 base with proper XMP metadata and embedding ZUGFeRD XML invoice data as an associated file with the correct AFRelationship. Due to ReportLab’s limited native support for full PDF/A-3 embedded-file compliance (especially AFRelationship), the typical approach includes setting PDF version to 1.7, adding XMP metadata with pdfaid:part=3, embedding the XML with file attachment classes, and associating the embedded file properly. The next step is to implement a sample combining these elements, possibly requiring careful use of ReportLab’s pdfdoc module to embed and reference the XML correctly inside the PDF.Providing ReportLab PDF creation with embedded ZUGFeRD XML via pikepdf
This approach creates a PDF/A-3-compatible invoice using ReportLab, then embeds the raw XML invoice following ZUGFeRD as an associated file with the proper AFRelationship using pikepdf, also adding PDF/A-3 and ZUGFeRD XMP metadata. It demonstrates how to combine both libraries to meet the standard’s requirements in one Python script.
Below is a minimal end‑to‑end example in Python that:
- Uses ReportLab to generate a simple invoice PDF.
- Creates basic PDF/A‑3 and ZUGFeRD XMP metadata.
- Embeds a ZUGFeRD‑style XML invoice inside the PDF as an “Associated File” (
AFRelationship=Data) using pikepdf.
Note:
- You’ll need
reportlab and pikepdf installed (pip install reportlab pikepdf).
- This is a demo; real‑world PDF/A‑3 validation may require an ICC color profile, exact XMP fields, and a fully compliant ZUGFeRD/Factur‑X XML.
import io
import datetime
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4
import pikepdf
# -------------------------------------------------------------------
# Sample ZUGFeRD XML data (highly simplified, for demonstration only)
# -------------------------------------------------------------------
SAMPLE_ZUGFERD_XML = b"""<?xml version="1.0" encoding="UTF-8"?>
<rsm:CrossIndustryInvoice
xmlns:rsm="urn:ferd:CrossIndustryDocument:invoice:1p0"
xmlns:ram="urn:ferd:CrossIndustryDocument:invoice:1p0:ram"
xmlns:udt="urn:un:unece:uncefact:data:standard:UnqualifiedDataType:100">
<rsm:ExchangedDocumentContext>
<ram:GuidelineSpecifiedDocumentContextParameter>
<ram:ID>urn:ferd:invoice:rc:basic</ram:ID>
</ram:GuidelineSpecifiedDocumentContextParameter>
</rsm:ExchangedDocumentContext>
<rsm:ExchangedDocument>
<ram:ID>INV-12345</ram:ID>
<ram:TypeCode>380</ram:TypeCode>
<ram:IssueDateTime>
<udt:DateTimeString format="102">20240525</udt:DateTimeString>
</ram:IssueDateTime>
</rsm:ExchangedDocument>
<rsm:SupplyChainTradeTransaction>
<ram:ApplicableSupplyChainTradeAgreement>
<ram:BuyerReference>BUYER-REF-01</ram:BuyerReference>
</ram:ApplicableSupplyChainTradeAgreement>
<ram:ApplicableSupplyChainTradeSettlement>
<ram:InvoiceCurrencyCode>EUR</ram:InvoiceCurrencyCode>
<ram:SpecifiedTradeSettlementMonetarySummation>
<ram:GrandTotalAmount>119.00</ram:GrandTotalAmount>
</ram:SpecifiedTradeSettlementMonetarySummation>
</ram:ApplicableSupplyChainTradeSettlement>
</rsm:SupplyChainTradeTransaction>
</rsm:CrossIndustryInvoice>
"""
# -------------------------------------------------------------------
# XMP metadata for PDF/A-3 + ZUGFeRD (Factur-X style example)
# -------------------------------------------------------------------
XMP_TEMPLATE = """<?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?>
<x:xmpmeta xmlns:x="adobe:ns:meta/">
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<!-- PDF/A-3 identification -->
<rdf:Description rdf:about=""
xmlns:pdfaid="http://www.aiim.org/pdfa/ns/id/">
<pdfaid:part>3</pdfaid:part>
<pdfaid:conformance>B</pdfaid:conformance>
</rdf:Description>
<!-- ZUGFeRD / Factur-X info (example) -->
<rdf:Description rdf:about=""
xmlns:fx="urn:factur-x:pdfa:CrossIndustryDocument:invoice:1p0#">
<fx:DocumentType>INVOICE</fx:DocumentType>
<fx:Version>1.0</fx:Version>
<fx:ConformanceLevel>EN16931</fx:ConformanceLevel>
</rdf:Description>
</rdf:RDF>
</x:xmpmeta>
<?xpacket end="w"?>"""
# -------------------------------------------------------------------
# Step 1: Generate a basic PDF invoice using ReportLab
# -------------------------------------------------------------------
def create_invoice_pdf():
buf = io.BytesIO()
c = canvas.Canvas(buf, pagesize=A4, pdfVersion='1.7')
c.setAuthor("ACME Corp")
c.setTitle("Invoice INV-12345")
c.setSubject("ZUGFeRD PDF/A-3 Invoice")
# Simple invoice text
c.setFont("Helvetica-Bold", 16)
c.drawString(50, 800, "Invoice #INV-12345")
c.setFont("Helvetica", 12)
c.drawString(50, 780, "Date: 2024-05-25")
c.drawString(50, 760, "Bill To: Example Customer")
c.drawString(50, 740, "Total: 119.00 EUR")
c.drawString(50, 720, "Thank you for your business!")
c.showPage()
c.save()
return buf.getvalue()
# -------------------------------------------------------------------
# Step 2: Embed XML + Add XMP metadata using pikepdf
# -------------------------------------------------------------------
def embed_zugferd(xml_bytes, pdf_bytes, output_file):
pdf = pikepdf.Pdf.open(io.BytesIO(pdf_bytes))
# Set XMP metadata for PDF/A-3 + ZUGFeRD
pdf.metadata = pikepdf.Metadata(XMP_TEMPLATE)
# Create embedded file stream
ef_stream = pdf.make_stream(xml_bytes)
ef_stream.Type = pikepdf.Name("/EmbeddedFile")
ef_stream.Subtype = pikepdf.Name("/text#2Fxml") # = "text/xml"
# File specification dictionary with AFRelationship=Data
filespec = pdf.make_indirect(pikepdf.Dictionary({
"/Type": pikepdf.Name("/Filespec"),
"/F": "ZUGFeRD-invoice.xml",
"/UF": "ZUGFeRD-invoice.xml",
"/Desc": "ZUGFeRD Invoice XML",
"/AFRelationship": pikepdf.Name("/Data"),
"/EF": pikepdf.Dictionary({
"/F": ef_stream
})
}))
# Names tree for EmbeddedFiles
if "/Names" not in pdf.root:
pdf.root.Names = pdf.make_indirect(pikepdf.Dictionary())
if "/EmbeddedFiles" not in pdf.root.Names:
pdf.root.Names.EmbeddedFiles = pdf.make_indirect(
pikepdf.Dictionary(Names=[])
)
pdf.root.Names.EmbeddedFiles.Names.append("ZUGFeRD-invoice.xml")
pdf.root.Names.EmbeddedFiles.Names.append(filespec)
# AF entry on the catalog (associates XML with the PDF)
if "/AF" not in pdf.root:
pdf.root.AF = pdf.make_indirect(pikepdf.Array())
pdf.root.AF.append(filespec)
# Basic docinfo entries
pdf.docinfo["/Title"] = "Invoice INV-12345"
pdf.docinfo["/Author"] = "ACME Corp"
pdf.docinfo["/Subject"] = "ZUGFeRD Invoice"
# Save final PDF/A-3 with embedded XML
pdf.save(output_file, fix_metadata_version=True)
if __name__ == "__main__":
# Build the base PDF with ReportLab
base_pdf = create_invoice_pdf()
# Embed ZUGFeRD XML inside it
embed_zugferd(SAMPLE_ZUGFERD_XML, base_pdf, "ZUGFeRD_invoice.pdf")
print("Created ZUGFeRD_invoice.pdf with embedded XML.")
What this code does:
create_invoice_pdf() uses ReportLab to draw a simple invoice (human‑readable).
embed_zugferd() uses pikepdf to:
- Insert PDF/A‑3 + ZUGFeRD XMP metadata.
- Embed the XML with
AFRelationship=Data.
- Update the names tree so the embedded file appears as an attachment in PDF readers.
- Saves the PDF as
ZUGFeRD_invoice.pdf with the raw XML included.
For full production compliance, supply a valid ICC color profile, ensure your XML meets the official ZUGFeRD/Factur‑X schema, and run the result through a PDF/A validator.