Skip to main content

pdf/read/
mod.rs

1// pdf::read -- a PDF reader: the objects of a file, its pages, information, outlines, links and
2// other annotations, form fields, attachments, page labels, the text of each page with where
3// each glyph stands, and the pages drawn as pixels (render/).  PDF 1.0 to 2.0: classic cross-reference tables and cross-reference
4// streams, object streams, incremental updates, hybrid files; files whose table is missing or
5// wrong are rebuilt from their objects, as the common readers do.  Encrypted files with the
6// standard security handler open with their password, or without one when only the owner
7// password is set (RC4 40 to 128 bit, AES-128, AES-256).
8//
9//   let doc = read::Document::open(bytes)?;            // or open_with(bytes, &Options { password, .. })
10//   for i in 0..doc.page_count() {
11//       let text = doc.text(i)?;                       // the page's text in reading order
12//       let size = doc.page(i)?.size();                // points, after /Rotate
13//   }
14//   let info = doc.info();                             // pdf::Info: title, author, dates, ...
15//   for o in doc.outlines() { .. }                     // bookmarks with their Action
16//   let px = doc.render(0, &RenderOptions { dpi: 150.0, ..Default::default() })?;  // gfx::Surface
17//
18//   Document     open / open_with, version, is_encrypted / permissions / opened_as_owner,
19//                was_repaired, trailer / catalog, get(Ref) / resolve, decode(Stream) /
20//                decode_until_image, page_count / page / pages / contents, info / metadata /
21//                language, outlines, named_dest, annotations / links, fields, attachments,
22//                page_label, page_text (glyphs with positions) / text, page_pixels / render
23//                (RenderOptions: dpi, region, background, annotations, fonts: a FontSource,
24//                SystemFonts by default)
25//   Object       Null, Bool, Int, Real, String, Name, Array, Dict, Stream, Ref; text_string
26//   Ops          the operators of a content stream with their operands (content::Op)
27//
28// Untrusted input: a damaged or hostile file gives an Error or less than it claims, never a
29// panic, a hang or memory without end.  Nesting, the objects of one parse, the depth of
30// references, page trees, outlines and form XObjects are bounded; every decoded stream is at
31// most Options::max_stream bytes.  Permissions are reported, not enforced: what a program
32// allows its user to do with the document is its own decision.
33//
34// Composite fonts: every predefined CMap of ISO 32000-1 Table 118 (lib/cidmap: the code space,
35// code -> CID), and without a ToUnicode the text of Adobe's four CJK collections through their
36// CID -> Unicode tables (9.10.2); both unpacked once per document.
37//
38// Not here: the image filters for decode_until_image (it stops before DCT, JPX, JBIG2 and
39// CCITTFax; drawing decodes DCT, CCITTFax, JPX and JBIG2), verifying signatures.  pdf::edit
40// changes a document and saves it as an incremental update (forms filled in and flattened).
41
42mod cmap;
43mod content;
44pub(crate) mod crypt;
45mod filter;
46pub(crate) mod font;
47pub(crate) mod lex;
48mod nav;
49mod object;
50mod render;
51pub(crate) mod tables;
52mod text;
53pub(crate) mod xref;
54
55pub use content::{Op, Ops};
56pub use nav::{Action, Annotation, Attachment, Dest, Field, FieldKind, Outline, Signature, View};
57pub use object::{text_string, Dict, Name, Object, Ref, Stream};
58pub use render::{FontQuery, FontSource, RenderOptions, SystemFonts};
59pub use text::{PageText, TextItem};
60
61use crate::{Date, Info};
62use alloc::collections::{BTreeMap, BTreeSet};
63use alloc::rc::Rc;
64use alloc::string::String;
65use alloc::vec::Vec;
66use core::cell::{Cell, OnceCell, RefCell};
67use xref::Entry;
68
69/// how a document is opened
70#[derive(Clone, Debug)]
71pub struct Options {
72    /// the user or the owner password ("" for files without one)
73    pub password: String,
74    /// the largest decoded stream, in bytes (a content stream, an image, an attachment)
75    pub max_stream: usize,
76}
77
78impl Default for Options {
79    fn default() -> Options {
80        Options { password: String::new(), max_stream: 256 << 20 }
81    }
82}
83
84/// why a document or a part of it cannot be read
85#[derive(Clone, Copy, Debug, PartialEq, Eq)]
86#[non_exhaustive]
87pub enum Error {
88    /// not a PDF file: no header and no objects
89    NotPdf,
90    /// the file is damaged where it was needed
91    Damaged(&'static str),
92    /// encrypted, and the password is missing or wrong
93    Password,
94    /// something this reader does not do (a security handler other than the standard one, an
95    /// image filter)
96    Unsupported(&'static str),
97    /// a change pdf::edit cannot make: a field that is not there, a value it does not take
98    Invalid(&'static str),
99    /// more than the Options allow
100    Limit(&'static str),
101    /// a page number past the last page
102    NoPage,
103}
104
105impl core::fmt::Display for Error {
106    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
107        match self {
108            Error::NotPdf => f.write_str("not a PDF file"),
109            Error::Damaged(s) => write!(f, "damaged: {s}"),
110            Error::Password => f.write_str("the password is missing or wrong"),
111            Error::Unsupported(s) => write!(f, "not supported: {s}"),
112            Error::Invalid(s) => write!(f, "invalid: {s}"),
113            Error::Limit(s) => write!(f, "limit: {s}"),
114            Error::NoPage => f.write_str("no such page"),
115        }
116    }
117}
118
119impl core::error::Error for Error {}
120
121/// a page: its boxes (points, PDF page space with y up), rotation and dictionaries
122#[derive(Clone, Debug)]
123pub struct Page {
124    /// the page object
125    pub obj: Option<Ref>,
126    /// x0, y0, x1, y1
127    pub media_box: [f64; 4],
128    /// the visible part (the media box when the page sets none)
129    pub crop_box: [f64; 4],
130    /// clockwise when shown: 0, 90, 180 or 270
131    pub rotate: u16,
132    /// the size of a unit in points (PDF 1.6; usually 1)
133    pub user_unit: f64,
134    /// the page dictionary, and its resources (inherited ones included)
135    pub dict: Dict,
136    pub resources: Dict,
137}
138
139impl Page {
140    /// width and height of the crop box in points as the page is shown (after /Rotate)
141    pub fn size(&self) -> (f64, f64) {
142        let w = (self.crop_box[2] - self.crop_box[0]) * self.user_unit;
143        let h = (self.crop_box[3] - self.crop_box[1]) * self.user_unit;
144        if self.rotate % 180 == 90 { (h, w) } else { (w, h) }
145    }
146}
147
148struct ObjStm {
149    data: Vec<u8>,
150    first: usize,
151    /// (object number, offset after /First)
152    index: Vec<(u32, usize)>,
153    /// object number -> offset (its first place in the index), for entries whose index is wrong
154    by_num: BTreeMap<u32, usize>,
155}
156
157/// at most this many references in a row (a reference to a reference ...)
158const MAX_CHAIN: u32 = 32;
159/// object streams and /Length references inside each other
160const MAX_LOAD_DEPTH: u32 = 8;
161/// the most pages a document may have
162const MAX_PAGES: usize = 1 << 20;
163/// what the object streams of a document may decode together: this many max_stream, and this
164/// many bytes for each byte of the file (a large file whose streams are dropped from the cache
165/// and read again keeps working; a small one cannot unpack to hundreds of GB)
166const OBJSTM_DECODES: usize = 4;
167const OBJSTM_PER_BYTE: usize = 64;
168
169/// a PDF document opened for reading
170pub struct Document {
171    data: Vec<u8>,
172    xref: xref::Xref,
173    scan: OnceCell<BTreeMap<u32, (usize, u16)>>,
174    ends: OnceCell<lex::Ends>,
175    /// where the objects of a repaired file begin (an object is read up to the next one)
176    heads: OnceCell<xref::Heads>,
177    objstms: RefCell<BTreeMap<u32, Option<Rc<ObjStm>>>>,
178    /// the bytes of the object streams held (at most max_stream), and what decoding them may
179    /// still take for the whole document (a stream dropped from the cache is decoded again)
180    objstm_held: Cell<usize>,
181    objstm_left: Cell<usize>,
182    crypt: Option<crypt::Crypt>,
183    encrypt_ref: Option<Ref>,
184    pages: Vec<Page>,
185    page_index: BTreeMap<Ref, usize>,
186    version: (u8, u8),
187    max_stream: usize,
188    /// what drawing keeps across pages (fonts, the system's font list)
189    render: render::Cache,
190    /// the predefined CMaps of lib/cidmap and the CID -> Unicode tables, unpacked once
191    cidmaps: RefCell<BTreeMap<Vec<u8>, Option<Rc<cidmap::CMap>>>>,
192    cid_texts: RefCell<BTreeMap<cidmap::Collection, Rc<cidmap::ToUnicode>>>,
193}
194
195impl Document {
196    /// open a document without a password
197    pub fn open(data: Vec<u8>) -> Result<Document, Error> {
198        Document::open_with(data, &Options::default())
199    }
200
201    pub fn open_with(data: Vec<u8>, opt: &Options) -> Result<Document, Error> {
202        let head = lex::find(&data[..data.len().min(1024)], b"%PDF-", 0);
203        let version = head
204            .map(|h| {
205                let d = |i: usize| data.get(h + i).filter(|c| c.is_ascii_digit()).map(|c| c - b'0');
206                (d(5).unwrap_or(1), d(7).unwrap_or(4))
207            })
208            .unwrap_or((1, 4));
209        let x = xref::load(&data);
210        if x.entries.is_empty() && head.is_none() {
211            return Err(Error::NotPdf);
212        }
213        let data_len = data.len();
214        let mut doc = Document {
215            data,
216            xref: x,
217            scan: OnceCell::new(),
218            ends: OnceCell::new(),
219            heads: OnceCell::new(),
220            objstms: RefCell::new(BTreeMap::new()),
221            objstm_held: Cell::new(0),
222            objstm_left: Cell::new(opt.max_stream.saturating_mul(OBJSTM_DECODES).saturating_add(data_len.saturating_mul(OBJSTM_PER_BYTE))),
223            crypt: None,
224            encrypt_ref: None,
225            pages: Vec::new(),
226            page_index: BTreeMap::new(),
227            version,
228            max_stream: opt.max_stream,
229            render: render::Cache::default(),
230            cidmaps: RefCell::new(BTreeMap::new()),
231            cid_texts: RefCell::new(BTreeMap::new()),
232        };
233        doc.setup_crypt(&opt.password)?;
234        // a catalog that does not load: rebuild from the objects
235        if !doc.xref.repaired && doc.catalog().is_empty() {
236            let x = xref::scan(&doc.data);
237            doc.xref = x;
238            doc.objstms.borrow_mut().clear();
239            doc.objstm_held.set(0);
240            doc.setup_crypt(&opt.password)?;
241        }
242        if doc.xref.repaired {
243            doc.add_objstm_entries();
244            if doc.catalog().is_empty() {
245                // no trailer named it: the last catalog among the objects
246                let nums: Vec<u32> = doc.xref.entries.keys().copied().collect();
247                let found = nums.into_iter().rev().take(1 << 20).find(|&n| doc.get(Ref { num: n, generation: 0 }).as_dict().is_some_and(|d| d.is("Type", "Catalog")));
248                if let Some(n) = found {
249                    doc.xref.trailer.insert("Root", Object::Ref(Ref { num: n, generation: 0 }));
250                }
251            }
252        }
253        if let Some(v) = doc.catalog().name("Version") {
254            if v.len() >= 3 && v[0].is_ascii_digit() && v[2].is_ascii_digit() && (v[0] - b'0', v[2] - b'0') > doc.version {
255                doc.version = (v[0] - b'0', v[2] - b'0');
256            }
257        }
258        doc.collect_pages();
259        if doc.pages.is_empty() && doc.catalog().is_empty() {
260            return Err(Error::Damaged("no catalog and no pages"));
261        }
262        Ok(doc)
263    }
264
265    fn setup_crypt(&mut self, password: &str) -> Result<(), Error> {
266        self.crypt = None;
267        self.encrypt_ref = None;
268        let Some(e) = self.xref.trailer.get("Encrypt").cloned() else { return Ok(()) };
269        if e.is_null() {
270            return Ok(());
271        }
272        self.encrypt_ref = e.as_ref();
273        let enc = match self.resolve(&e) {
274            Object::Dict(d) => d,
275            _ => return Err(Error::Damaged("the encryption dictionary")),
276        };
277        let id0 = match self.xref.trailer.get("ID") {
278            Some(Object::Array(a)) => a.first().and_then(Object::as_bytes).map(<[u8]>::to_vec).unwrap_or_default(),
279            _ => Vec::new(),
280        };
281        self.crypt = Some(crypt::Crypt::open(&enc, &id0, password)?);
282        Ok(())
283    }
284
285    /// a scanned file: the objects of its object streams are known once they can be decoded
286    fn add_objstm_entries(&mut self) {
287        let list = core::mem::take(&mut self.xref.objstms);
288        for s in list {
289            let Some(st) = self.objstm(s, 0) else { continue };
290            for (i, &(num, _)) in st.index.iter().enumerate() {
291                self.xref.entries.entry(num).or_insert((Entry::InStream(s, i as u32), 0));
292            }
293        }
294    }
295
296    /// the version of the header, or of the catalog's /Version when that is newer
297    pub fn version(&self) -> (u8, u8) {
298        self.version
299    }
300
301    pub fn is_encrypted(&self) -> bool {
302        self.crypt.is_some()
303    }
304
305    /// the permission bits /P of an encrypted file (ISO 32000-1, Table 22: bit 3 print, 4
306    /// modify, 5 copy text and graphics, 6 annotate, 9 fill in forms, 10 extract for
307    /// accessibility, 11 assemble, 12 print in high quality; counted from 1)
308    pub fn permissions(&self) -> Option<u32> {
309        self.crypt.as_ref().map(|c| c.permissions)
310    }
311
312    /// the revision of the standard security handler (2 to 6) of an encrypted file
313    pub fn encryption_revision(&self) -> Option<u8> {
314        self.crypt.as_ref().map(|c| c.revision)
315    }
316
317    /// the password given was the owner password
318    pub fn opened_as_owner(&self) -> bool {
319        self.crypt.as_ref().is_some_and(|c| c.owner)
320    }
321
322    /// the cross-reference was rebuilt from the objects of the file
323    pub fn was_repaired(&self) -> bool {
324        self.xref.repaired
325    }
326
327    pub fn trailer(&self) -> &Dict {
328        &self.xref.trailer
329    }
330
331    /// the document catalog (empty when there is none)
332    pub fn catalog(&self) -> Dict {
333        match self.xref.trailer.get("Root") {
334            Some(r) => self.dict(r),
335            None => Dict::new(),
336        }
337    }
338
339    /// the raw bytes of the file
340    pub fn data(&self) -> &[u8] {
341        &self.data
342    }
343
344    /// the cross-reference: object number -> (where, generation)
345    pub(crate) fn xref_entries(&self) -> &BTreeMap<u32, (Entry, u16)> {
346        &self.xref.entries
347    }
348
349    /// where the newest cross-reference section begins and whether it is a stream (None: the
350    /// file was repaired)
351    pub(crate) fn xref_start(&self) -> Option<(usize, bool)> {
352        if self.xref.repaired { None } else { self.xref.start }
353    }
354
355    pub(crate) fn crypt(&self) -> Option<&crypt::Crypt> {
356        self.crypt.as_ref()
357    }
358
359    /// the encryption dictionary, when it is an indirect object
360    pub(crate) fn encrypt_ref(&self) -> Option<Ref> {
361        self.encrypt_ref
362    }
363
364    fn scan(&self) -> &BTreeMap<u32, (usize, u16)> {
365        self.scan.get_or_init(|| xref::scan_objects(&self.data))
366    }
367
368    /// an indirect object (Null when it is missing, as ISO 32000 has it)
369    pub fn get(&self, r: Ref) -> Object {
370        self.load(r, 0)
371    }
372
373    fn load(&self, r: Ref, depth: u32) -> Object {
374        if depth > MAX_LOAD_DEPTH {
375            return Object::Null;
376        }
377        match self.xref.entries.get(&r.num).copied() {
378            Some((Entry::At(off), _)) => {
379                if let Some(o) = self.at(off, r, depth) {
380                    return o;
381                }
382                if !self.xref.repaired {
383                    if let Some(&(o2, _)) = self.scan().get(&r.num) {
384                        if o2 != off {
385                            return self.at(o2, r, depth).unwrap_or_default();
386                        }
387                    }
388                }
389                Object::Null
390            }
391            Some((Entry::InStream(s, i), _)) => self.in_stream(s, i, r.num, depth).unwrap_or_default(),
392            _ if self.xref.repaired || self.xref.deleted(r.num) => Object::Null,
393            // an object a damaged table left out
394            _ => match self.scan().get(&r.num) {
395                Some(&(off, _)) => self.at(off, r, depth).unwrap_or_default(),
396                None => Object::Null,
397            },
398        }
399    }
400
401    fn at(&self, off: usize, r: Ref, depth: u32) -> Option<Object> {
402        let ends = |from: usize| self.ends.get_or_init(|| lex::Ends::of(&self.data)).after(from);
403        // a repaired file's objects end at the next header (its table was no guide; a string that
404        // runs on through the objects after it would be read for each of them)
405        let limit = match self.xref.repaired {
406            true => self.heads.get_or_init(|| xref::Heads::from_offsets(self.xref.entries.values().filter_map(|e| if let Entry::At(o) = e.0 { Some(o) } else { None }))).after(off, self.data.len()),
407            false => self.data.len(),
408        };
409        let (got, mut obj) = lex::indirect(&self.data, off, limit, &mut |lr| self.load(lr, depth + 1).as_int(), &ends)?;
410        if got.num != r.num {
411            return None;
412        }
413        if let Some(c) = &self.crypt {
414            if self.encrypt_ref != Some(r) {
415                c.strings_in(r, &mut obj, 0);
416            }
417        }
418        Some(obj)
419    }
420
421    fn objstm(&self, num: u32, depth: u32) -> Option<Rc<ObjStm>> {
422        if let Some(v) = self.objstms.borrow().get(&num) {
423            return v.clone();
424        }
425        let built = (|| {
426            let o = self.load(Ref { num, generation: 0 }, depth + 1);
427            let s = o.as_stream()?;
428            // what the object streams decode together is bounded (each one is at most
429            // max_stream; one dropped from the cache below is decoded again)
430            let left = self.objstm_left.get();
431            if left == 0 {
432                return None;
433            }
434            let decoded = self.decode_d(s, depth + 1);
435            // one that went past max_stream decoded that much (the filters fail early otherwise)
436            let used = match &decoded {
437                Ok(d) => d.0.len(),
438                Err(Error::Limit(_)) => self.max_stream,
439                Err(_) => 0,
440            };
441            self.objstm_left.set(left.saturating_sub(used));
442            let (data, img) = decoded.ok()?;
443            if img.is_some() {
444                return None;
445            }
446            let n = s.dict.int("N").unwrap_or(0).max(0) as usize;
447            let first = usize::try_from(s.dict.int("First")?).ok()?;
448            let mut lx = lex::Lexer::new(&data, 0);
449            let mut index = Vec::new();
450            let mut by_num = BTreeMap::new();
451            while index.len() < n && lx.pos < first.min(data.len()) {
452                let (lex::Tok::Int(a), lex::Tok::Int(b)) = (lx.next(), lx.next()) else { break };
453                let (Ok(a), Ok(b)) = (u32::try_from(a), usize::try_from(b)) else { break };
454                index.push((a, b));
455                by_num.entry(a).or_insert(b);
456            }
457            Some(Rc::new(ObjStm { data, first, index, by_num }))
458        })();
459        let mut cache = self.objstms.borrow_mut();
460        if let Some(st) = &built {
461            // the decoded streams held together stay within max_stream: older ones make room
462            let len = st.data.len();
463            while self.objstm_held.get() + len > self.max_stream {
464                let Some(k) = cache.iter().find(|e| e.1.is_some()).map(|e| *e.0) else { break };
465                let gone = cache.remove(&k).flatten().map_or(0, |s| s.data.len());
466                self.objstm_held.set(self.objstm_held.get().saturating_sub(gone));
467            }
468            self.objstm_held.set(self.objstm_held.get() + len);
469        }
470        if let Some(old) = cache.insert(num, built.clone()).flatten() {
471            // a stream inside itself, decoded while it was being decoded
472            self.objstm_held.set(self.objstm_held.get().saturating_sub(old.data.len()));
473        }
474        built
475    }
476
477    fn in_stream(&self, s: u32, i: u32, num: u32, depth: u32) -> Option<Object> {
478        let st = self.objstm(s, depth)?;
479        let off = match st.index.get(i as usize) {
480            Some(&(n, off)) if n == num => off,
481            _ => *st.by_num.get(&num)?,
482        };
483        let mut lx = lex::Lexer::new(&st.data, st.first.checked_add(off)?);
484        lx.object(true).ok()
485    }
486
487    /// follow references until an object that is none (Null after too many)
488    pub fn resolve(&self, o: &Object) -> Object {
489        let mut cur = match o {
490            Object::Ref(r) => self.get(*r),
491            o => return o.clone(),
492        };
493        for _ in 0..MAX_CHAIN {
494            match cur {
495                Object::Ref(r) => cur = self.get(r),
496                _ => return cur,
497            }
498        }
499        Object::Null
500    }
501
502    /// a dictionary (a stream's), resolved; empty when it is none
503    pub(crate) fn dict(&self, o: &Object) -> Dict {
504        match self.resolve(o) {
505            Object::Dict(d) => d,
506            Object::Stream(s) => s.dict,
507            _ => Dict::new(),
508        }
509    }
510
511    /// the value under `key`, resolved
512    pub(crate) fn key(&self, d: &Dict, key: &str) -> Object {
513        d.get(key).map(|o| self.resolve(o)).unwrap_or_default()
514    }
515
516    /// a stream's data with all its filters applied (an image filter is Error::Unsupported)
517    /// a predefined CMap of lib/cidmap by its name, unpacked once per document
518    pub(crate) fn cidmap(&self, name: &[u8]) -> Option<Rc<cidmap::CMap>> {
519        if let Some(c) = self.cidmaps.borrow().get(name) {
520            return c.clone();
521        }
522        let c = cidmap::predefined(name).map(Rc::new);
523        let mut m = self.cidmaps.borrow_mut();
524        if m.len() < 256 {
525            m.insert(name.to_vec(), c.clone());
526        }
527        c
528    }
529
530    /// a collection's CID -> Unicode table, unpacked once per document
531    pub(crate) fn cid_text(&self, c: cidmap::Collection) -> Rc<cidmap::ToUnicode> {
532        self.cid_texts.borrow_mut().entry(c).or_insert_with(|| Rc::new(cidmap::to_unicode(c))).clone()
533    }
534
535    pub fn decode(&self, s: &Stream) -> Result<Vec<u8>, Error> {
536        match self.decode_d(s, 0)? {
537            (d, None) => Ok(d),
538            (_, Some(_)) => Err(Error::Unsupported("an image filter (decode_until_image)")),
539        }
540    }
541
542    /// a stream's data with its filters applied up to an image filter: the data, and the image
543    /// filter with its parameters (DCTDecode is a JPEG file then, JPXDecode a JPEG 2000 one)
544    pub fn decode_until_image(&self, s: &Stream) -> Result<(Vec<u8>, Option<(Name, Dict)>), Error> {
545        self.decode_d(s, 0)
546    }
547
548    fn decode_d(&self, s: &Stream, depth: u32) -> Result<(Vec<u8>, Option<(Name, Dict)>), Error> {
549        let raw = self.data.get(s.start..s.end).ok_or(Error::Damaged("a stream outside the file"))?;
550        // the filters and their parameters may be references
551        let mut fd = Dict::new();
552        for k in ["Filter", "DecodeParms"] {
553            if let Some(o) = s.dict.get(k) {
554                let v = match self.resolve_d(o, depth) {
555                    Object::Array(a) => Object::Array(a.iter().map(|e| self.resolve_d(e, depth)).collect()),
556                    v => v,
557                };
558                fd.insert(k, v);
559            }
560        }
561        let chain = filter::chain(&fd);
562        let mut data = raw.to_vec();
563        if let (Some(c), Some(r)) = (&self.crypt, s.owner) {
564            let exempt = s.dict.is("Type", "XRef") || (!c.encrypt_metadata && s.dict.is("Type", "Metadata"));
565            if !exempt {
566                let cf = match chain.first() {
567                    Some((n, p)) if n == "Crypt" => Some(p.name("Name").unwrap_or(b"Identity")),
568                    _ => None,
569                };
570                data = c.stream(r, &data, cf, s.dict.is("Type", "EmbeddedFile"));
571            }
572        }
573        filter::apply(&chain, data, self.max_stream)
574    }
575
576    fn resolve_d(&self, o: &Object, depth: u32) -> Object {
577        match o {
578            Object::Ref(r) => match self.load(*r, depth + 1) {
579                Object::Ref(_) => Object::Null,
580                v => v,
581            },
582            o => o.clone(),
583        }
584    }
585
586    fn collect_pages(&mut self) {
587        #[derive(Clone, Default)]
588        struct Inh {
589            resources: Option<Object>,
590            media: Option<Object>,
591            crop: Option<Object>,
592            rotate: Option<i64>,
593        }
594        let cat = self.catalog();
595        let mut pages = Vec::new();
596        let mut seen = BTreeSet::new();
597        // the inherited values are shared by the kids: a node with a large direct /Resources
598        // and ten thousand /Kids made a copy for each kid
599        let mut stack: Vec<(Object, Rc<Inh>, u32)> = Vec::new();
600        if let Some(root) = cat.get("Pages") {
601            stack.push((root.clone(), Rc::new(Inh::default()), 0));
602        }
603        let budget = self.xref.entries.len().saturating_mul(2).max(64);
604        let mut nodes = 0usize;
605        while let Some((node, inh, depth)) = stack.pop() {
606            nodes += 1;
607            if nodes > budget || pages.len() >= MAX_PAGES || depth > 256 {
608                break;
609            }
610            let r = node.as_ref();
611            if let Some(r) = r {
612                if !seen.insert(r) {
613                    continue; // a loop in the tree, or a page listed twice
614                }
615            }
616            let d = self.dict(&node);
617            if d.is_empty() {
618                continue;
619            }
620            let rotate = d.get("Rotate").map(|o| self.resolve(o)).and_then(|o| o.as_int());
621            let mut inh = inh;
622            if d.contains("Resources") || d.contains("MediaBox") || d.contains("CropBox") || rotate.is_some() {
623                let mut own = (*inh).clone();
624                if let Some(v) = d.get("Resources") {
625                    own.resources = Some(v.clone());
626                }
627                if let Some(v) = d.get("MediaBox") {
628                    own.media = Some(v.clone());
629                }
630                if let Some(v) = d.get("CropBox") {
631                    own.crop = Some(v.clone());
632                }
633                if rotate.is_some() {
634                    own.rotate = rotate;
635                }
636                inh = Rc::new(own);
637            }
638            let kids = match self.key(&d, "Kids") {
639                Object::Array(a) => Some(a),
640                _ => None,
641            };
642            let is_page = d.is("Type", "Page") || (kids.is_none() && !d.is("Type", "Pages"));
643            if !is_page {
644                for k in kids.unwrap_or_default().into_iter().rev() {
645                    // a kid seen before costs nothing more than its place on the stack
646                    if k.as_ref().is_some_and(|r| seen.contains(&r)) {
647                        continue;
648                    }
649                    stack.push((k, inh.clone(), depth + 1));
650                }
651                continue;
652            }
653            pages.push((r, d, inh));
654        }
655        // a tree that leads nowhere: the page objects of the file, in order
656        if pages.is_empty() {
657            let nums: Vec<u32> = self.xref.entries.keys().copied().collect();
658            for num in nums.into_iter().take(1 << 20) {
659                let r = Ref { num, generation: self.xref.entries.get(&num).map(|e| e.1).unwrap_or(0) };
660                let d = self.dict(&Object::Ref(r));
661                if d.is("Type", "Page") {
662                    let inh = Inh { resources: d.get("Resources").cloned(), ..Inh::default() };
663                    pages.push((Some(r), d, Rc::new(inh)));
664                }
665            }
666        }
667        // resources that are references are read once for all the pages that share them (5000
668        // pages on one /Resources of 5000 XObjects held 5000 copies of it)
669        let mut shared: BTreeMap<Ref, Dict> = BTreeMap::new();
670        for (r, d, inh) in pages {
671            let rect = |o: &Option<Object>| o.as_ref().map(|o| self.resolve(o)).and_then(|o| o.as_rect());
672            let media = rect(&inh.media).filter(|b| b[2] > b[0] && b[3] > b[1]).unwrap_or([0.0, 0.0, 612.0, 792.0]);
673            let crop = rect(&inh.crop)
674                .map(|c| [c[0].max(media[0]), c[1].max(media[1]), c[2].min(media[2]), c[3].min(media[3])])
675                .filter(|c| c[2] > c[0] && c[3] > c[1])
676                .unwrap_or(media);
677            let rotate = (inh.rotate.unwrap_or(0).rem_euclid(360) / 90 * 90) as u16;
678            let user_unit = d.num("UserUnit").filter(|&u| u > 0.0 && u < 1e4).unwrap_or(1.0);
679            let resources = match &inh.resources {
680                Some(Object::Ref(rr)) => shared.entry(*rr).or_insert_with(|| self.dict(&Object::Ref(*rr))).clone(),
681                Some(o) => self.dict(o),
682                None => Dict::new(),
683            };
684            if let Some(r) = r {
685                self.page_index.insert(r, self.pages.len());
686            }
687            self.pages.push(Page { obj: r, media_box: media, crop_box: crop, rotate, user_unit, dict: d, resources });
688        }
689    }
690
691    pub fn page_count(&self) -> usize {
692        self.pages.len()
693    }
694
695    pub fn pages(&self) -> &[Page] {
696        &self.pages
697    }
698
699    pub fn page(&self, i: usize) -> Result<&Page, Error> {
700        self.pages.get(i).ok_or(Error::NoPage)
701    }
702
703    /// the page a page object is (for destinations)
704    pub fn page_of(&self, r: Ref) -> Option<usize> {
705        self.page_index.get(&r).copied()
706    }
707
708    /// the content of a page: its content streams decoded and joined (a stream that cannot be
709    /// decoded adds nothing)
710    pub fn contents(&self, i: usize) -> Result<Vec<u8>, Error> {
711        let p = self.page(i)?;
712        let mut out = Vec::new();
713        let parts = match self.key(&p.dict, "Contents") {
714            Object::Array(a) => a,
715            Object::Stream(s) => alloc::vec![Object::Stream(s)],
716            _ => Vec::new(),
717        };
718        for part in parts {
719            if let Object::Stream(s) = self.resolve(&part) {
720                if let Ok(d) = self.decode(&s) {
721                    if out.len() + d.len() > self.max_stream {
722                        return Err(Error::Limit("the page's content is larger than max_stream"));
723                    }
724                    out.extend_from_slice(&d);
725                    out.push(b'\n');
726                }
727            }
728        }
729        Ok(out)
730    }
731
732    /// the document information (the Info dictionary; dates as the file writes them)
733    pub fn info(&self) -> Info {
734        let d = match self.xref.trailer.get("Info") {
735            Some(o) => self.dict(o),
736            None => Dict::new(),
737        };
738        let s = |k: &str| match self.key(&d, k) {
739            Object::String(b) => Some(text_string(&b)),
740            _ => None,
741        };
742        Info {
743            title: s("Title"),
744            author: s("Author"),
745            subject: s("Subject"),
746            keywords: s("Keywords"),
747            creator: s("Creator"),
748            producer: s("Producer"),
749            created: s("CreationDate").and_then(|t| parse_date(&t)),
750            modified: s("ModDate").and_then(|t| parse_date(&t)),
751        }
752    }
753
754    /// the XMP metadata of the document (the catalog's /Metadata stream)
755    pub fn metadata(&self) -> Option<Vec<u8>> {
756        match self.key(&self.catalog(), "Metadata") {
757            Object::Stream(s) => self.decode(&s).ok(),
758            _ => None,
759        }
760    }
761
762    /// the natural language of the document (/Lang: "de-DE")
763    pub fn language(&self) -> Option<String> {
764        match self.key(&self.catalog(), "Lang") {
765            Object::String(b) => Some(text_string(&b)),
766            _ => None,
767        }
768    }
769}
770
771/// a date of a PDF file (7.9.4: "D:YYYYMMDDHHmmSSOHH'mm'"; every part after the year may be
772/// missing, as may "D:")
773pub fn parse_date(s: &str) -> Option<Date> {
774    let s = s.trim();
775    let s = s.strip_prefix("D:").unwrap_or(s).as_bytes();
776    let num = |i: usize, n: usize| -> Option<u32> {
777        let p = s.get(i..i + n)?;
778        p.iter().all(u8::is_ascii_digit).then(|| p.iter().fold(0u32, |a, &c| a * 10 + (c - b'0') as u32))
779    };
780    let year = num(0, 4)?;
781    let mut parts = [1u32, 1, 0, 0, 0];
782    let mut i = 4;
783    for p in parts.iter_mut() {
784        let Some(v) = num(i, 2) else { break };
785        *p = v;
786        i += 2;
787    }
788    let [month, day, hour, minute, second] = parts;
789    if !(1..=12).contains(&month) || !(1..=31).contains(&day) || hour > 23 || minute > 59 || second > 60 {
790        return None;
791    }
792    let mut offset = 0i32;
793    match s.get(i) {
794        Some(&c @ (b'+' | b'-')) => {
795            let h = num(i + 1, 2).unwrap_or(0) as i32;
796            let m = s.get(i + 3).filter(|&&c| c == b'\'').map_or_else(|| num(i + 3, 2), |_| num(i + 4, 2)).unwrap_or(0) as i32;
797            offset = (h * 60 + m).min(1439) * if c == b'-' { -1 } else { 1 };
798        }
799        _ => {}
800    }
801    Some(Date { year: year as u16, month: month as u8, day: day as u8, hour: hour as u8, minute: minute as u8, second: second.min(59) as u8, offset_minutes: offset as i16 })
802}