Skip to content

extract()

Extract the embedded XML invoice from a Factur-X / Order-X / ZUGFeRD PDF.

Signature

ts
function extract(options: {
  pdf: string | Buffer | PDFDocument
  check?: boolean
  flavor?: string
  level?: string
}): Promise<{
  filename: string
  xml: string
  flavor?: string
  level?: string
}>

Options

OptionTypeDefaultDescription
pdfstring | Buffer | PDFDocumentRequired. The PDF to read.
checkbooleanfalseSet true to XSD-validate the extracted XML; throws Invalid XML on failure.
flavorstringautodetectAssert an expected flavor; mismatches throw.
levelstringautodetectSchema level used for the validation step.

Returns

FieldTypeDescription
filenamestringThe embedded attachment filename (e.g. factur-x.xml).
xmlstringThe extracted XML as a string.
flavorstring?The detected (or asserted) flavor.
levelstring?The level, if provided.

Behaviour

  • Scans the PDF attachments for a recognised e-invoice filename (factur-x.xml, order-x.xml, or a ZUGFeRD filename) and returns the first match.
  • The flavor is inferred from the attachment filename. Passing flavor asserts an expectation: e.g. flavor: 'facturx' throws Invalid flavor, expected facturx but found orderx if the PDF actually contains an Order-X file.
  • Throws No attachment found when no recognised XML is present.
  • Validation is off by default; pass check: true to XSD-validate the extracted XML (Invalid XML is thrown on failure).

Example

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

const pdf = await readFile('Facture_FR_EN16931.pdf')

const { filename, xml, flavor } = await extract({ pdf })
console.log(`found ${filename} (${flavor})`)

await writeFile('factur-x.xml', xml)
ts
// Require the PDF to be Factur-X, and XSD-validate the extracted XML
const { xml } = await extract({ pdf, flavor: 'facturx', check: true })

See also

Released under the MIT License.