PDF page operations, attachments, metadata and e-invoices
PDF page operations
Section titled “PDF page operations”erp-pdf is a pure Rust framework leaf. Report composition code can merge byte buffers, extract or
split pages, rotate selected pages, apply a one-page PDF overlay, embed files, edit Info/XMP metadata and
turn a PDF/A-3 invoice into a Factur-X / ZUGFeRD container. Addons use the report integration; this is not
a new addon dependency or a server endpoint. There is no new end-user print screen or deployment implied
by this API.
Placement and publication
Section titled “Placement and publication”Run foreign or uploaded PDFs inside an isolated report worker with operating-system memory and deadline limits. The library’s byte, graph and work limits, and its caught Rust panics, do not contain allocator abort, stack exhaustion, upstream parser allocation or infinite loops. A caller with no isolated worker must refuse foreign input. The library opens no files, uses no database, clock or network, and keeps no shared state. No converter executable is needed.
Every operation emits to a caller-owned FnMut(&[u8]) -> std::io::Result<()>. An error invalidates all
emitted bytes, including earlier split documents. Buffer privately or use unpublished storage; publish
only after the entire operation succeeds. A sink failure stops input consumption. Retry and cluster
quotas belong to the caller, not a process-local singleton in this crate.
Operations
Section titled “Operations”merge(inputs, limits, emit)accepts a lazy iterator of byte buffers. It loads one document at a time, remaps object references and emits one plain PDF in input/page order. Xref and page bookkeeping grow with bounded output size; this is not a constant-memory claim.PageSelection::new(vec![3, 1], limits)uses one-based page numbers and preserves this order forextract. Empty, zero, repeated and out-of-document selections fail explicitly.split(input, ranges, limits, emit)requires consecutive inclusive ranges covering all pages exactly once. The consumer receives one complete PDF per call. Output bytes are counted across all results.rotatecomposes a validatedRotationwith inherited quarter-turn rotation on selected pages; siblings keep their original inheritance.stampimports a one-page overlay into an isolated Form XObject.StampPlacementsupplies the six finite affine-matrix numbers in target default page coordinates. Crop origins remain source coordinates; the caller chooses translation/scale. The overlay is placed the way a viewer shows its page: a quarter-turnRotateturns it clockwise about its crop box (the turned box keeps the lower-left corner of the crop box), andUserUnitkeeps its physical size (overlay coordinates times the overlay’s unit, divided by the unit of each selected target page; the translation of the placement stays in target units). AUserUnitthat is not a positive number is malformed input, as is a resulting transform whose coefficients overflow or collapse to a singular matrix. Render labels/fonts in the caller’s PDF renderer; this crate adds no text layout engine.
Merge, extract and split are plain reading copies: catalog metadata, attachments, outlines, document structure and archival claims are not carried over; page annotations follow the policy below. Page associations and structural parent references are removed. This is not a general PDF sanitizer. Content streams and ordinary resources remain opaque unless stamping or form flattening needs to decode drawing operations.
The profile refuses signed documents; page annotations, forms and layers have their own sections below. Unsupported cross-document page references fail instead of leaving broken references. Rotation/stamping also refuse output intents or PDF/A identification metadata; they do not certify archival conformance. Drawing operations must balance graphics and text scopes for stamping. Malformed page trees, dangling references, invalid geometry and malformed metadata fail explicitly.
Page annotations
Section titled “Page annotations”Links, notes and highlights are page annotations. A reading copy has a fresh catalog, so an annotation can
be carried only when it needs nothing from the old one. The caller chooses with ReadingCopy:
let summary = ReadingCopy::new() .annotations(AnnotationPolicy::KeepOrDrop) .merge(inputs, &limits, &mut emit)?;if summary.annotations_dropped() > 0 { // Tell the user that some interactive elements are not in the printable copy.}| Policy | Self-contained annotations | Any other annotation |
|---|---|---|
AnnotationPolicy::Refuse (default; what merge, extract and split use) | document refused | document refused |
AnnotationPolicy::KeepSelfContained | carried | document refused; the message names the reason, input and page |
AnnotationPolicy::KeepOrDrop | carried | left out and counted in the summary |
Self-contained are: links to a URI; links with an explicit destination (direct or in a GoTo action) to a
page of the same copy, meaning the same input document in a merge, the same selection in extract and the
same range in split; and the markup types (Text, FreeText with its own appearance, Line, Square, Circle,
Polygon, PolyLine, Highlight, Underline, Squiggly, StrikeOut, Stamp, Caret, Ink) with their popups and
replies, as long as the parent is carried too. Carried annotations point at the copied pages.
Form fields follow the form policy. Not self-contained, and therefore refused or left out: any other annotation type (file
attachments, media, 3D, redaction), named destinations, links to a page outside the copy,
additional actions, chained actions, structure destinations and every action other than URI
and GoTo (scripts, launch, remote go-to, form submission). The URI of a carried link is copied as it is; it is data of the
source document, so show merged foreign documents with the same care as the originals. An annotation that
belongs to a layer is carried with its layer (see Layers).
Use KeepSelfContained for documents the system rendered itself (a failure there is a defect to see) and
KeepOrDrop for uploaded documents that only need a printable copy. ReadingCopy::extract and
ReadingCopy::split take the same policy; the summary of a split covers all its results.
rotate and stamp write the whole document again and keep its annotations as they are; a reader draws
them above the stamped overlay. Unsigned forms are preserved. An overlay page that has annotations is refused.
Unsupported input returns a contextual error. PDF feature <feature> is refused by design marks a combination the library does not plan to process. Other unsupported features identify the missing capability.
Layers (optional content)
Section titled “Layers (optional content)”A PDF can hide part of a page in a layer that is off by default, for example a draft mark or a print-only note. The state of a layer lives in the document catalog, not with the layer, so each operation treats it by what it writes:
rotateandstampwrite the whole document again. Layers, their default state and alternate configurations stay as they are.stampneeds the marked-content sections of the target page and of the overlay page closed (PDF unbalanced marked contentotherwise), so the overlay is never drawn inside a hidden layer.merge,extractandsplitwrite a fresh catalog. The copy lists the layers its pages use and gives each one its default state explicitly, so a hidden layer stays hidden and a shown one stays shown. The layer panel order, automatic states, radio groups and locks are kept for the copied layers. Layers no copied page uses, alternate configurations and the configuration’s name are not carried. A carried annotation that belongs to a layer keeps it: its layer is listed like one the page content uses.- An overlay with layers is refused (
overlay optional content): draw the overlay without layers. - A document whose layer configuration is inconsistent is refused with a message that names the entry,
for example a layer used by a page but missing from the catalog list. A default configuration with base
state
Unchangedor an intent other thanViewis refused by design.
The exact rules and messages are in the specification, section 4.5 (docs/specs/reports/pdf-post-processing.md).
Forms and signed documents
Section titled “Forms and signed documents”rotate and stamp keep an unsigned form as it is: the fields, their values and their appearances are
written again and the result can still be filled in. A field annotation in a document that has no form in
its catalog is refused.
A reading copy has no form. By default a document with a form is refused. To put a filled-in form into a printable copy, flatten it:
let summary = ReadingCopy::new() .forms(FormPolicy::Flatten) .annotations(AnnotationPolicy::KeepOrDrop) .merge(inputs, &limits, &mut emit)?;// summary.fields_flattened(): painted fields and intentionally invisible fields.// summary.annotations_dropped(): includes fields that could not be painted.Flattening paints each field of the copied pages into its page from the appearance the file stores for it, where a reader shows it. The values stay visible; the copy has no fields, no field actions and no field scripts. A field a reader does not show (hidden, no area, an unchecked box) paints nothing.
Some fields cannot be painted from the file alone: a field without a stored appearance, a form that asks the
reader to build all appearances (NeedAppearances, common after a library filled the form without
redrawing it), a field that stays upright on a rotated page, and a widget directly carrying optional-content
membership (a form field with optional-content membership, refused by design). Such a field follows
the annotation policy: Refuse and KeepSelfContained refuse the document and name the reason, input
and page; KeepOrDrop leaves it out and counts it. Check annotations_dropped() before you present a
flattened form as complete: a dropped field is a value the copy does not show. Flattening XFA forms is refused.
A stored appearance may itself use layers: its groups are carried with the configuration described in Layers. A form can coexist with layered page content and ordinary layered annotations. A group missing from the catalog list is refused.
Other annotations still follow the annotation policy. With AnnotationPolicy::Refuse a document whose only
annotations are paintable or intentionally invisible form fields is accepted under FormPolicy::Flatten.
Unsigned XFA content is preserved by rotation and stamping. Overlay documents containing forms are refused.
A signed document is refused by merge, extract, split, rotate and stamp (also as overlay): writing
it again breaks the signature, and a copy is not signed. Keep and send the signed original instead. Detection of signature markers does not verify a signature.
Embedded files, metadata and e-invoices
Section titled “Embedded files, metadata and e-invoices”These edits are incremental updates: the input bytes are emitted unchanged and one update section
follows, so the original is always a prefix of the output and identical inputs give identical bytes.
Encrypted and signed (Perms) inputs are refused.
embedded_files(input, limits)reads every entry of the flat or nestedEmbeddedFilesname tree: exact decoded bytes (all files together bounded bydecoded_bytes), MIME type, description,AFRelationship, creation/modification dates and whether the catalogAFarray lists it. Cyclic or malformed trees fail. Names are returned as data; nothing is written to disk.attach(input, data, &EmbeddedFileOptions::new(name, mime, Relationship::Alternative, modified, limits)?, Duplicate::Refuse, limits, emit)embeds a file withF/UF,EF, MIME and the relationship, and lists it in the catalogAF. Other names stay. A name that exists fails unlessDuplicate::Replaceis given; then the same file specification object is revised so every reference follows the new payload. Names with path separators are refused. PDF/A-1 and PDF/A-2 inputs are refused (arbitrary attachments break those parts).metadata(input, limits)returns Info and XMP values of Title, Author, Subject, Keywords, Creator, Producer, CreationDate and ModDate (dates in ISO 8601 form), thepdfaidpart/level and the raw packet.update_metadata(input, &MetadataUpdate::new().text(MetadataField::Title, "…", limits)?.date(MetadataField::ModDate, date)?, limits, emit)writes the fields to both Info and XMP. Unknown XMP properties are kept byte for byte. A DTD or entity, malformed XML or an oversized packet fails instead of being dropped. Multiple RDF roots and qualified standard values are supported for an unambiguous document subject. Other subjects, nested resource fields and unknown qualifiers are preserved. Titles/subjects update x-default while retaining translations. Author sets one entry; removing qualified later entries is refused. Ambiguous subjects and conflicting standard or PDF/A identification values fail before any bytes are emitted, even when the edit changes a different field. A qualified value needs one consistent representation across its outer property and nested Description.PdfDate::new(…)takes an explicit date and UTC offset.einvoice(input, xml, &EInvoiceOptions::new(EInvoiceName::FacturX, description, date, limits)?, limits, emit)needs an input whose XMP declarespdfaid:part3. It reads the profile from the CII guideline identifier (MINIMUM, BASIC WL, BASIC, EN 16931, EXTENDED, XRECHNUNG), embeds the XML asfactur-x.xml(orxrechnung.xmlfor XRECHNUNG) with relationshipDatafor MINIMUM/BASIC WL andAlternativeotherwise, and adds thefx:properties (DocumentType, DocumentFileName, Version, ConformanceLevel from the profile) with their PDF/A extension schema. The producer’spdfaidlevel and every other property are kept, so Info and XMP stay equal. Existing extension-schema bags receive the new schema entry without changing earlier entries. An unknown profile, repeated Factur-X data/schema, ambiguous or malformed schema container, or non-PDF/A-3 input fails.einvoice_level(xml, limits)returns the profile alone.
Merged downloads stay plain reading copies: merging two e-invoices yields no pdfaid packet and no
embedded files. Structural success is not a PDF/A or Factur-X verdict: veraPDF and an e-invoice
validator are not run by this crate, and producing the PDF/A-3 base document is the renderer’s job.
Limits and errors
Section titled “Limits and errors”PdfLimits::default().with(Limit::InputBytes, bytes)? changes a bound. All bounds have floor one and a
hard ceiling; zero never means unlimited. The public get, name and ceiling methods expose the contract.
The caller supplies these values from worker node configuration; this leaf cannot read administrator settings.
An integration that adds business defaults must declare them at its owning settings scope.
| Dimension | Default | Ceiling |
|---|---|---|
| Encoded bytes per input | 64 MiB | 256 MiB |
| Emitted / copied-generated bytes (separate counters) | 256 MiB | 1 GiB |
| Merge inputs / split results | 1,024 | 10,000 |
| Pages | 10,000 | 100,000 |
| Admitted source objects / emitted objects | 1,000,000 | 4,000,000 |
| Graph nesting | 64 | 128 |
| Traversal work units | 4,000,000 | 16,000,000 |
| Decoded content bytes | 16 MiB | 64 MiB |
| Metadata bytes | 1 MiB | 4 MiB |
These are admission choices, not measured throughput or memory capacities. Source-object accounting includes unreachable objects across all merge inputs and new normalized/imported objects; emitted objects have a separate bound of the same value. Work is shared by library traversals within a public call. Parser-internal work remains subject to worker enforcement. Decoded content is bounded per page, with the completed stamped stream checked again; metadata is bounded per packet. Stamping also charges cumulative generated content and deep-copied resource payload/node storage against the output-byte setting before retaining each copy. This is conservative admission, separate from emitted bytes and actual allocator/RSS usage. Content decoding with non-null DecodeParms is refused rather than silently applying fallback parameters. Caller concurrency multiplies resource needs and requires caller admission.
PdfError::kind() distinguishes invalid options, malformed documents, unsupported features, exceeded limits,
consumer errors and caught panics. Display supplies stable contextual messages without document contents;
std::error::Error::source retains a lower-level cause where available. No performance or PDF/A compliance claim
is made by successful parsing or rendering.