Skip to content
ERPForAll DocsDevelopment

    PDF page operations, attachments, metadata and e-invoices

    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.

    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.

    • 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 for extract. 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.
    • rotate composes a validated Rotation with inherited quarter-turn rotation on selected pages; siblings keep their original inheritance.
    • stamp imports a one-page overlay into an isolated Form XObject. StampPlacement supplies 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-turn Rotate turns it clockwise about its crop box (the turned box keeps the lower-left corner of the crop box), and UserUnit keeps 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). A UserUnit that 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.

    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.
    }
    PolicySelf-contained annotationsAny other annotation
    AnnotationPolicy::Refuse (default; what merge, extract and split use)document refuseddocument refused
    AnnotationPolicy::KeepSelfContainedcarrieddocument refused; the message names the reason, input and page
    AnnotationPolicy::KeepOrDropcarriedleft 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.

    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:

    • rotate and stamp write the whole document again. Layers, their default state and alternate configurations stay as they are. stamp needs the marked-content sections of the target page and of the overlay page closed (PDF unbalanced marked content otherwise), so the overlay is never drawn inside a hidden layer.
    • merge, extract and split write 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 Unchanged or an intent other than View is refused by design.

    The exact rules and messages are in the specification, section 4.5 (docs/specs/reports/pdf-post-processing.md).

    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.

    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 nested EmbeddedFiles name tree: exact decoded bytes (all files together bounded by decoded_bytes), MIME type, description, AFRelationship, creation/modification dates and whether the catalog AF array 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 with F/UF, EF, MIME and the relationship, and lists it in the catalog AF. Other names stay. A name that exists fails unless Duplicate::Replace is 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), the pdfaid part/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 declares pdfaid:part 3. It reads the profile from the CII guideline identifier (MINIMUM, BASIC WL, BASIC, EN 16931, EXTENDED, XRECHNUNG), embeds the XML as factur-x.xml (or xrechnung.xml for XRECHNUNG) with relationship Data for MINIMUM/BASIC WL and Alternative otherwise, and adds the fx: properties (DocumentType, DocumentFileName, Version, ConformanceLevel from the profile) with their PDF/A extension schema. The producer’s pdfaid level 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.

    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.

    DimensionDefaultCeiling
    Encoded bytes per input64 MiB256 MiB
    Emitted / copied-generated bytes (separate counters)256 MiB1 GiB
    Merge inputs / split results1,02410,000
    Pages10,000100,000
    Admitted source objects / emitted objects1,000,0004,000,000
    Graph nesting64128
    Traversal work units4,000,00016,000,000
    Decoded content bytes16 MiB64 MiB
    Metadata bytes1 MiB4 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.