Skip to main content

Document

Struct Document 

Source
pub struct Document { /* private fields */ }
Expand description

A loaded PDF document: retained bytes + parsed structure.

See the module docs for the three design commitments this type embodies (one model, retained buffer, strict eager load).

Implementations§

Source§

impl Document

Source

pub fn load(path: &Path) -> Result<Self, DocError>

Load a document from a file on disk.

§Errors

DocError — I/O, header, xref, or object-level failure; every variant carries the offending offset/object for diagnostics.

Source

pub fn load_with_password( path: &Path, password: Option<&[u8]>, ) -> Result<Self, DocError>

Load a document from disk, supplying a password for an encrypted file.

password is None to mean “no password known” — which is not the same as an empty password. §7.6.3.1 requires a reader to try the empty user password first and silently in either case, so None still opens a permissions-only document with no prompt; what None means is that if that fails, there is nothing else to try and the load returns DocError::PasswordRequired.

Either the user or the owner password opens the document (§7.6.3.1). Which one it was is reported by Document::encryption.

§Errors

DocError — as Document::load, plus DocError::Encryption for a configuration pdfcer will not decrypt and DocError::PasswordRequired when no supplied password authenticated.

Source

pub fn load_with_options( path: &Path, password: Option<&[u8]>, options: LoadOptions, ) -> Result<Self, DocError>

Load a document from disk under explicit LoadOptions — the path-shaped twin of Document::from_bytes_with_options.

§Why this exists as well as the bytes form

Pass 283.0 gave the loader a tolerant posture and gave the operator the other choice, but shipped the choice on the bytes entry point only. Every shell that opens a document opens a file — the GUI’s open-file action, the CLI’s path argument — so taking the alternative reading meant re-implementing Document::load’s std::fs::read at each call site. An intervention route the intended caller can only reach by rewriting the route beside it is not offered, it is merely present.

The operator’s ruling this discharges: “if the user can intervene in a decision that should always be an option along with them not having to intervene.” Re-loading the same path under LoadOptions::new().with_duplicate_keys(DuplicateKeyPolicy::KeepFirst) is the whole intervention; see Document::load_anomalies for how a shell learns there was a decision to intervene in.

§Examples
use std::path::Path;
use pdfcer_model::document::{Document, LoadOptions};
use pdfcer_model::parser::DuplicateKeyPolicy;

let path = Path::new("drawing.pdf");
let doc = Document::load(path)?;
if !doc.load_anomalies().is_empty() {
    // Offer the operator the other reading; nothing forces them to take it.
    let other = Document::load_with_options(
        path,
        None,
        LoadOptions::new().with_duplicate_keys(DuplicateKeyPolicy::KeepFirst),
    )?;
    let _ = other;
}
§Errors

DocError — as Document::load_with_password. Under LoadOptions::strict() this refuses every malformation Pass 283.0 taught the loader to decide.

Source

pub fn from_bytes(buf: Vec<u8>) -> Result<Self, DocError>

Load a document from bytes (takes ownership — the buffer is retained for the document’s lifetime; see module docs).

§Errors

DocError — see Document::load.

Source

pub fn from_bytes_with_password( buf: Vec<u8>, password: Option<&[u8]>, ) -> Result<Self, DocError>

Load a document from bytes, supplying a password for an encrypted file.

See Document::load_with_password for what None means (it is not the empty password).

§Errors

DocError — see Document::load_with_password.

Source

pub fn from_bytes_with_options( buf: Vec<u8>, password: Option<&[u8]>, options: LoadOptions, ) -> Result<Self, DocError>

Load a document, choosing how its self-contradictions are decided (Pass 283.0).

The intervention half of the operator’s ruling: a shell that has shown the operator what pdfcer chose (via Document::load_anomalies) and been told to take the other value re-loads the same bytes through here. Everything else is identical to Document::from_bytes_with_password, which is this with the defaults.

§Errors

DocError — see Document::load_with_password.

Source

pub fn reopen_appended(&self, buf: Vec<u8>) -> Result<Self, DocError>

Load buf — bytes produced by saving this document incrementally — decrypting under this document’s file key and access, with no password. An unencrypted document loads buf like Document::from_bytes.

The contract is that buf keeps this document’s /Encrypt and /ID[0] (an incremental save carries both, ISO 32000-2 §7.6.3); bytes from anywhere else decrypt to noise.

§Errors

DocError — see Document::load.

Source

pub fn encryption(&self) -> Option<&DocumentEncryption>

How this document was encrypted, if it was – None for a plain file.

A disclosure, not a gate. See DocumentEncryption.

Source

pub fn set_rc4_append(&mut self, policy: Rc4Append)

Choose whether an incremental save of an RC4-encrypted document keeps its RC4 handler (Rc4Append::Preserve) or is refused (Rc4Append::Refuse, the default). No effect on a plain or AES document.

Preserve keeps existing signatures valid, at a cost the save reports in SaveReport::rc4_keystream_reused: an edited object rewritten under its old number and generation is encrypted with the same RC4 keystream as its previous revision. Decision 190.

Source

pub fn bytes(&self) -> &[u8] ⓘ

The retained source bytes (the coordinate system every span in this document indexes into).

Source

pub fn view(&self) -> DocumentView<'_>

A read view of this document for the rasterizer, the vector object model and pageops — the file exactly as loaded.

The mirror of EditSession::view, and the reason every read path can take one parameter type (DocumentView) instead of two overloads. A Document has no overlay and no staging buffer, so its view carries a StreamSource::Contiguous over Document::bytes — meaning “render the file as it is on disk”, which is exactly what pdfcer and the round-trip tools want — and why pdfcer-render’s &Document back-compat wrappers can build one implicitly without changing any caller’s behaviour.

Cheap: two borrows plus a version probe. Building one per call is the intended usage; there is nothing to cache.

§Examples
use pdfcer_model::document::Document;
use pdfcer_model::graph::ObjectGraph;

let doc = Document::from_bytes(
    include_bytes!("../../../fixtures/synthetic/hello.pdf").to_vec(),
)?;
let view = doc.view();
assert_eq!(view.version(), doc.version());
assert_eq!(view.catalog_id(), doc.catalog_id());
Source

pub const fn trailer(&self) -> &Dict

The newest trailer dictionary (§7.5.5 Table 15).

Source

pub const fn xref(&self) -> &XrefTable

The merged cross-reference table.

Source

pub fn version(&self) -> PdfVersion

The document’s effective version: the header’s %PDF-M.N, upgraded by the catalog’s /Version name if present and higher (§7.5.5: version = max of the two; the catalog entry exists so an incremental update can raise the version without touching byte 0).

Source

pub fn get(&self, id: ObjId) -> Option<&IndirectObject>

Look up an indirect object by full identity, applying the §7.3.10/§7.5.4 rules (module docs): dangling, stale-generation, and free all yield None here — callers wanting the null-object semantics use Document::resolve, which maps None to Object::Null.

Source

pub fn resolve<'a>(&'a self, obj: &'a Object) -> &'a Object

Resolve obj to a non-reference value: follow reference chains (depth-guarded), mapping every unresolvable case to the null object per §7.3.10. Non-reference objects return themselves.

Source

pub fn catalog(&self) -> Result<&Dict, DocError>

The document catalog (§7.7.2) — the dictionary the trailer’s required /Root reference points at.

§Errors

DocError::NoCatalog if /Root is missing, not a reference, or doesn’t resolve to a dictionary.

Source

pub fn object_count(&self) -> usize

Number of parsed (in-use) objects.

Source

pub fn objects(&self) -> impl Iterator<Item = &IndirectObject>

Iterate all parsed indirect objects (unordered).

Source

pub const fn base_startxref(&self) -> u64

The byte offset this file’s own startxref names (§7.5.5).

This is the value an appended update’s /Prev must carry — §7.5.6: “a Prev entry giving the location of the previous cross-reference section”, which is the section startxref currently points at. Taking the base trailer’s own /Prev instead is the classic off-by-one-revision bug: it would skip a revision and silently resurrect superseded objects.

Source

pub const fn section_shape(&self) -> SectionShape

The physical form of the newest cross-reference section.

The writer matches this rather than choosing (R33): emitting a cross-reference stream where the base file had a classic table silently raises a PDF 1.4 document’s effective version to 1.5. §7.5.6 does not require the match — that is a recorded spec silence — which is exactly why pdfcer imposes it.

Source

pub const fn is_hybrid(&self) -> bool

Whether this file is a §7.5.8.4 hybrid-reference file: a classic cross-reference section whose trailer carries /XRefStm.

Hybrid files are readable by pre-1.5 readers and carry the PDF 1.5 features those readers cannot see. Incremental save preserves that duality (form A: a classic update section carrying /XRefStm forward); a full rewrite cannot, and refuses by name rather than flattening it.

Source

pub fn load_anomalies(&self) -> &[LoadAnomaly]

Every contradiction this file contained that pdfcer decided rather than refused (Pass 283.0).

§The three obligations this satisfies at once

The operator’s ruling: “we should be making pdfcer so that it opens pdfs that have errors, and have a way that it manages those errors such that they aren’t fatal, and if the user can intervene in a decision that should always be an option along with them not having to intervene.”

  • Not fatal — the document is loaded; this list is a report about it, not a gate in front of it.
  • Intervention possible — each entry names what pdfcer chose and what it chose between, which is what a shell needs to offer the alternative. Re-load through Document::from_bytes_with_options with the other policy to take it.
  • Intervention optional — a caller that never reads this gets a working document with pdfcer’s documented default.

Empty for a file that contains no contradiction, which is the overwhelming majority. A non-empty list is not a warning that anything is wrong with pdfcer’s output — it is the file saying two things.

Source

pub const fn hybrid_partition(&self) -> &HybridPartition

This file’s §7.5.8.4 partition — which objects it hides behind /XRefStm, and whether pdfcer could read the stream that says so (Pass 281.0).

§Why a writer needs it, and why re-deriving it would be wrong

§7.5.8.4 describes a three-part unit a writer creates “at the same time”: a main classic table marking the hidden objects free with generation 65535, an update section, and a cross-reference stream giving their real locations. Rewriting such a file means rebuilding that unit, which means knowing which side each object belongs on.

§7.5.8.4’s visibility rule answers a different question — what a producer is permitted to hide. This answers what this file did hide. A file may legally hide less than it could, and a rewrite that re-derived the maximum would move objects the operator never touched, which is exactly the “plausible, working, wrong file” R33 guards against.

Empty and readable for every non-hybrid file. See crate::xref::HybridPartition::is_reproducible for the case that still refuses: a file that says it hides objects and whose stream pdfcer could not parse.

Source

pub const fn recovery(&self) -> Option<&RecoveryReport>

The cross-reference recovery record, or None for a cleanly loaded file (decision 013).

Some means the stored cross-reference table could not be parsed and pdfcer rebuilt it by scanning the file for N G obj headers (rebuild-by-scan). The returned RecoveryReport carries the counted disclosure (why the strict path failed, how many objects came from the file-level scan vs. object streams, collisions, trailer source, offset-start). This is a reviewable fact (fuzzy-never-sneaky, R20): the CLI prints it and forces a distinct exit status, and the GUI shows a banner. A recovered document also cannot be saved incrementally — see Document::save_incremental’s refusal.

Source

pub const fn loaded_via_recovery(&self) -> bool

Whether this document was loaded via cross-reference recovery (decision 013) — the shorthand the writer’s incremental-save refusal and the front ends’ disclosure branch on.

Source

pub const fn linearization(&self) -> Linearization

Annex F linearization (“Fast Web View”) state, detected at load.

Reported so a save can warn before spending the property (F.1: an incremental update “shall” de-linearize). pdfcer never repairs it and never strips a stale /Linearized dictionary — see crate::linearization.

Source

pub fn save_incremental( &self, path: &Path, dirty: &DirtySet, options: &SaveOptions, ) -> Result<SaveReport, WriteError>

Save an incremental update (§7.5.6) to path.

This is pdfcer’s default save mode (ARCHITECTURE.md §5): the existing bytes are copied untouched and a new revision is appended, which is what keeps any pre-existing digital signature’s /ByteRange digest valid (§12.8.1 NOTE 1).

dirty is the save-time diff against the base revision, and the only thing that should compute one is pdfcer_core::edit::EditSession::dirty_set — see ARCHITECTURE.md §11.1 for the “union of every command ever run” bug that a hand-built dirty set reintroduces. An empty one gives byte-identical output.

⚠️ Incremental save structurally preserves superseded content. The old bytes of every replaced object remain in the file by construction. Any operation whose contract is removal — redaction above all — must therefore use Document::save_full and must refuse this mode (R35).

§Errors

crate::writer::WriteError — I/O, a broken provenance span, or a cross-reference form that cannot express an entry.

Source

pub fn save_full( &self, path: &Path, dirty: &DirtySet, options: &SaveOptions, ) -> Result<SaveReport, WriteError>

Rewrite the whole document to path as a single revision.

Every File-provenance object is re-emitted from its retained source bytes verbatim; only the header prefix, object offsets, the cross-reference section and the trailer are regenerated. So byte identity holds per object definition, never for the file as a whole (R32) — offsets legitimately move.

⚠️ A full rewrite invalidates every existing digital signature, because a signature covers a byte range that this mode necessarily disturbs (§12.8.1). That collides with R35’s requirement that redaction use this mode; “redact a signed document” is a genuine either/or for the operator to resolve, never something pdfcer decides silently (R36, decision 007 W7).

§Errors

crate::writer::WriteError, notably WriteError::HybridFullRewrite for a §7.5.8.4 hybrid-reference input.

Source

pub fn next_object_number(&self) -> Option<u32>

The lowest object number this document does not already account for — where a newly created object goes.

Four sources are consulted, and taking the maximum of all four is the point:

  1. the highest number the cross-reference chain mentions before the /Size filter runs. The unfiltered number, deliberately: /Size is a hard reader-side filter, so a file that under-reports it loads with real entries invisible, and allocating from the filtered view picks a number the file already defines. That produces an update section whose entry collides with a live object — a file that looks fine and resolves to the wrong bytes. Found by the writer_roundtrip fuzz target, on a corpus file carrying /Size 3 over six entries.

    Free entries count too. A free number is reusable in principle (§7.5.4’s free list exists to be consumed), but reusing one correctly means honouring the generation rules — a resurrected object takes the free entry’s generation — and pdfcer has no deletion path to have created those entries in the first place. Allocating past them is always safe; consuming them is Pass 3.2 work.

  2. every parsed object, in case the two disagree;

  3. the trailer’s /Size, so a stale, oversized /Size cannot hand out a number that a /Prev revision defines and this merged view dropped.

  4. the newest cross-reference STREAM’s own object number, when the file has one (Document::section_shape).

§Why source 4 exists, and the bug it closes

A cross-reference stream is an indirect object, and the writer reuses its number for the update section it emits (R33: match the base’s section shape). But it is the section, not a body object — the parser never files it in objects, and there is no requirement anywhere that it appear in its own /Index or be covered by its own /Size.

So a file can carry 75 0 obj << /Type /XRef /Size 75 /Index [9 1 29 45] >>: object 75 exists, and every one of sources 1–3 answers 74. This function then handed out 75, the session wrote its new object there, and the writer wrote its own cross-reference stream over the top of it — same object number, later in the file, so the session’s object simply vanished and the reader resolved the reference to the xref stream.

The failure is silent in the worst way: the file parses, opens, and renders. Only the one thing the edit added is missing. Found by tools/embed-sweep over the pdfium corpus (testing/resources/annotation_stamp_with_ap.pdf), where an embedded font program came back as a 44-byte cross-reference stream and the text it should have drawn was silently skipped.

This was never specific to font embedding. Any command that creates an object — adding text, an image, an annotation, a form field — hits it on any file shaped this way. It survived because a collision needs a file whose xref stream is outside its own /Size, which no producer pdfcer’s fixtures came from emits.

Returns None only if the document already reaches u32::MAX, which Annex C’s implementation limits put far out of reach for any real file — reported rather than wrapped, because silently allocating object 0 would corrupt the free list.

⚠️ A caller must also check Document::suppressed_object_count before creating an object: a valid number is not by itself a licence to write one.

Source

pub const fn suppressed_object_count(&self) -> usize

How many cross-reference entries this file’s /Size is hiding.

§Why anyone cares (and why it blocks object creation)

Table 15 / §7.5.5 make /Size a hard filter: an object numbered at or above it “shall be ignored and defined to be missing”. A file whose /Size under-reports is therefore relying on the filter — the entries above it are invisible, and the document may only be loadable at all because they are (they can point at bytes that do not parse).

Creating an object raises /Size. That does not merely add the new object: it exposes every suppressed entry below the new number, resurrecting objects the operator never touched. Two separate rules say no — §5’s minimal-diff invariant (an edit must not change objects it did not name) and R27’s fail-clean posture (name the refusal rather than produce a plausible wrong file).

So a non-zero count means “an edit may modify existing objects in this file, but must not create one”. The eventual fix is to emit explicit free entries (§7.5.4, generation 65535 — the very mechanism §7.5.8.4 uses to hide an object) for the exposed range, which needs free-list writing that Pass 3.2 brings.

Zero for essentially every well-formed file, which is why this is a refusal rather than a feature gap worth blocking on.

Trait Implementations§

Source§

impl Clone for Document

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Document

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl ObjectGraph for Document

The loaded file, as a graph.

Document already has inherent resolve/catalog methods with the same semantics; those keep working and keep winning method resolution (inherent methods are preferred), so this impl adds a generic entry point without changing a single existing call site.

Source§

fn value(&self, id: ObjId) -> Option<&Object>

The current value of id, or None when this view has no such object. Read more
Source§

fn trailer_entry(&self, key: &[u8]) -> Option<&Object>

The current value of the trailer entry key, or None. Read more
Source§

fn resolve<'a>(&'a self, obj: &'a Object) -> &'a Object

Follow a reference chain to a non-reference value, applying §7.3.10’s rules: an unresolvable reference yields null rather than an error, and the chain is depth-guarded (MAX_RESOLVE_DEPTH) so 5 0 obj 5 0 R endobj — legal syntax — cannot loop.
Source§

fn resolved(&self, id: ObjId) -> &Object

Resolve id directly to a non-reference value, or null. Read more
Source§

fn catalog_dict(&self) -> Option<&Dict>

The document catalog (§7.7.2) — the dictionary the trailer’s /Root points at — or None if the file has no usable one. Read more
Source§

fn catalog_id(&self) -> Option<ObjId>

The object id the trailer’s /Root names, if it is a reference. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.