Repository navigation
Creating invoices
How to turn a PDF into a Factur-X, ZUGFeRD or XRechnung hybrid invoice with ZeRechnung, and what the package does to the file.
- The short version
- What Create does
- PDF/A: the host PDF
- Embedding XML you already have
- Writing the XML only
- Supporting documents
- The /AFRelationship of the XML, by country
- France: VAT on debits
Your application renders the invoice as a PDF, ideally PDF/A-3 (or PDF/A-4 for a PDF 2.0 file). You fill an invoice.Invoice, and zerechnung.Create writes the CII XML for the profile you chose and embeds it in the PDF.
host, _ := os.ReadFile("invoice.pdf") // rendered by your app
pdf, err := zerechnung.Create(host, inv, &zerechnung.CreateOptions{
Calculate: true, // line amounts, totals and VAT breakdown
Validate: &validate.Options{Rules: validate.Default | validate.France},
})
if err != nil {
var verr *zerechnung.ValidationError
if errors.As(err, &verr) {
for _, f := range verr.Report.Errors() {
fmt.Println(f) // error [BR-FR] BR-FR-12_BT-49: ...
}
}
log.Fatal(err)
}
os.WriteFile("invoice-facturx.pdf", pdf, 0o644)A complete French B2B invoice, with the mentions the 2026 reform requires, is in example_test.go.
Calculate fills in the amounts the standard derives from other fields: line net amounts (BT-131), document totals (BT-106 to BT-115) and the VAT breakdown (BG-23). The arithmetic uses exact decimals, never floats.
Validate runs the validation before anything is written to the PDF. If the report has errors, Create embeds nothing and returns a *zerechnung.ValidationError that holds the full report. Create sets validate.Options.Hybrid for you, so an EN 16931 invoice is checked against the Factur-X schematron (see Validating invoices).
The PDF is changed with an incremental update. The original bytes stay as they are, so an existing signature remains valid.
The XMP metadata is merged with what the host already has: PDF/A identification, the fx properties and the extension schema that describes them.
- A PDF 2.0 file, or a host that already declares PDF/A-4, is declared PDF/A-4f (level E is kept). Anything else is declared PDF/A-3.
- Entries of the host's
/Infodictionary that the XMP lacks (title, author, producer, creation date...) are copied into the XMP. - A PDF/A-4 document keeps its metadata in the XMP only. PDF/A-4 admits
/Infoonly when the catalog has aPieceInfoentry, and then only with ModDate (ISO 19005-4, § 6.1.3).Embedtherefore removes/Info, or reduces it to ModDate when the catalog hasPieceInfo.
CreateOptions.Profile picks the profile to write. When it is empty, inv.Profile is used, and EN 16931 when that is empty too.
The host should already meet PDF/A-2, PDF/A-3 or PDF/A-4, which most PDF generators can do with an option. Embed declares PDF/A in the XMP, but it does not touch fonts, colour spaces or output intents.
By default, any host is declared PDF/A anyway, and zerechnung.Check reports afterwards what is missing (rules PDF-01 to PDF-72, page content and font programs included, see Coverage and accuracy).
Set ConvertPDFA to rewrite a host that does not declare PDF/A as PDF/A-3 before the XML is embedded:
pdf, err := zerechnung.Create(host, inv, &zerechnung.CreateOptions{
Embed: zerechnung.EmbedOptions{ConvertPDFA: true},
})
var ce *zerechnung.ConversionError
if errors.As(err, &ce) { // wraps zerechnung.ErrNotConvertible
for _, r := range ce.Reasons {
log.Println(r) // page 1 /Contents: the font "Helvetica" (Type1) shows text but its font program is not embedded…
}
}The conversion is written in pure Go and does not render the pages. It adds a PDF/A output intent (an sRGB profile computed by the package, unless the PDF has one), declares PDF/A-3 level B in the XMP, removes JavaScript, forbidden actions and the other entries PDF/A does not allow, re-encodes LZW streams with Flate, cleans graphics states, images and annotations, and completes the embedded files. What would need a PDF engine is refused, with every reason and where it was found: a font that shows visible text without being embedded, a glyph its font program lacks or whose width differs, DeviceCMYK without a CMYK profile, JPEG 2000 data PDF/A does not allow, a hidden annotation or one without an appearance, a signed document, PDF 2.0. The converted file must pass the PDF/A checks of Check, and the CI runs veraPDF on the converted files of the veraPDF corpus.
zerechnung.ConvertPDFA converts a PDF on its own, and zerechnung pdfa does it on the command line.
To refuse a host that is not PDF/A up front, set RequirePDFA:
pdf, err := zerechnung.Create(host, inv, &zerechnung.CreateOptions{
Embed: zerechnung.EmbedOptions{RequirePDFA: true},
})
if errors.Is(err, zerechnung.ErrNotPDFA) {
// the host's XMP does not declare PDF/A-2, PDF/A-3 or PDF/A-4
}With RequirePDFA, pdfaid:part must be 2, 3 or 4, with a conformance level that exists for that part: A, B or U for parts 2 and 3; none, F or E for part 4. Only the declaration is read. A file can declare PDF/A and still break its rules; Check is the tool for that.
If another system produced the XML, embed it directly:
pdf, err := zerechnung.Embed(host, xml, nil)Embed reads the profile from the XML (BT-24) and writes the attachment, its file specification, the /AF entry and the XMP metadata, like Create. EmbedOptions lets you change the attachment name, its description, its date, its /AFRelationship, and add supporting documents.
xml, err := cii.Marshal(inv, &cii.MarshalOptions{Profile: invoice.ProfileBasic})Only the elements the target profile allows are written, in the order of its schema. Set Strict: true to get an error listing the data that the profile could not carry, instead of dropping it silently.
For UBL output, use ubl.Marshal. See Reading invoices.
Factur-X allows attachments besides the invoice: a purchase order, a timesheet, a delivery note... EmbedOptions.Attachments (and CreateOptions.Embed.Attachments) writes them the same way as the XML: a stream with its MIME type and modification date, /F and /UF, /AFRelationship /Supplement by default, and an entry in /EmbeddedFiles and in the catalog's /AF.
pdf, err := zerechnung.Embed(host, xml, &zerechnung.EmbedOptions{
Attachments: []zerechnung.File{
{Name: "order-4512.pdf", Data: order, Description: "Purchase order 4512"},
{Name: "timesheet.csv", Data: timesheet}, // MIME type from the extension: text/csv
},
})- Without
MimeType, the type is guessed from the extension (PDF, XML, CSV, text, JSON, images, ZIP, OpenDocument, Office), andapplication/octet-streamotherwise. WithoutModDate, the invoice date is used. - The invoice file names (
factur-x.xml,xrechnung.xml,zugferd-invoice.xml, orEmbedOptions.Filename) are refused, whatever the case. - A host attachment with the same name as an added one is replaced.
-
Checkreports an attachment without/AFRelationship(PDF-36), without a MIME type (PDF-37), or missing from every/AFarray (PDF-39).
From the command line: zerechnung embed -xml invoice.xml -attach order.pdf -attach timesheet.csv input.pdf.
The Factur-X 1.09 specification (§ 5.3 and § 6.2.2) sets the relationship between the XML and the PDF by profile and by country:
| Profile | France | Germany |
|---|---|---|
| MINIMUM, BASIC WL | Data |
Data |
| BASIC, EN 16931, EXTENDED, EXTENDED-CTC-FR |
Alternative, Source or Data
|
Alternative |
| XRECHNUNG | n/a | Alternative |
- By default,
EmbedandCreatewriteDatafor MINIMUM and BASIC WL, andAlternativeotherwise. These values work in both countries. -
Embed(and soCreate) refuses anEmbedOptions.Relationshipthat the table excludes: anything butDatafor MINIMUM and BASIC WL, anything butAlternativefor XRECHNUNG or for a seller established in Germany (BT-40 =DE). -
Checkreports a value that does not match the profile (PDF-14, warning).Datafor BASIC and above is not reported when the French rules apply (France, orAutofor a seller in France), since France admits it. -
Checkreports as an error any value other thanAlternativefor BASIC and above when the German rules apply (PDF-40): XRECHNUNG profile,GermanyorGermanyProfilerule sets, orAutofor a seller in Germany.CheckContainer, which takes no options, applies this rule to XRECHNUNG only.
A French service provider who opted to pay VAT on debits ("option pour le paiement de la taxe d'après les débits") must say so on its invoices (article 242 nonies A of annex II to the CGI). The DGFiP carries this mention in BT-8, with the code of the invoice date: 5 in CII, 3 in UBL (rule G1.43 of its external specifications v3.2).
inv.TaxPointDateCode = invoice.TaxPointDebits // "5", written in every VAT breakdown- Without the option, leave BT-8 empty. VAT on services is then due on payment.
- BT-8 excludes the VAT point date BT-7 (BR-CO-03).
- No rule checks the mention. The invoice does not say whether the supplier opted, and the DGFiP states that applications cannot check this rule. The checks that can run on the XML already exist: the code list (BR-CL-06), a single value (CII-SR-462) and the exclusion of BT-7 (BR-CO-03).
- Codes 29 and 72 are still available (
TaxPointDeliveryDate,TaxPointPaymentDate). The specifications v2.3 expressed the option with 29; the DGFiP moved to 5 in v2.4.
Example_vatOnDebits in example_test.go writes and validates such an invoice.
ZeRechnung
Guides
- Creating invoices
- Reading invoices
- Validating invoices
- Coverage and accuracy
- Testing
- License and provenance
By country
- Facturer en France
- E-Rechnungen in Deutschland
- E-facturen in Nederland
- Fatturazione elettronica in Italia
- Facturación electrónica en España
- Guides par pays
En français