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
impl Document
Sourcepub fn load_with_password(
path: &Path,
password: Option<&[u8]>,
) -> Result<Self, DocError>
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.
Sourcepub fn load_with_options(
path: &Path,
password: Option<&[u8]>,
options: LoadOptions,
) -> Result<Self, DocError>
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.
Sourcepub fn from_bytes(buf: Vec<u8>) -> Result<Self, DocError>
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.
Sourcepub fn from_bytes_with_password(
buf: Vec<u8>,
password: Option<&[u8]>,
) -> Result<Self, DocError>
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
Sourcepub fn from_bytes_with_options(
buf: Vec<u8>,
password: Option<&[u8]>,
options: LoadOptions,
) -> Result<Self, DocError>
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
Sourcepub fn reopen_appended(&self, buf: Vec<u8>) -> Result<Self, DocError>
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.
Sourcepub fn encryption(&self) -> Option<&DocumentEncryption>
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.
Sourcepub fn set_rc4_append(&mut self, policy: Rc4Append)
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.
Sourcepub fn bytes(&self) -> &[u8] ⓘ
pub fn bytes(&self) -> &[u8] ⓘ
The retained source bytes (the coordinate system every span in this document indexes into).
Sourcepub fn view(&self) -> DocumentView<'_>
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());Sourcepub fn version(&self) -> PdfVersion
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).
Sourcepub fn get(&self, id: ObjId) -> Option<&IndirectObject>
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.
Sourcepub fn resolve<'a>(&'a self, obj: &'a Object) -> &'a Object
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.
Sourcepub fn catalog(&self) -> Result<&Dict, DocError>
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.
Sourcepub fn object_count(&self) -> usize
pub fn object_count(&self) -> usize
Number of parsed (in-use) objects.
Sourcepub fn objects(&self) -> impl Iterator<Item = &IndirectObject>
pub fn objects(&self) -> impl Iterator<Item = &IndirectObject>
Iterate all parsed indirect objects (unordered).
Sourcepub const fn base_startxref(&self) -> u64
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.
Sourcepub const fn section_shape(&self) -> SectionShape
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.
Sourcepub const fn is_hybrid(&self) -> bool
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.
Sourcepub fn load_anomalies(&self) -> &[LoadAnomaly]
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_optionswith 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.
Sourcepub const fn hybrid_partition(&self) -> &HybridPartition
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.
Sourcepub const fn recovery(&self) -> Option<&RecoveryReport>
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.
Sourcepub const fn loaded_via_recovery(&self) -> bool
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.
Sourcepub const fn linearization(&self) -> Linearization
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.
Sourcepub fn save_incremental(
&self,
path: &Path,
dirty: &DirtySet,
options: &SaveOptions,
) -> Result<SaveReport, WriteError>
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.
Sourcepub fn save_full(
&self,
path: &Path,
dirty: &DirtySet,
options: &SaveOptions,
) -> Result<SaveReport, WriteError>
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.
Sourcepub fn next_object_number(&self) -> Option<u32>
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:
-
the highest number the cross-reference chain mentions before the
/Sizefilter runs. The unfiltered number, deliberately:/Sizeis 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 thewriter_roundtripfuzz target, on a corpus file carrying/Size 3over 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.
-
every parsed object, in case the two disagree;
-
the trailer’s
/Size, so a stale, oversized/Sizecannot hand out a number that a/Prevrevision defines and this merged view dropped. -
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.
Sourcepub const fn suppressed_object_count(&self) -> usize
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 ObjectGraph for Document
The loaded file, as a graph.
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 resolve<'a>(&'a self, obj: &'a Object) -> &'a Object
fn resolve<'a>(&'a self, obj: &'a Object) -> &'a Object
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.