from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import mm, inch
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph, Spacer, PageBreak
from reportlab.pdfgen import canvas
from datetime import datetime, timedelta
import xml.etree.ElementTree as ET
from xml.dom import minidom
import pikepdf
from io import BytesIO
import hashlib
import uuid
from pathlib import Path
from lxml import etree
import json
class ZUGFeRDGenerator:
"""Generate ZUGFeRD 2.1 compliant XML invoice"""
def __init__(self, invoice_data):
self.data = invoice_data
self.namespaces = {
'rsm': 'urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100',
'qdt': 'urn:un:unece:uncefact:data:standard:QualifiedDataType:100',
'ram': 'urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100',
'udt': 'urn:un:unece:uncefact:data:type:basic:UNQUALIFIED_DATA_TYPES:100',
}
def generate_xml(self):
"""Generate complete ZUGFeRD XML"""
# Register namespaces
for prefix, uri in self.namespaces.items():
ET.register_namespace(prefix, uri)
# Root element
root = ET.Element('{urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100}CrossIndustryInvoice')
# Context element
self._add_context(root)
# ExchangedDocument
self._add_exchanged_document(root)
# SupplyChainTradeTransaction
self._add_supply_chain_trade(root)
# Pretty print
xml_str = minidom.parseString(
ET.tostring(root)
).toprettyxml(indent=" ")
# Remove extra blank lines
return '\n'.join([line for line in xml_str.split('\n') if line.strip()])
def _add_context(self, root):
"""Add specification context"""
nsmap = {'rsm': self.namespaces['rsm'], 'ram': self.namespaces['ram'], 'udt': self.namespaces['udt']}
context = ET.SubElement(root, '{urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100}SpecificationDocumentReference')
id_elem = ET.SubElement(context, '{urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100}ID')
id_elem.text = 'urn:cen.eu:en16931:2017#compliant#urn:factur-x.eu:1p0:extended'
def _add_exchanged_document(self, root):
"""Add exchange document details"""
doc = ET.SubElement(root, '{urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100}ExchangedDocument')
# Invoice number
id_elem = ET.SubElement(doc, '{urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100}ID')
id_elem.text = self.data['invoice_number']
# Type code (380 = Invoice)
type_code = ET.SubElement(doc, '{urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100}TypeCode')
type_code.text = '380'
# Issue date
issue_date = ET.SubElement(doc, '{urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100}IssueDateTime')
date_str = ET.SubElement(issue_date, '{urn:un:unece:uncefact:data:type:basic:UNQUALIFIED_DATA_TYPES:100}DateTimeString')
date_str.set('format', '20060921')
date_str.text = datetime.strptime(self.data['invoice_date'], '%Y-%m-%d').strftime('%Y%m%d')
# Notes
if self.data.get('notes'):
note = ET.SubElement(doc, '{urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100}IncludedNote')
content = ET.SubElement(note, '{urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100}Content')
content.text = self.data['notes']
def _add_supply_chain_trade(self, root):
"""Add supply chain trade transaction"""
supply = ET.SubElement(root, '{urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100}SupplyChainTradeTransaction')
# Line items
for idx, item in enumerate(self.data['line_items']):
self._add_line_item(supply, item, idx + 1)
# Trade settlement / totals
self._add_trade_settlement(supply)
# Trade parties
self._add_trade_parties(supply)
def _add_line_item(self, parent, item, index):
"""Add invoice line item"""
line_item = ET.SubElement(
parent,
'{urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100}IncludedSupplyChainTradeLineItem'
)
# Document line ID
doc_line_id = ET.SubElement(line_item, '{urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100}AssociatedDocumentLineDocument')
line_id = ET.SubElement(doc_line_id, '{urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100}LineID')
line_id.text = str(index)
# Trade line item
trade_item = ET.SubElement(line_item, '{urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100}SpecifiedTradeProduct')
name = ET.SubElement(trade_item, '{urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100}Name')
name.text = item['description']
# Quantity
quantity = ET.SubElement(line_item, '{urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100}SpecifiedLineTradeAgreement')
net_price = ET.SubElement(quantity, '{urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100}NetPriceProductTradePrice')
charge_amt = ET.SubElement(net_price, '{urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100}ChargeAmount')
charge_amt.text = f"{item['unit_price']:.2f}"
# Delivery
delivery = ET.SubElement(line_item, '{urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100}SpecifiedLineTradeDelivery')
qty = ET.SubElement(delivery, '{urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100}BilledQuantity')
qty.set('unitCode', item.get('unit', 'C62'))
qty.text = str(item['quantity'])
# Settlement
settlement = ET.SubElement(line_item, '{urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100}SpecifiedLineTradeSettlement')
monetary_sum = ET.SubElement(settlement, '{urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100}SpecifiedTradeSettlementLineMonetarySummation')
line_total = ET.SubElement(monetary_sum, '{urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100}LineTotalAmount')
line_total.text = f"{item['quantity'] * item['unit_price']:.2f}"
def _add_trade_settlement(self, parent):
"""Add trade settlement with totals"""
settlement = ET.SubElement(
parent,
'{urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100}ApplicableHeaderTradeSettlement'
)
# Currency
currency = ET.SubElement(settlement, '{urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100}InvoiceCurrencyCode')
currency.text = self.data.get('currency', 'EUR')
# Monetary totals
monetary = ET.SubElement(settlement, '{urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100}SpecifiedTradeSettlementHeaderMonetarySummation')
# Calculate totals
subtotal = sum(item['quantity'] * item['unit_price'] for item in self.data['line_items'])
tax = self.data.get('tax_amount', subtotal * 0.19)
total = subtotal + tax
# Line total
line_total = ET.SubElement(monetary, '{urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100}LineTotalAmount')
line_total.text = f"{subtotal:.2f}"
# Tax
tax_elem = ET.SubElement(monetary, '{urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100}TaxTotalAmount')
tax_elem.set('currencyID', self.data.get('currency', 'EUR'))
tax_elem.text = f"{tax:.2f}"
# Grand total
total_elem = ET.SubElement(monetary, '{urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100}GrandTotalAmount')
total_elem.text = f"{total:.2f}"
def _add_trade_parties(self, parent):
"""Add seller and buyer parties"""
# Seller
seller_trade = ET.SubElement(
parent,
'{urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100}ApplicableHeaderTradeAgreement'
)
seller = ET.SubElement(seller_trade, '{urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100}SellerTradeParty')
self._add_party_info(seller, self.data['seller'])
# Buyer
buyer = ET.SubElement(seller_trade, '{urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100}BuyerTradeParty')
self._add_party_info(buyer, self.data['buyer'])
def _add_party_info(self, parent, party_data):
"""Add party information (seller/buyer)"""
# Name
name = ET.SubElement(parent, '{urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100}Name')
name.text = party_data['name']
# Address
address = ET.SubElement(parent, '{urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100}PostalTradeAddress')
street = ET.SubElement(address, '{urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100}LineOne')
street.text = party_data.get('street', '')
city = ET.SubElement(address, '{urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100}CityName')
city.text = party_data.get('city', '')
postal = ET.SubElement(address, '{urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100}PostcodeCode')
postal.text = party_data.get('postal_code', '')
country = ET.SubElement(address, '{urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100}CountryID')
country.text = party_data.get('country', 'DE')
# Tax ID
if party_data.get('tax_id'):
tax_id = ET.SubElement(parent, '{urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100}SpecifiedTaxRegistration')
tax_id_elem = ET.SubElement(tax_id, '{urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100}ID')
tax_id_elem.set('schemeID', 'VA')
tax_id_elem.text = party_data['tax_id']
class PDFInvoiceGenerator:
"""Generate human-readable invoice PDF"""
def __init__(self, invoice_data):
self.data = invoice_data
def generate_pdf(self):
"""Generate PDF with invoice details"""
buffer = BytesIO()
doc = SimpleDocTemplate(buffer, pagesize=A4, topMargin=15*mm, bottomMargin=15*mm)
story = []
styles = getSampleStyleSheet()
# Custom styles
title_style = ParagraphStyle(
'CustomTitle',
parent=styles['Heading1'],
fontSize=24,
textColor=colors.HexColor('#1a1a1a'),
spaceAfter=12,
fontName='Helvetica-Bold'
)
heading_style = ParagraphStyle(
'CustomHeading',
parent=styles['Heading2'],
fontSize=11,
textColor=colors.HexColor('#333333'),
spaceAfter=6,
fontName='Helvetica-Bold'
)
normal_style = ParagraphStyle(
'CustomNormal',
parent=styles['Normal'],
fontSize=9,
textColor=colors.HexColor('#555555')
)
# Header
story.append(Paragraph("INVOICE", title_style))
story.append(Spacer(1, 12))
# Invoice details
invoice_info = [
['Invoice Number:', self.data['invoice_number']],
['Date:', self.data['invoice_date']],
['Due Date:', self.data['due_date']],
]
table = Table(invoice_info, colWidths=[80*mm, 80*mm])
table.setStyle(TableStyle([
('FONTNAME', (0, 0), (0, -1), 'Helvetica-Bold'),
('FONTSIZE', (0, 0), (-1, -1), 9),
('TEXTCOLOR', (0, 0), (-1, -1), colors.HexColor('#333333')),
('ALIGN', (0, 0), (-1, -1), 'LEFT'),
('LEFTPADDING', (0, 0), (-1, -1), 0),
('RIGHTPADDING', (0, 0), (-1, -1), 0),
('TOPPADDING', (0, 0), (-1, -1), 3),
('BOTTOMPADDING', (0, 0), (-1, -1), 3),
]))
story.append(table)
story.append(Spacer(1, 12))
# Seller and Buyer
story.append(Paragraph("From:", heading_style))
seller_text = f"{self.data['seller']['name']}<br/>{self.data['seller'].get('street', '')}<br/>{self.data['seller'].get('postal_code', '')} {self.data['seller'].get('city', '')}"
story.append(Paragraph(seller_text, normal_style))
story.append(Spacer(1, 12))
story.append(Paragraph("Bill To:", heading_style))
buyer_text = f"{self.data['buyer']['name']}<br/>{self.data['buyer'].get('street', '')}<br/>{self.data['buyer'].get('postal_code', '')} {self.data['buyer'].get('city', '')}"
story.append(Paragraph(buyer_text, normal_style))
story.append(Spacer(1, 12))
# Line items
story.append(Paragraph("Line Items:", heading_style))
line_data = [['Description', 'Qty', 'Unit', 'Price', 'Total']]
for item in self.data['line_items']:
line_data.append([
item['description'],
str(item['quantity']),
item.get('unit', 'C62'),
f"€{item['unit_price']:.2f}",
f"€{item['quantity'] * item['unit_price']:.2f}"
])
table = Table(line_data, colWidths=[70*mm, 20*mm, 25*mm, 30*mm, 35*mm])
table.setStyle(TableStyle([
('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#e6e6e6')),
('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
('FONTSIZE', (0, 0), (-1, -1), 9),
('TEXTCOLOR', (0, 0), (-1, -1), colors.HexColor('#333333')),
('ALIGN', (1, 0), (-1, -1), 'RIGHT'),
('ALIGN', (0, 0), (0, -1), 'LEFT'),
('GRID', (0, 0), (-1, -1), 0.5, colors.HexColor('#cccccc')),
('ROWBACKGROUNDS', (0, 1), (-1, -1), [colors.white, colors.HexColor('#f9f9f9')]),
]))
story.append(table)
story.append(Spacer(1, 12))
# Totals
subtotal = sum(item['quantity'] * item['unit_price'] for item in self.data['line_items'])
tax = self.data.get('tax_amount', subtotal * 0.19)
total = subtotal + tax
totals_data = [
['Subtotal:', f"€{subtotal:.2f}"],
['Tax (19%):', f"€{tax:.2f}"],
['Total:', f"€{total:.2f}"],
]
table = Table(totals_data, colWidths=[130*mm, 35*mm])
table.setStyle(TableStyle([
('FONTNAME', (0, 0), (0, -3), 'Helvetica'),
('FONTNAME', (0, -1), (0, -1), 'Helvetica-Bold'),
('FONTSIZE', (0, 0), (-1, -1), 9),
('TEXTCOLOR', (0, 0), (-1, -1), colors.HexColor('#333333')),
('ALIGN', (0, 0), (0, -1), 'RIGHT'),
('ALIGN', (1, 0), (1, -1), 'RIGHT'),
('LINEABOVE', (0, -1), (-1, -1), 1, colors.HexColor('#333333')),
]))
story.append(table)
if self.data.get('notes'):
story.append(Spacer(1, 12))
story.append(Paragraph("Notes:", heading_style))
story.append(Paragraph(self.data['notes'], normal_style))
# Build PDF
doc.build(story)
buffer.seek(0)
return buffer
class PDFAConverter:
"""Convert PDF to PDF/A-3 with embedded ZUGFeRD XML"""
@staticmethod
def create_pdfa3_with_zugferd(pdf_buffer, xml_content, invoice_number):
"""Create PDF/A-3 compliant PDF with embedded ZUGFeRD invoice"""
# Write temporary files
temp_pdf = f'temp_{invoice_number}.pdf'
temp_xml = f'temp_{invoice_number}.xml'
output_pdf = f'invoice_{invoice_number}_PDFA3.pdf'
# Write XML to file
with open(temp_xml, 'wb') as f:
f.write(xml_content.encode('utf-8'))
# Write PDF to file
with open(temp_pdf, 'wb') as f:
f.write(pdf_buffer.getvalue())
# Open with pikepdf
pdf = pikepdf.open(temp_pdf)
# Add XMP metadata for PDF/A-3 compliance
pdf.Root.Pages.Count = pikepdf.Number(len(pdf.pages))
# Create file specification for attachment
filespec = pikepdf.Dictionary(
Type=pikepdf.Name.Filespec,
F=pikepdf.String('invoice.xml'),
UF=pikepdf.String('invoice.xml'),
EF=pikepdf.Dictionary(
F=pikepdf.Stream(pdf, open(temp_xml, 'rb').read())
)
)
# Add to embedded files
if pdf.Root.Names is None:
pdf.Root.Names = pikepdf.Dictionary()
if pdf.Root.Names.EmbeddedFiles is None:
pdf.Root.Names.EmbeddedFiles = pikepdf.Dictionary(
Names=pikepdf.Array()
)
# Add file to embedded files array
names_array = pdf.Root.Names.EmbeddedFiles.Names
names_array.append(pikepdf.String('invoice.xml'))
names_array.append(filespec)
# Add XMP metadata
xmp_content = _generate_xmp_metadata(invoice_number, xml_content)
pdf.Root.Metadata = pikepdf.Stream(pdf, xmp_content.encode('utf-8'))
# Save as PDF/A-3
pdf.save(output_pdf)
# Cleanup
Path(temp_pdf).unlink()
Path(temp_xml).unlink()
return output_pdf
def _generate_xmp_metadata(invoice_number, xml_content):
"""Generate XMP metadata for PDF/A-3"""
return f'''<?xml version="1.0" encoding="UTF-8"?>
<x:xmpmeta xmlns:x="adobe:ns:meta/">
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<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>
<rdf:Description rdf:about=""
xmlns:xmpMM="http://ns.adobe.com/xap/1.0/mm/">
<xmpMM:DocumentID>uuid:{invoice_number}</xmpMM:DocumentID>
</rdf:Description>
</rdf:RDF>
</x:xmpmeta>'''
# Example usage
def create_invoice():
"""Create a complete invoice with ZUGFeRD XML"""
# Sample invoice data
invoice_data = {
'invoice_number': 'INV-2024-001',
'invoice_date': '2024-01-15',
'due_date': '2024-02-15',
'currency': 'EUR',
'seller': {
'name': 'Company ABC GmbH',
'street': 'Hauptstrasse 123',
'postal_code': '12345',
'city': 'Berlin',
'country': 'DE',
'tax_id': 'DE123456789'
},
'buyer': {
'name': 'Client XYZ Ltd',
'street': 'Oak Avenue 456',
'postal_code': '54321',
'city': 'London',
'country': 'GB',
'tax_id': 'GB987654321'
},
'line_items': [
{
'description': 'Consulting Services - January',
'quantity': 40,
'unit': 'HUR', # Hours
'unit_price': 150.00
},
{
'description': 'Software License (Annual)',
'quantity': 1,
'unit': 'C62', # Units
'unit_price': 5000.00
},
{
'description': 'Hardware Support',
'quantity': 3,
'unit': 'C62',
'unit_price': 500.00
}
],
'tax_amount': 1395.00,
'notes': 'Payment due within 30 days. Thank you for your business!'
}
print("📋 Generating Invoice...")
# Generate ZUGFeRD XML
print("🔄 Creating ZUGFeRD XML...")
zugferd = ZUGFeRDGenerator(invoice_data)
xml_content = zugferd.generate_xml()
# Save XML for reference
with open('invoice_zugferd.xml', 'w', encoding='utf-8') as f:
f.write(xml_content)
print(f"✓ ZUGFeRD XML saved: invoice_zugferd.xml")
# Generate PDF
print("📄 Creating PDF...")
pdf_gen = PDFInvoiceGenerator(invoice_data)
pdf_buffer = pdf_gen.generate_pdf()
# Convert to PDF/A-3 with embedded XML
print("🔐 Converting to PDF/A-3 with embedded ZUGFeRD...")
output_file = PDFAConverter.create_pdfa3_with_zugferd(
pdf_buffer,
xml_content,
invoice_data['invoice_number'].replace('/', '-')
)
print(f"✓ Invoice created: {output_file}")
print("\n📊 Invoice Summary:")
print(f" Invoice Number: {invoice_data['invoice_number']}")
print(f" Seller: {invoice_data['seller']['name']}")
print(f" Buyer: {invoice_data['buyer']['name']}")
print(f" Line Items: {len(invoice_data['line_items'])}")
subtotal = sum(item['quantity'] * item['unit_price'] for item in invoice_data['line_items'])
print(f" Subtotal: €{subtotal:.2f}")
print(f" Total: €{subtotal + invoice_data['tax_amount']:.2f}")
return output_file
if __name__ == '__main__':
create_invoice()