Skip to main content

einvoice_pdf/
lib.rs

1//! Extract the embedded e-invoice XML from a Factur-X, `ZUGFeRD` or Order-X PDF (a PDF/A-3
2//! file with the invoice as an associated file), with its XMP metadata, in pure Rust.
3//!
4//! * [`extract`] returns the embedded file named as the specifications require
5//!   ([`INVOICE_FILE_NAMES`]: `factur-x.xml`, `zugferd-invoice.xml`, `ZUGFeRD-invoice.xml`,
6//!   `xrechnung.xml`, `order-x.xml`), its `/AFRelationship`, and the XMP metadata of the
7//!   document catalog with the PDF/A identification and the Factur-X / `ZUGFeRD` properties
8//!   (`DocumentType`, `DocumentFileName`, `Version`, `ConformanceLevel`).
9//! * [`attachments`] returns every embedded file.
10//!
11//! Only the part of PDF (ISO 32000-2) needed to reach embedded files is read: the header,
12//! cross-reference tables and streams with their trailers and incremental updates (`/Prev`,
13//! `/XRefStm`), indirect objects, object streams, the object syntax, `FlateDecode` with the
14//! PNG predictors, the catalog's `/AF` and `/Names /EmbeddedFiles` name tree, file
15//! specification dictionaries and embedded file streams (`/Params /Size` and `/CheckSum`
16//! are verified). Anything else the reader meets on that path, such as another filter, is
17//! refused with [`Error::Unsupported`]; a file that breaks the syntax is refused with
18//! [`Error::Malformed`], never repaired. Encrypted files are refused ([`Error::Encrypted`]):
19//! PDF/A forbids encryption. Page content is never read.
20//!
21//! The input is untrusted: nesting, reference chains, name tree depth, the number of
22//! cross-reference sections and of embedded files, and decoded sizes are bounded by
23//! [`Limits`], each object and object stream is parsed at most once, and cycles are errors.
24//! The crate has no `unsafe` code and builds for `wasm32-unknown-unknown`.
25//!
26//! ```no_run
27//! fn main() -> Result<(), Box<dyn std::error::Error>> {
28//!     let pdf = std::fs::read("invoice.pdf")?;
29//!     let invoice = einvoice_pdf::extract(&pdf)?;
30//!     println!("{}: {} bytes", invoice.xml.file_name, invoice.xml.data.len());
31//!     println!("relationship: {:?}", invoice.xml.relationship);
32//!     if let Some(fx) = invoice.metadata.as_ref().and_then(|m| m.invoice.as_ref()) {
33//!         println!("{:?} {:?} {:?}", fx.document_type, fx.version, fx.conformance_level);
34//!     }
35//!     for attachment in einvoice_pdf::attachments(&pdf)? {
36//!         println!("embedded: {} ({:?})", attachment.file_name, attachment.mime_type);
37//!     }
38//!     Ok(())
39//! }
40//! ```
41
42mod catalog;
43mod document;
44mod error;
45mod filter;
46mod md5;
47mod object;
48mod parser;
49mod text;
50mod xmp;
51mod xref;
52
53use std::fmt;
54
55pub use error::{Error, Location};
56
57use document::Document;
58
59/// The names under which the specifications embed the invoice XML: Factur-X (and
60/// `ZUGFeRD` 2.1 and later), `ZUGFeRD` 2.0, `ZUGFeRD` 1.0, `XRechnung` in `ZUGFeRD`, Order-X.
61pub const INVOICE_FILE_NAMES: [&str; 5] = [
62    "factur-x.xml",
63    "zugferd-invoice.xml",
64    "ZUGFeRD-invoice.xml",
65    "xrechnung.xml",
66    "order-x.xml",
67];
68
69/// Bounds on the work done for one file, against hostile input. Every bound that is
70/// reached is an [`Error::LimitExceeded`] naming the field.
71#[derive(Debug, Clone, PartialEq, Eq)]
72#[non_exhaustive]
73pub struct Limits {
74    /// Nesting of arrays and dictionaries in one object. Default 64.
75    pub max_depth: usize,
76    /// Chains of indirect references, and objects whose reading requires reading others
77    /// (a stream's indirect `/Length`, an object stream). Default 32.
78    pub max_resolution_depth: usize,
79    /// Cross-reference sections (incremental updates). Default 1024.
80    pub max_xref_sections: usize,
81    /// Depth of the `/EmbeddedFiles` name tree. Default 32.
82    pub max_name_tree_depth: usize,
83    /// Embedded files (name tree entries, then distinct files). Default 10 000.
84    pub max_attachments: usize,
85    /// Decoded size of one stream, in bytes. Default 64 MiB.
86    pub max_stream_size: usize,
87    /// Decoded size of all streams together, in bytes. Default 256 MiB.
88    pub max_total_decoded: usize,
89    /// Nodes of the XMP metadata XML tree. Default 1 000 000.
90    pub max_xmp_nodes: u32,
91}
92
93impl Default for Limits {
94    fn default() -> Self {
95        Self {
96            max_depth: 64,
97            max_resolution_depth: 32,
98            max_xref_sections: 1024,
99            max_name_tree_depth: 32,
100            max_attachments: 10_000,
101            max_stream_size: 64 << 20,
102            max_total_decoded: 256 << 20,
103            max_xmp_nodes: 1_000_000,
104        }
105    }
106}
107
108/// The relationship of an associated file to the document (`/AFRelationship`,
109/// ISO 32000-2, 14.13.2, Table 43).
110#[derive(Debug, Clone, PartialEq, Eq)]
111#[non_exhaustive]
112pub enum AfRelationship {
113    /// `/Source`.
114    Source,
115    /// `/Data`.
116    Data,
117    /// `/Alternative`.
118    Alternative,
119    /// `/Supplement`.
120    Supplement,
121    /// `/EncryptedPayload`.
122    EncryptedPayload,
123    /// `/FormData`.
124    FormData,
125    /// `/Schema`.
126    Schema,
127    /// `/Unspecified`.
128    Unspecified,
129    /// Any other name (second-class names are allowed), as written, `#xx` escapes
130    /// decoded and bytes outside UTF-8 replaced.
131    Other(String),
132}
133
134impl AfRelationship {
135    fn from_name(name: &[u8]) -> Self {
136        match name {
137            b"Source" => Self::Source,
138            b"Data" => Self::Data,
139            b"Alternative" => Self::Alternative,
140            b"Supplement" => Self::Supplement,
141            b"EncryptedPayload" => Self::EncryptedPayload,
142            b"FormData" => Self::FormData,
143            b"Schema" => Self::Schema,
144            b"Unspecified" => Self::Unspecified,
145            other => Self::Other(String::from_utf8_lossy(other).into_owned()),
146        }
147    }
148
149    /// The name, without its `/`.
150    #[must_use]
151    pub fn as_str(&self) -> &str {
152        match self {
153            Self::Source => "Source",
154            Self::Data => "Data",
155            Self::Alternative => "Alternative",
156            Self::Supplement => "Supplement",
157            Self::EncryptedPayload => "EncryptedPayload",
158            Self::FormData => "FormData",
159            Self::Schema => "Schema",
160            Self::Unspecified => "Unspecified",
161            Self::Other(name) => name,
162        }
163    }
164}
165
166impl fmt::Display for AfRelationship {
167    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168        f.write_str(self.as_str())
169    }
170}
171
172/// An embedded file: its file specification and its decoded content.
173#[derive(Debug, Clone, PartialEq, Eq)]
174#[non_exhaustive]
175pub struct Attachment {
176    /// The file name: the file specification's `/UF`, else its `/F`, else its key in the
177    /// `/EmbeddedFiles` name tree.
178    pub file_name: String,
179    /// Its key in the `/EmbeddedFiles` name tree, when it is listed there.
180    pub key: Option<String>,
181    /// Whether it is listed in the catalog's `/AF` (associated files).
182    pub in_associated_files: bool,
183    /// `/AFRelationship`.
184    pub relationship: Option<AfRelationship>,
185    /// `/Desc`.
186    pub description: Option<String>,
187    /// The MIME type of the embedded file stream (`/Subtype`), such as `text/xml`.
188    pub mime_type: Option<String>,
189    /// `/Params /Size`, verified against the decoded content.
190    pub size: Option<u64>,
191    /// `/Params /CheckSum`, the MD5 digest, verified against the decoded content. Written
192    /// as the 16 bytes of the digest (ISO 32000-2) or, as some producers do, as its 32
193    /// hexadecimal digits: both are read.
194    pub checksum: Option<[u8; 16]>,
195    /// `/Params /CreationDate`, as written (a PDF date string).
196    pub creation_date: Option<String>,
197    /// `/Params /ModDate`, as written (a PDF date string).
198    pub modification_date: Option<String>,
199    /// The decoded content, byte for byte.
200    pub data: Vec<u8>,
201}
202
203/// The Factur-X / `ZUGFeRD` / Order-X extension schema properties of the XMP metadata.
204#[derive(Debug, Clone, PartialEq, Eq)]
205#[non_exhaustive]
206pub struct InvoiceMetadata {
207    /// The namespace of the properties, such as
208    /// `urn:factur-x:pdfa:CrossIndustryDocument:invoice:1p0#` (any
209    /// `urn:<scheme>:pdfa:CrossIndustryDocument:…` namespace is recognised).
210    pub namespace: String,
211    /// `DocumentType`, such as `INVOICE` or `ORDER`.
212    pub document_type: Option<String>,
213    /// `DocumentFileName`, such as `factur-x.xml`.
214    pub document_file_name: Option<String>,
215    /// `Version`, such as `1.0`.
216    pub version: Option<String>,
217    /// `ConformanceLevel`, the profile, such as `EN 16931`.
218    pub conformance_level: Option<String>,
219}
220
221/// The XMP metadata of the document catalog (`/Metadata`).
222#[derive(Debug, Clone, PartialEq, Eq)]
223#[non_exhaustive]
224pub struct Metadata {
225    /// The decoded metadata stream (UTF-8).
226    pub xmp: String,
227    /// `pdfaid:part`, such as `3`.
228    pub pdfa_part: Option<String>,
229    /// `pdfaid:conformance`, such as `B`.
230    pub pdfa_conformance: Option<String>,
231    /// The Factur-X / `ZUGFeRD` / Order-X properties, when the packet has any.
232    pub invoice: Option<InvoiceMetadata>,
233}
234
235/// What [`extract`] returns.
236#[derive(Debug, Clone, PartialEq, Eq)]
237#[non_exhaustive]
238pub struct Embedded {
239    /// The embedded invoice (or order) XML.
240    pub xml: Attachment,
241    /// The XMP metadata of the document catalog, when it has any.
242    pub metadata: Option<Metadata>,
243    /// The PDF version of the header, such as `1.7`.
244    pub pdf_version: String,
245}
246
247/// The embedded invoice XML of a Factur-X, `ZUGFeRD` or Order-X PDF, with the default
248/// [`Limits`].
249///
250/// # Errors
251///
252/// When the file cannot be read (see [`Error`]), when no embedded file has one of the
253/// [`INVOICE_FILE_NAMES`] ([`Error::NoInvoice`]) or several do ([`Error::Ambiguous`]),
254/// and when the XMP metadata is not well-formed ([`Error::Metadata`]).
255pub fn extract(pdf: &[u8]) -> Result<Embedded, Error> {
256    extract_with(pdf, &Limits::default())
257}
258
259/// [`extract`] with explicit [`Limits`].
260///
261/// # Errors
262///
263/// As [`extract`].
264pub fn extract_with(pdf: &[u8], limits: &Limits) -> Result<Embedded, Error> {
265    let mut doc = Document::load(pdf, limits)?;
266    let catalog = catalog::catalog(&mut doc)?;
267    let object::Object::Dict(catalog) = &*catalog else {
268        return Err(Error::malformed(
269            None,
270            "the document catalog is not a dictionary",
271        ));
272    };
273    let specs = catalog::file_specs(&mut doc, catalog)?;
274    let candidates: Vec<&catalog::FileSpec> = specs
275        .iter()
276        .filter(|spec| INVOICE_FILE_NAMES.contains(&spec.file_name.as_str()))
277        .collect();
278    let spec = match candidates.as_slice() {
279        [] => {
280            return Err(Error::NoInvoice {
281                attachments: specs.iter().map(|s| s.file_name.clone()).collect(),
282            });
283        }
284        [spec] => *spec,
285        several => {
286            return Err(Error::Ambiguous {
287                names: several.iter().map(|s| s.file_name.clone()).collect(),
288            });
289        }
290    };
291    let xml = catalog::attachment(&mut doc, spec)?;
292    let metadata = catalog::metadata_stream(&mut doc, catalog)?
293        .map(|bytes| xmp::parse(bytes, limits.max_xmp_nodes))
294        .transpose()?;
295    Ok(Embedded {
296        xml,
297        metadata,
298        pdf_version: doc.version.clone(),
299    })
300}
301
302/// Every embedded file of a PDF, with the default [`Limits`]: those of the
303/// `/EmbeddedFiles` name tree in key order, then those of the catalog's `/AF` not
304/// already listed.
305///
306/// # Errors
307///
308/// When the file cannot be read, or an embedded file cannot be decoded or fails its
309/// `/Params` checks (see [`Error`]).
310pub fn attachments(pdf: &[u8]) -> Result<Vec<Attachment>, Error> {
311    attachments_with(pdf, &Limits::default())
312}
313
314/// [`attachments`] with explicit [`Limits`].
315///
316/// # Errors
317///
318/// As [`attachments`].
319pub fn attachments_with(pdf: &[u8], limits: &Limits) -> Result<Vec<Attachment>, Error> {
320    let mut doc = Document::load(pdf, limits)?;
321    let catalog = catalog::catalog(&mut doc)?;
322    let object::Object::Dict(catalog) = &*catalog else {
323        return Err(Error::malformed(
324            None,
325            "the document catalog is not a dictionary",
326        ));
327    };
328    let specs = catalog::file_specs(&mut doc, catalog)?;
329    specs
330        .iter()
331        .map(|spec| catalog::attachment(&mut doc, spec))
332        .collect()
333}