Skip to content

generate()

Embed an XML invoice into a PDF and return a compliant PDF/A-3 as bytes.

Signature

ts
function generate(options: {
  pdf: string | Buffer | PDFDocument
  xml: string | Buffer | XMLDocument
  check?: boolean
  flavor?: string
  level?: string
  language?: string
  meta?: PdfMetadata
}): Promise<Uint8Array>

Options

OptionTypeDefaultDescription
pdfstring | Buffer | PDFDocumentRequired. Source PDF (path/bytes already read, or a pdf-lib document).
xmlstring | Buffer | XMLDocumentRequired. Invoice XML to embed.
checkbooleanfalseSet true to run XSD validation before embedding; throws on invalid XML.
flavorstringautodetectfacturx, orderx or zugferd.
levelstringautodetectSchema level (e.g. en16931).
languagestringPDF language code (RFC 3066), e.g. en-GB.
metaPdfMetadataderived from XMLOverride the PDF document metadata.

PdfMetadata:

ts
interface PdfMetadata {
  author: string
  title: string
  subject: string
  keywords: string[]
  date: Date
}

Returns

Promise<Uint8Array> — the bytes of the generated PDF/A-3, ready to write to disk or stream.

Behaviour

  • Chooses the embedded filename from the flavor: factur-x.xml, order-x.xml or zugferd-invoice.xml, and writes the matching PDF/A-3 XMP metadata (including the Factur-X conformanceLevel for the level).
  • When meta is omitted, the title/author/subject/date are derived from the invoice XML.
  • Throws Invalid XML format (<flavor> - <level>) when check is enabled and validation fails, and Unknown schema flavor for an unrecognised flavor.

Example

This is a real, runnable script from the repo's examples/ — it reads the bundled fixtures and embeds the XML:

ts
import { readFile, writeFile } from 'node:fs/promises'
import { generate } from '@stafyniaksacha/facturx'

const pdf = await readFile('source-invoice.pdf')
const xml = await readFile('Facture_FR_EN16931.xml')

const bytes = await generate({
  pdf,
  xml,
  // all optional:
  flavor: 'facturx',
  level: 'en16931',
  language: 'en-GB',
  meta: {
    author: 'Acme Corporation',
    title: 'Invoice INV-2023-001',
    subject: 'Invoice',
    keywords: ['invoice', 'factur-x'],
    date: new Date(),
  },
})

await writeFile('facturx.pdf', bytes)

See also

Released under the MIT License.