Repository navigation
Reading invoices
How to read the invoices you receive with ZeRechnung: hybrid PDFs, CII XML, UBL XML, FatturaPA XML, Facturae XML and old ZUGFeRD 1.0 files.
inv, att, err := zerechnung.Read(pdf)
if err != nil {
log.Fatal(err)
}
fmt.Println(inv.Number, inv.Seller.Name, inv.Totals.DuePayable, inv.Currency)
fmt.Println(att.Filename, att.Relationship, att.Metadata.ConformanceLevel)inv is the EN 16931 model (inv.Number, inv.Seller, inv.Lines, inv.Totals...). att describes the attachment: file name, /AFRelationship, whether it is listed in the catalog's /AF, MIME type, PDF version and the XMP metadata.
If you only need the XML bytes, zerechnung.Extract(pdf) returns the attachment without parsing it. zerechnung.ExtractAll returns every embedded file of the PDF, invoice or not, which is how you get the supporting documents (purchase order, timesheet...).
From the command line:
zerechnung extract -o invoice.xml invoice.pdf # the XML
zerechnung info invoice.pdf # a summary of the PDF and the invoice
zerechnung json invoice.pdf # the parsed model as JSONinv, err := cii.Parse(xml) // CII, ZUGFeRD 1.0 included
inv, err := ubl.Parse(xml) // UBL 2.1 Invoice or CreditNote
inv, err := fatturapa.Parse(xml) // FatturaPA 1.2 (Italy)
inv, err := facturae.Parse(xml) // Facturae 3.2, 3.2.1 or 3.2.2 (Spain)zerechnung.DetectProfile(xml) returns the profile a CII invoice declares in BT-24, without building the model.
Invoices found in the wild are not always clean, so reading is lenient:
- ZUGFeRD 2.0 and 2.1 are read like Factur-X, and ZUGFeRD 1.0 too (see below).
- Any namespace prefix is accepted.
- Misspelled profile identifiers seen in real invoices are recognised.
- An unreadable value (a bad date, a malformed amount) is reported as an issue, and the rest of the document is still read.
The model carries the business data of the EXTENDED profile: extra parties (end user, ultimate ship-to, ship-from), delivery terms, the end customer's orders, the despatch advice, exchange rates, logistics charges, detailed allowances and charges on the price, products included in an item... The EXT-FR-FE-* fields of EXTENDED-CTC-FR map to elements of the EXTENDED XSD and are covered the same way.
What the model has no field for (a fax number, a product brand, discount terms, a listID, an element no schema knows...) is kept as is in the Extensions field of the enclosing value: the invoice, a line, a party, a payment means... inv.Unmodeled() lists them:
inv, _ := cii.Parse(xml)
for _, u := range inv.Unmodeled() {
fmt.Println(u) // "Seller: DefinedTradeContact/FaxUniversalCommunication", "Lines[0]: SpecifiedTradeProduct/BrandName"...
}cii.Marshal puts each extension back in its place, in schema order, and recreates the enclosing elements if needed, as long as the target profile allows it. Otherwise it reports the extension as lost (with Strict).
So an EXTENDED invoice read and written back as EXTENDED gives back its whole tree, apart from normalised forms:
- a
currencyIDequal to BT-5 or BT-6 is left implicit; - attributes from other namespaces (
xsi:schemaLocation) are not kept; - a party's tax registrations are written VA, then FC;
- a party's global identifier is written as
ram:GlobalID; - BT-7 and BT-8 are repeated in every VAT breakdown.
The list of EXTENDED XSD elements and attributes that have no field in the model is kept in cii/testdata/extended-unmodeled.txt.
inv, err := ubl.Parse(xml) // UBL 2.1 Invoice or CreditNote, same model as cii.Parse
out, err := ubl.Marshal(inv, nil) // CreditNote if BT-3 is a credit note code, Invoice otherwise
// UBL to CII
xmlCII, err := cii.Marshal(inv, &cii.MarshalOptions{Profile: invoice.ProfileEN16931})Both syntaxes share one model, so an invoice read in one can be written in the other.
- Reading follows the EN 16931 UBL binding (CEN/TS 16931-3-2) and accepts any namespace prefix. An unreadable value is reported (
ubl.Issue) and reading goes on. -
ubl.Marshalwrites the EN 16931 data set in UBL 2.1 schema order. What the binding cannot carry (the EXTENDED fields of the model, the extensions) is not written;Strictreports it (*ubl.LossError), as withcii.Marshal.
The G-rekening (G-account) extension of NLCIUS is read and written in UBL.
When the cbc:CustomizationID that is read declares the extension (invoice.GAccountExtension), ubl.Parse puts:
- the identifier of each payment means (NL-GA-04) in
PaymentMeans.ID; - each
cac:PaymentTermsin an entry ofinv.PaymentTerms, with its reference to a payment means (NL-GA-02) inPaymentMeansIDand its amount (NL-GA-03) inPartialAmount.
In any other invoice, these elements stay extensions.
ubl.Marshal writes these fields when the cbc:CustomizationID it writes declares the extension, and reports them as lost otherwise. A G-account invoice read and written back still passes the BR-GA rules, with no loss reported by Strict.
CII has no G-account extension. cii.Marshal removes its identifier from BT-24 and reports the loss of the identifiers and references in every profile. The amounts and the second payment term are only written in EXTENDED.
The domestic CIUS-IT invoice carries part of the FatturaPA data in UBL: seven UBL extensions and UBL elements outside EN 16931, listed in appendix 4.2 of the Italian technical rules. When the cbc:CustomizationID that is read declares the extension (invoice.ItalianExtension), ubl.Parse puts them in the Italian blocks of the model, as fatturapa.Parse does:
- the extensions
SistemaEmittente,SoggettoEmittente,TipoDocumento,TipoRitenuta,Art73,RiepilogoIVA:ArrotondamentoandScontoMaggiorazione(with their index::n) ininv.ItalyandVATBreakdown.Italy; - the tax regime (
cbc:TaxLevelCode) and the permanent establishment (cac:AgentParty) of the seller inSeller.Italy, the intermediary (cac:ServiceProviderParty) ininv.Italy.Intermediary; - the carrier, the despatch, the shipment and the delivery terms in
inv.Italy.Transport; - the withholdings (
cac:WithholdingTaxTotal) ininv.Italy.Withholdings; - the dates of the orders and of the transport documents, in the header and on the lines, in
inv.Italy.PurchaseOrdersandTransportDocuments, and the main invoice ininv.Italy.MainInvoice; - the early payment discount and the late payment penalty in
PaymentMeans.Italy.
An extension that does not have exactly the form of appendix 4.2 stays an extension, at its place. In any other invoice, all these elements stay extensions.
ubl.Marshal writes them when the cbc:CustomizationID it writes declares the extension, which it does for a seller in Italy. With Strict, it reports what they cannot carry (bank details, CIG and CUP codes beyond BT-17 and BT-11, delivery time, the withholdings of a credit note...). A FatturaPA invoice converted to UBL and back keeps the rest; the UBL written is checked against the BR-IT-DE rules like any domestic invoice.
fatturapa.Parse reads FatturaPA 1.2, the national format of the Italian SDI, for public administrations (FPA12) and between private parties (FPR12), into the same model:
inv, err := fatturapa.Parse(xml) // the first invoice, with an issue if the file holds several
invs, err := fatturapa.ParseAll(xml) // every invoice of a batch (lotto)
out, err := fatturapa.Marshal(inv, &fatturapa.MarshalOptions{Strict: true})- What appendix 4 of the Italian technical rules maps to EN 16931 goes to the EN 16931 fields. The rest (withholding tax, pension fund, tax regime, REA registration, transport, several orders or contracts...) goes to typed national blocks:
inv.Italy,Party.Italy,Line.Italy,VATBreakdown.Italy,PaymentMeans.Italy,AllowanceCharge.Italy. - An invoice read from FatturaPA has the CIUS-IT profile: written with
cii.Marshalorubl.Marshal, it is checked against the CIUS-IT rules. WithStrict,cii.Marshalreports the national blocks as lost (EXT Italy.Withholdings...), asinv.NationalData()lists them;ubl.Marshalwrites part of them in the Italian extensions of a domestic invoice (see The Italian extensions) and reports the rest. -
fatturapa.Marshalwrites any invoice. When the national blocks are empty, it derives the FatturaPA values from EN 16931 (document type from BT-3, nature from the VAT category, payment method from BT-81, transmitter and sequence number from the seller and BT-1). WithStrict, it lists the EN 16931 terms FatturaPA cannot carry. - Reading is as tolerant as for CII: any namespace prefix, unknown elements kept as extensions and written back, malformed values reported with their path and line. The XAdES signature is skipped; a signed
.p7mfile is opened withfatturapa.Unwrapfirst (see Signed files). -
zerechnung jsonreads FatturaPA too, and prints an array for a batch.
validate.XML and zerechnung validate check a FatturaPA document against its XSD 1.2.4 and the SDI controls on the content that need none of the SDI data, under their codes (see Validating invoices): convert it to UBL to apply the CIUS-IT rules and those of the Italian extensions.
The SDI accepts FatturaPA files signed in CAdES (.xml.p7m, a CMS envelope in DER, or in base64 as such files are often received) or in XAdES (an enveloped signature, the last child of FatturaElettronica), both in Baseline B. fatturapa.Unwrap opens both, nested envelopes included, and returns the document only once every signature verifies against it. zerechnung json reads .xml.p7m files the same way.
doc, sig, err := fatturapa.Unwrap(file) // err when the file does not match its signature; sig lists the signers
inv, err := fatturapa.Parse(doc)
report := fatturapa.VerifySignature(file, &fatturapa.VerifyOptions{
Roots: qualifiedCAs, // nothing is downloaded
OCSP: responses, // or CRLs
At: receivedAt, // when the SDI received the file
Name: "IT01234567890_00001.xml.p7m",
})VerifySignature applies the reception checks of the SDI technical specifications 1.8.4 (§5.1.1) and reports them under the codes of the SDI: 00001 (file name), 00003 (file larger than 5 MB, counted as 5 MiB), 00100 (certificate expired), 00101 (revoked or suspended, according to the CRLs and OCSP responses given), 00102 (signature not valid: the file does not match what was signed), 00103 (no signing time, the riferimento temporale), 00104 (untrusted CA), 00105 (signing time after the reception) and 00107 (certificate not valid). Its own rules IT-SIG-01 to IT-SIG-07 report an unsigned file (an error for FPA12), a certificate that is not qualified or that is issued for seals, trust or revocation left unchecked, a signature that is not Baseline B, and signed content that is not FatturaPA.
SignCAdES and SignXAdES sign with a crypto.Signer, so the key can stay in a smart card, an HSM or a remote signing service, and FileName names the file (see the README).
facturae.Parse reads Facturae 3.2, 3.2.1 and 3.2.2, the Spanish format of the invoices sent to public administrations through FACe and one of the four syntaxes allowed for the B2B invoice (Real Decreto 238/2026, article 7.1), into the same model. The version is given by the namespace of the root element. facturae.Marshal writes Facturae 3.2.2:
inv, err := facturae.Parse(xml) // the first invoice, with an issue if the file holds several
invs, err := facturae.ParseAll(xml) // every invoice of a batch, each with the file header and the parties
out, err := facturae.Marshal(inv, &facturae.MarshalOptions{Strict: true})- No official mapping between Facturae and EN 16931 is published: the package follows its own, described in the package documentation (section Mapping). BT-1 is the series followed by the number; a corrective invoice (OR) reads as 384, a self-billed invoice (AF) as 389, a corrective self-billed invoice as 471.
- What has no EN 16931 term goes to typed national blocks:
inv.Spain,Party.Spain,Line.Spain,VATBreakdown.Spain,PaymentMeans.Spain,AdditionalDocument.Spain. They hold the taxes withheld (IRPF), the equivalence surcharge, the DIR3 administrative centres that FACe requires, the commercial registry data, the payments on account and the executable totals. WithStrict,cii.Marshal,ubl.Marshalandfatturapa.Marshalreport them as lost (EXT Spain.SeriesCode...), asinv.NationalData()lists them. -
facturae.Marshalwrites any invoice. When the national blocks are empty, it derives the Facturae values from EN 16931 (person type and residence from the parties, tax type from the VAT category, payment means from BT-81). A credit note is written as a corrective invoice with its amounts negated and a derivedCorrectiveblock (reason 16, method 01 or 02, tax period). WithStrict, it lists the EN 16931 terms Facturae cannot carry. - Reading is as tolerant as for CII: any namespace prefix, unknown elements kept as extensions and written back, malformed values reported with their path and line. The XAdES signature is skipped, and none is written.
-
zerechnung jsonreads Facturae too, and prints an array for a batch.
validate.XML and zerechnung validate check a Facturae document against the XSD of its version and the readability of its values (see Validating invoices). The EN 16931 rules apply once the invoice is written in UBL or CII.
cii.Parse and zerechnung.Read also read the XML of ZUGFeRD 1.0 PDFs: rsm:CrossIndustryDocument (the 2013 CII syntax, older than D16B) and rsm:Invoice from the 2014 release candidate.
The document is read through a CII D16B view built in memory, without changing it:
- elements are renamed and put back in schema order;
- dates are written in format 102 (ZUGFeRD 1.0 also allows 610 and 616);
- the SEPA mandate reference and the creditor identifier, which ZUGFeRD 1.0 puts on the payment means, move to BT-89 and BT-90.
An unreadable value is located in the original ZUGFeRD 1.0 document.
| ZUGFeRD 1.0 identifier | Profile in the model |
|---|---|
urn:ferd:CrossIndustryDocument:invoice:1p0:basic |
BASIC |
urn:ferd:CrossIndustryDocument:invoice:1p0:comfort |
EN 16931 |
urn:ferd:CrossIndustryDocument:invoice:1p0:extended |
EXTENDED |
The release candidate identifiers (urn:ferd:invoice:rc:basic, comfort, extended) are mapped the same way, and inv.SpecificationID keeps the identifier that was read.
ZUGFeRD 1.0 is read only. cii.Marshal writes the invoice as Factur-X, with the identifier of the target profile. What CII D16B cannot carry (the bank name, the German bank code, a tax type other than VAT...) stays in the extensions and is reported as lost (with Strict).
ZUGFeRD 1.0 predates EN 16931 and CII D16B. The EN 16931, Factur-X and national rules were written for invoices that follow them, and would raise false findings on a valid ZUGFeRD 1.0 invoice. validate therefore applies only a minimal structural check, in the Schema set:
- ZF1-01: a known ZUGFeRD 1.0 identifier;
- ZF1-02: readable values;
- ZF1-03: the data that identifies an invoice (number, type, date, seller, buyer, currency and total amount).
Warning ZF1-04, raised whatever the rule sets, says that a ZUGFeRD 1.0 invoice is not an EN 16931 invoice. The German BMF accepts ZUGFeRD as an e-invoice only from version 2.0.1, and the French reform requires a format that conforms to EN 16931.
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