Skip to main content

zpdf_document/
lib.rs

1pub mod annot_appearance;
2pub mod annotation;
3mod catalog;
4pub mod destinations;
5pub mod doc_info;
6pub mod embedded_files;
7pub mod font_loader;
8pub mod forms;
9pub mod ink;
10pub mod measure;
11mod obj_util;
12pub mod optional_content;
13pub mod outline;
14pub mod output_intents;
15pub mod page;
16pub mod page_labels;
17pub mod signature;
18pub mod structure;
19pub mod xmp;
20
21pub use annotation::Annotation;
22pub use catalog::Catalog;
23pub use destinations::{DestView, Destination};
24pub use doc_info::DocInfo;
25pub use embedded_files::{EmbeddedFile, EmbeddedSource};
26pub use forms::{
27    build_resources, escape_text, generate_widget_appearance, standard_font_dict,
28    unicode_to_winansi, AcroForm, FieldKind, FieldValue, FormField, GeneratedAppearance,
29    FF_READONLY,
30};
31pub use ink::{InkAnnotDict, InkAnnotationBuilder};
32pub use measure::{GeographicCoordinateSystem, Measure};
33pub use optional_content::OcConfig;
34pub use outline::OutlineItem;
35pub use output_intents::OutputIntent;
36pub use page::{PdfPage, ResourceDict};
37pub use page_labels::{PageLabelStyle, PageLabels};
38pub use signature::{ByteRangeCoverage, CryptoStatus, DigestStatus, Signature};
39pub use structure::{StructElem, StructKid, StructRole, StructTree};
40pub use xmp::XmpMetadata;
41
42use std::collections::HashMap;
43use std::sync::{Arc, OnceLock};
44use zpdf_core::{Error, ParseLimits, PdfObject, Result};
45use zpdf_font::FontCache;
46use zpdf_parser::PdfFile;
47
48pub struct PdfDocument {
49    file: PdfFile,
50    catalog: Catalog,
51    /// Lazily-parsed interactive form, shared across page-annotation calls so
52    /// the field-tree walk runs at most once per document.
53    acro_form: OnceLock<Option<AcroForm>>,
54    /// Lazily-flattened named-destination map, shared across page-annotation
55    /// calls so resolving link targets never re-walks the name tree per page —
56    /// a full-document link scan stays O(pages × links + tree), not O(pages ×
57    /// tree).
58    named_dests: OnceLock<HashMap<Vec<u8>, PdfObject>>,
59}
60
61impl PdfDocument {
62    pub fn open(data: impl Into<Arc<[u8]>>) -> Result<Self> {
63        Self::open_with_limits(data, ParseLimits::default())
64    }
65
66    pub fn open_with_limits(data: impl Into<Arc<[u8]>>, limits: ParseLimits) -> Result<Self> {
67        Self::open_with_password_and_limits(data, b"", limits)
68    }
69
70    /// Open an encrypted document with a user or owner password. Returns
71    /// [`zpdf_core::Error::WrongPassword`] when the password authenticates as
72    /// neither. (A non-encrypted document opens regardless of the password.)
73    pub fn open_with_password(data: impl Into<Arc<[u8]>>, password: &[u8]) -> Result<Self> {
74        Self::open_with_password_and_limits(data, password, ParseLimits::default())
75    }
76
77    pub fn open_with_password_and_limits(
78        data: impl Into<Arc<[u8]>>,
79        password: &[u8],
80        limits: ParseLimits,
81    ) -> Result<Self> {
82        let file = PdfFile::parse_with_password_and_limits(data, password, limits)?;
83        let catalog = Catalog::from_trailer(&file)?;
84        Ok(Self {
85            file,
86            catalog,
87            acro_form: OnceLock::new(),
88            named_dests: OnceLock::new(),
89        })
90    }
91
92    /// True when the document is encrypted (carries an `/Encrypt` dictionary).
93    pub fn is_encrypted(&self) -> bool {
94        self.file.is_encrypted()
95    }
96
97    pub fn page_count(&self) -> usize {
98        self.catalog.page_count
99    }
100
101    pub fn page(&self, index: usize) -> Result<PdfPage> {
102        self.catalog.get_page(&self.file, index)
103    }
104
105    pub fn file(&self) -> &PdfFile {
106        &self.file
107    }
108
109    pub fn version(&self) -> (u8, u8) {
110        (self.file.header.major, self.file.header.minor)
111    }
112
113    /// Get decoded content stream bytes for a page.
114    pub fn page_content_bytes(&self, page: &PdfPage) -> Result<Vec<u8>> {
115        let mut all_bytes = Vec::new();
116        for &content_id in &page.contents {
117            match self.file.resolve_stream_data(content_id) {
118                Ok(bytes) => {
119                    if !all_bytes.is_empty() {
120                        all_bytes.push(b'\n');
121                    }
122                    all_bytes.extend_from_slice(&bytes);
123                }
124                Err(e) => {
125                    tracing::warn!("failed to decode content stream {content_id}: {e}");
126                }
127            }
128        }
129        Ok(all_bytes)
130    }
131
132    /// Load all fonts referenced by a page.
133    pub fn load_page_fonts(&self, page: &PdfPage) -> FontCache {
134        font_loader::load_page_fonts(self.file(), page)
135    }
136
137    /// Parse a page's annotations into renderable form (/Rect, /F, the
138    /// /AS-selected appearance stream, /OC membership). Widget annotations for
139    /// interactive-form fields gain a generated appearance when the producer
140    /// left none (or set /NeedAppearances).
141    pub fn page_annotations(&self, page: &PdfPage) -> Vec<Annotation> {
142        annotation::parse_annotations(
143            &self.file,
144            page,
145            &self.catalog,
146            self.named_dests(),
147            self.acro_form(),
148        )
149    }
150
151    /// The document's named-destination map, flattened once and cached for the
152    /// document's lifetime. Backs link-target resolution so the name tree is
153    /// walked at most once, never per page.
154    fn named_dests(&self) -> &HashMap<Vec<u8>, PdfObject> {
155        self.named_dests
156            .get_or_init(|| destinations::collect_named_dests(&self.file))
157    }
158
159    /// The document's interactive form (`/AcroForm`), if any. Parsed once and
160    /// cached for the lifetime of the document.
161    pub fn acro_form(&self) -> Option<&AcroForm> {
162        self.acro_form
163            .get_or_init(|| AcroForm::parse(&self.file))
164            .as_ref()
165    }
166
167    /// The document's default optional-content configuration, if any.
168    pub fn oc_config(&self) -> Option<OcConfig> {
169        optional_content::parse_oc_config(&self.file)
170    }
171
172    /// The document-level output intents (catalog `/OutputIntents`). Empty when
173    /// the document declares none. Page-level intents (PDF 2.0) are carried on
174    /// the page and read via [`PdfDocument::page_output_intents`].
175    pub fn output_intents(&self) -> Vec<OutputIntent> {
176        output_intents::parse_output_intents(&self.file)
177    }
178
179    /// PDF 2.0 page-level `/OutputIntents`, which override the document-level
180    /// intents for that page. Empty for pre-2.0 / most documents.
181    pub fn page_output_intents<'a>(&self, page: &'a PdfPage) -> &'a [OutputIntent] {
182        &page.output_intents
183    }
184
185    /// The document's embedded files — file streams registered in the catalog's
186    /// `/Names /EmbeddedFiles` name tree (a viewer's "attachments"). Empty when
187    /// the document carries none. Pull a file's bytes with
188    /// [`PdfDocument::embedded_file_bytes`].
189    pub fn embedded_files(&self) -> Vec<EmbeddedFile> {
190        embedded_files::parse_embedded_files(&self.file)
191    }
192
193    /// Catalog-level associated files (`/Root /AF`, PDF 2.0). Each carries an
194    /// `/AFRelationship`. Per PDF 2.0 these are also listed by
195    /// [`PdfDocument::embedded_files`]; the two lists usually overlap.
196    pub fn associated_files(&self) -> Vec<EmbeddedFile> {
197        embedded_files::parse_associated_files(&self.file)
198    }
199
200    /// Page-level associated files (`/Page /AF`, PDF 2.0) for one page. `/AF` is
201    /// not inheritable, so only the leaf page dictionary is consulted.
202    pub fn page_associated_files(&self, page: &PdfPage) -> Vec<EmbeddedFile> {
203        match self
204            .file
205            .resolve(page.id)
206            .ok()
207            .and_then(|o| o.as_dict().ok().cloned())
208        {
209            Some(dict) => embedded_files::parse_page_associated_files(&self.file, &dict),
210            None => Vec::new(),
211        }
212    }
213
214    /// Decode and return the bytes of an embedded file. Routes through the
215    /// parser's filter pipeline, so it respects `ParseLimits` (max stream size).
216    /// Errors if the file specification carries no embedded stream
217    /// ([`EmbeddedFile::is_embedded`] is `false`).
218    pub fn embedded_file_bytes(&self, file: &EmbeddedFile) -> Result<Vec<u8>> {
219        match file.stream {
220            Some(id) => self.file.resolve_stream_data(id),
221            // An external file specification has nothing to extract; report the
222            // absent /EF as a missing key rather than a fake object-corruption
223            // error, so a caller can distinguish it from a decode failure.
224            None => Err(Error::MissingKey("EF".into())),
225        }
226    }
227
228    /// The document outline (bookmarks) from the catalog's `/Outlines`, as a
229    /// nested tree of [`OutlineItem`]. Each item's `/Dest` or go-to `/A` is
230    /// resolved to a [`Destination`]; URI / remote-go-to targets are captured as
231    /// strings. Empty when the document has no outline.
232    pub fn outline(&self) -> Vec<OutlineItem> {
233        outline::parse_outlines(&self.file, &self.catalog)
234    }
235
236    /// Resolve a *named* destination (from a named-destination string/name) to a
237    /// [`Destination`]. Tries the `/Names /Dests` name tree and the legacy
238    /// `/Root /Dests` dictionary. `None` when the name is unknown.
239    pub fn named_destination(&self, name: &[u8]) -> Option<Destination> {
240        destinations::resolve_named(&self.file, &self.catalog, name)
241    }
242
243    /// Resolve any destination *value* — an explicit `[page /Fit …]` array, a
244    /// named-destination name/string, a `<< /D … >>` dictionary, or an indirect
245    /// reference to one — to a [`Destination`]. This is what a `/Dest` entry or
246    /// a go-to action's `/D` carries; useful for resolving link-annotation
247    /// targets. `None` when it does not name a destination.
248    pub fn resolve_destination(&self, dest: &PdfObject) -> Option<Destination> {
249        destinations::resolve_explicit(&self.file, &self.catalog, dest)
250    }
251
252    /// The document information dictionary (`/Info`): title, author, subject,
253    /// keywords, creator/producer, and creation/modification dates (raw PDF date
254    /// strings). `None` when the document carries no `/Info` or it is empty.
255    pub fn info(&self) -> Option<DocInfo> {
256        doc_info::parse_info(&self.file)
257    }
258
259    /// The document's page labels (`/PageLabels`, ISO 32000-1 §12.4.2): the
260    /// number tree mapping page indices to the printed labels a viewer shows and
261    /// a user navigates by — e.g. lowercase-roman front matter (`i, ii, …`) then
262    /// decimal body (`1, 2, …`), or a prefixed appendix (`A-1, A-2, …`). These
263    /// are distinct from the physical 0-based page indices. `None` when the
264    /// document declares no page labels. Query a page with [`PageLabels::label`].
265    pub fn page_labels(&self) -> Option<PageLabels> {
266        page_labels::parse_page_labels(&self.file)
267    }
268
269    /// The document's XMP metadata (`/Metadata`, ISO 32000-1 §14.3.2): the common
270    /// Dublin Core / XMP / PDF-schema properties (title, authors, description,
271    /// keywords, producer, creator tool, dates), read with a bounded scrape (no
272    /// XML engine; entity-expansion-safe). `None` when the document carries no
273    /// `/Metadata` or none of the recognized properties. PDF 2.0 prefers this
274    /// over the `/Info` dictionary ([`PdfDocument::info`]).
275    pub fn xmp_metadata(&self) -> Option<XmpMetadata> {
276        xmp::parse_xmp(&self.file)
277    }
278
279    /// The raw bytes of the catalog's `/Metadata` XMP packet (decoded through the
280    /// filter pipeline, respecting `ParseLimits`), for callers that want to parse
281    /// the RDF/XML themselves. `None` when the document carries no `/Metadata`.
282    pub fn metadata_bytes(&self) -> Option<Vec<u8>> {
283        xmp::metadata_bytes(&self.file)
284    }
285
286    /// The document's logical structure tree (`/StructTreeRoot`, ISO 32000-1
287    /// §14.7–14.8): the Tagged-PDF tree of structure elements (headings,
288    /// paragraphs, lists, tables, figures …) with their roles, accessibility
289    /// text, and marked-content / object associations. `None` when the document
290    /// declares no structure tree. Read-only; runs only when called.
291    pub fn struct_tree(&self) -> Option<StructTree> {
292        structure::parse_struct_tree(&self.file, &self.catalog)
293    }
294
295    /// Whether the document declares Tagged-PDF conformance via the catalog's
296    /// `/MarkInfo` dictionary (`/Marked true`). Independent of whether a
297    /// [`PdfDocument::struct_tree`] is actually present.
298    pub fn is_tagged(&self) -> bool {
299        structure::is_tagged(&self.file)
300    }
301
302    /// The document's digital signatures (`/Sig` form fields, ISO 32000-1
303    /// §12.8). Each [`Signature`] carries the signature dictionary's metadata,
304    /// its `/ByteRange` coverage, a byte-range **integrity** verdict
305    /// ([`DigestStatus`]) obtained by recomputing the covered-bytes digest and
306    /// comparing it to the digest embedded in the CMS blob, and a
307    /// **cryptographic** verdict ([`CryptoStatus`]) from verifying the signer's
308    /// RSA/ECDSA signature over the signed attributes against the embedded
309    /// certificate's public key. This does *not* validate certificate trust,
310    /// revocation, or signing-time validity — see the [`signature`] module docs
311    /// and [`Signature::is_cryptographically_valid`]. Empty when the document
312    /// carries no signatures. Read-only; runs only when called.
313    pub fn signatures(&self) -> Vec<Signature> {
314        signature::parse_signatures(&self.file)
315    }
316}
317
318#[cfg(test)]
319pub(crate) mod test_util {
320    /// Build a synthetic PDF from numbered object bodies (index `i` becomes
321    /// object `i + 1`), with a correct xref table and a trailer whose /Root is
322    /// object 1. Offsets are computed, so bodies can be edited freely.
323    pub fn build_pdf(objects: &[&str]) -> Vec<u8> {
324        let mut buf = Vec::from(&b"%PDF-1.7\n"[..]);
325        let mut offsets = Vec::with_capacity(objects.len());
326        for (i, body) in objects.iter().enumerate() {
327            offsets.push(buf.len());
328            buf.extend_from_slice(format!("{} 0 obj\n{body}\nendobj\n", i + 1).as_bytes());
329        }
330        let xref_off = buf.len();
331        buf.extend_from_slice(
332            format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).as_bytes(),
333        );
334        for off in &offsets {
335            buf.extend_from_slice(format!("{off:010} 00000 n \n").as_bytes());
336        }
337        buf.extend_from_slice(
338            format!(
339                "trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref_off}\n%%EOF\n",
340                objects.len() + 1
341            )
342            .as_bytes(),
343        );
344        buf
345    }
346}