Skip to main content

pdf/read/
nav.rs

1// What a document holds besides its pages' content (ISO 32000-1, 12): the outline
2// (bookmarks), destinations (explicit and named, through the /Dests dictionary or the name
3// tree), actions, annotations with links, the fields of an interactive form with their values
4// and signatures (read, not verified), embedded files and page labels.  Trees and lists are
5// walked with a set of the objects seen and a budget, so a loop or a huge tree ends.
6
7use super::object::{text_string, Dict, Object, Ref, Stream};
8use super::{parse_date, Document, Error};
9use crate::Date;
10use alloc::collections::BTreeSet;
11use alloc::format;
12use alloc::rc::Rc;
13use alloc::string::String;
14use alloc::vec::Vec;
15
16/// how a destination shows its page (12.3.2.2); None keeps what the viewer has
17#[derive(Clone, Copy, Debug, PartialEq)]
18pub enum View {
19    Xyz { left: Option<f64>, top: Option<f64>, zoom: Option<f64> },
20    Fit,
21    FitH(Option<f64>),
22    FitV(Option<f64>),
23    /// left, bottom, right, top
24    FitR([f64; 4]),
25    FitB,
26    FitBH(Option<f64>),
27    FitBV(Option<f64>),
28}
29
30/// a place in the document: a page (counted from 0) and how it is shown
31#[derive(Clone, Copy, Debug, PartialEq)]
32pub struct Dest {
33    pub page: usize,
34    pub view: View,
35}
36
37/// what an outline item or a link does (12.6.4)
38#[derive(Clone, Debug, PartialEq)]
39pub enum Action {
40    GoTo(Dest),
41    /// a web address or other URI
42    Uri(String),
43    /// a page of another PDF file (GoToR): the file, the page when given as a number
44    GoToFile { file: String, page: Option<usize> },
45    /// start another file or program (Launch)
46    Launch(String),
47    /// a viewer command (Named: NextPage, PrevPage, FirstPage, LastPage, ...)
48    Named(String),
49    /// any other kind of action (JavaScript, SubmitForm, ...), by its /S
50    Other(String),
51}
52
53/// an item of the outline, with its children
54#[derive(Clone, Debug, PartialEq)]
55pub struct Outline {
56    pub title: String,
57    pub action: Option<Action>,
58    /// its children are shown
59    pub open: bool,
60    pub children: Vec<Outline>,
61}
62
63/// an annotation of a page
64#[derive(Clone, Debug, PartialEq)]
65pub struct Annotation {
66    /// /Subtype: Link, Text, Highlight, Widget, FileAttachment, ...
67    pub subtype: String,
68    /// x0, y0, x1, y1 in page space
69    pub rect: [f64; 4],
70    /// /Contents: the text of a note or comment
71    pub contents: Option<String>,
72    /// /T: the author of a markup annotation
73    pub author: Option<String>,
74    pub modified: Option<Date>,
75    /// a link's action (its /A, or its /Dest as GoTo)
76    pub action: Option<Action>,
77    pub obj: Option<Ref>,
78}
79
80/// a form field's kind (12.7.4)
81#[derive(Clone, Copy, Debug, PartialEq, Eq)]
82pub enum FieldKind {
83    Text,
84    CheckBox,
85    Radio,
86    PushButton,
87    ComboBox,
88    ListBox,
89    Signature,
90    /// a field without /FT
91    Unknown,
92}
93
94/// a field's signature as the file states it (12.8): the signature is not verified
95#[derive(Clone, Debug, PartialEq)]
96pub struct Signature {
97    /// /Filter and /SubFilter: Adobe.PPKLite, adbe.pkcs7.detached, ETSI.CAdES.detached, ...
98    pub filter: String,
99    pub sub_filter: String,
100    /// /Name, /Reason, /Location, /ContactInfo as given
101    pub name: Option<String>,
102    pub reason: Option<String>,
103    pub location: Option<String>,
104    pub time: Option<Date>,
105    /// the byte ranges of the file the signature covers: (start, length) pairs
106    pub byte_range: Vec<(u64, u64)>,
107    /// the signature (a PKCS #7 / CMS structure for the usual kinds)
108    pub contents: Vec<u8>,
109    /// the ranges cover the whole file but the signature itself (later changes make it false)
110    pub covers_file: bool,
111}
112
113/// a field of the interactive form
114#[derive(Clone, Debug, PartialEq)]
115pub struct Field {
116    /// the full name: the partial names of its parents and its own, with dots
117    pub name: String,
118    pub kind: FieldKind,
119    /// the value: text, the chosen option(s), a button's state ("Off" when not checked; the
120    /// export value of /Opt when the state is a place in it)
121    pub value: Vec<String>,
122    /// /Ff
123    pub flags: u32,
124    pub read_only: bool,
125    pub required: bool,
126    /// the options of a choice field, as shown
127    pub options: Vec<String>,
128    /// the widgets: the page (when known) and the rectangle
129    pub widgets: Vec<(Option<usize>, [f64; 4])>,
130    /// for a signature field with a value
131    pub signature: Option<Signature>,
132}
133
134/// a file embedded in the document (7.11.4)
135#[derive(Clone, Debug, PartialEq)]
136pub struct Attachment {
137    /// the file name (/UF, else /F)
138    pub name: String,
139    pub description: Option<String>,
140    /// /Subtype of the file stream: a MIME type ("text/xml")
141    pub mime: Option<String>,
142    pub size: Option<u64>,
143    pub modified: Option<Date>,
144    /// /AFRelationship (PDF/A-3, ZUGFeRD: Data, Source, Alternative, ...)
145    pub relationship: Option<String>,
146    /// the data: Document::decode(&stream)
147    pub stream: Option<Stream>,
148}
149
150/// trees and lists end after this many nodes
151const BUDGET: usize = 1 << 20;
152
153fn rect_of(o: &Object) -> [f64; 4] {
154    o.as_rect().unwrap_or([0.0; 4])
155}
156
157impl Document {
158    fn text_of(&self, d: &Dict, k: &str) -> Option<String> {
159        match self.key(d, k) {
160            Object::String(b) => Some(text_string(&b)),
161            Object::Name(n) => Some(n.to_text()),
162            _ => None,
163        }
164    }
165
166    /// an explicit destination [page /XYZ left top zoom] or a named one
167    pub(crate) fn dest(&self, o: &Object) -> Option<Dest> {
168        self.dest_d(o, 0)
169    }
170
171    fn dest_d(&self, o: &Object, depth: u32) -> Option<Dest> {
172        if depth > 4 {
173            return None;
174        }
175        match self.resolve(o) {
176            Object::Array(a) => {
177                let page = match a.first()? {
178                    Object::Ref(r) => self.page_of(*r)?,
179                    // some writers number the page in a local destination
180                    Object::Int(n) => usize::try_from(*n).ok().filter(|&n| n < self.page_count())?,
181                    _ => return None,
182                };
183                let n = |i: usize| a.get(i).and_then(Object::as_f64);
184                let view = match a.get(1).and_then(Object::as_name).unwrap_or(b"Fit") {
185                    b"XYZ" => View::Xyz { left: n(2), top: n(3), zoom: n(4).filter(|&z| z > 0.0) },
186                    b"FitH" => View::FitH(n(2)),
187                    b"FitV" => View::FitV(n(2)),
188                    b"FitR" => View::FitR([n(2).unwrap_or(0.0), n(3).unwrap_or(0.0), n(4).unwrap_or(0.0), n(5).unwrap_or(0.0)]),
189                    b"FitB" => View::FitB,
190                    b"FitBH" => View::FitBH(n(2)),
191                    b"FitBV" => View::FitBV(n(2)),
192                    _ => View::Fit,
193                };
194                Some(Dest { page, view })
195            }
196            Object::Dict(d) => self.dest_d(d.get("D")?, depth + 1),
197            Object::Name(n) => self.dest_d(&self.named_dest_obj(&n.0)?, depth + 1),
198            Object::String(s) => self.dest_d(&self.named_dest_obj(&s)?, depth + 1),
199            _ => None,
200        }
201    }
202
203    fn named_dest_obj(&self, name: &[u8]) -> Option<Object> {
204        let cat = self.catalog();
205        // PDF 1.1: a dictionary of names
206        if let Object::Dict(d) = self.key(&cat, "Dests") {
207            if let Some(v) = d.get_bytes(name) {
208                return Some(v.clone());
209            }
210        }
211        let names = self.dict(cat.get("Names")?);
212        self.name_tree_get(names.get("Dests")?, name)
213    }
214
215    /// a named destination ("chapter1")
216    pub fn named_dest(&self, name: &str) -> Option<Dest> {
217        self.dest(&self.named_dest_obj(name.as_bytes())?)
218    }
219
220    /// the value of `key` in a name tree (7.9.6), through /Limits
221    pub(crate) fn name_tree_get(&self, root: &Object, key: &[u8]) -> Option<Object> {
222        let mut seen = BTreeSet::new();
223        let mut node = root.clone();
224        for _ in 0..64 {
225            if let Some(r) = node.as_ref() {
226                if !seen.insert(r) {
227                    return None;
228                }
229            }
230            let d = self.dict(&node);
231            if let Object::Array(a) = self.key(&d, "Names") {
232                let mut i = 0;
233                while i + 1 < a.len() {
234                    if let Object::String(k) = self.resolve(&a[i]) {
235                        if k == key {
236                            return Some(a[i + 1].clone());
237                        }
238                    }
239                    i += 2;
240                }
241                return None;
242            }
243            let Object::Array(kids) = self.key(&d, "Kids") else { return None };
244            let mut next = None;
245            for k in &kids {
246                let kd = self.dict(k);
247                match self.key(&kd, "Limits") {
248                    Object::Array(l) if l.len() >= 2 => {
249                        let (lo, hi) = (self.resolve(&l[0]), self.resolve(&l[1]));
250                        if let (Some(lo), Some(hi)) = (lo.as_bytes(), hi.as_bytes()) {
251                            if lo <= key && key <= hi {
252                                next = Some(k.clone());
253                                break;
254                            }
255                        }
256                    }
257                    // a kid without limits: look inside
258                    _ => {
259                        if let Some(v) = self.name_tree_get_flat(k, key, &mut seen) {
260                            return Some(v);
261                        }
262                    }
263                }
264            }
265            node = next?;
266        }
267        None
268    }
269
270    fn name_tree_get_flat(&self, root: &Object, key: &[u8], seen: &mut BTreeSet<Ref>) -> Option<Object> {
271        let mut found = None;
272        self.walk_tree(root, "Names", seen, &mut |k, v| {
273            if found.is_none() && k.as_bytes() == Some(key) {
274                found = Some(v.clone());
275            }
276        });
277        found
278    }
279
280    /// every (key, value) of a name or number tree (`leaf` "Names" or "Nums"), in order
281    fn walk_tree(&self, root: &Object, leaf: &str, seen: &mut BTreeSet<Ref>, f: &mut dyn FnMut(&Object, &Object)) {
282        let mut stack = alloc::vec![root.clone()];
283        let mut n = 0;
284        while let Some(node) = stack.pop() {
285            n += 1;
286            if n > BUDGET {
287                return;
288            }
289            if let Some(r) = node.as_ref() {
290                if !seen.insert(r) {
291                    continue;
292                }
293            }
294            let d = self.dict(&node);
295            if let Object::Array(a) = self.key(&d, leaf) {
296                for pair in a.chunks(2) {
297                    if let [k, v] = pair {
298                        f(&self.resolve(k), v);
299                    }
300                }
301            }
302            if let Object::Array(kids) = self.key(&d, "Kids") {
303                stack.extend(kids.into_iter().rev());
304            }
305        }
306    }
307
308    pub(crate) fn action(&self, o: &Object) -> Option<Action> {
309        let d = self.dict(o);
310        let s = d.name("S")?.to_vec();
311        Some(match s.as_slice() {
312            b"GoTo" => Action::GoTo(self.dest(d.get("D")?)?),
313            b"URI" => {
314                let u = self.key(&d, "URI");
315                let b = u.as_bytes()?;
316                // a URI is 7-bit ASCII; some writers put UTF-8 there
317                Action::Uri(String::from_utf8_lossy(b).into_owned())
318            }
319            b"GoToR" | b"GoToE" => Action::GoToFile {
320                file: self.file_name(&self.key(&d, "F")).unwrap_or_default(),
321                page: match self.key(&d, "D") {
322                    Object::Array(a) => a.first().and_then(Object::as_int).and_then(|n| usize::try_from(n).ok()),
323                    _ => None,
324                },
325            },
326            b"Launch" => Action::Launch(self.file_name(&self.key(&d, "F")).unwrap_or_default()),
327            b"Named" => Action::Named(d.name("N").map(|n| String::from_utf8_lossy(n).into_owned()).unwrap_or_default()),
328            other => Action::Other(String::from_utf8_lossy(other).into_owned()),
329        })
330    }
331
332    /// a file specification (7.11): a string, or a dictionary with /UF or /F
333    fn file_name(&self, o: &Object) -> Option<String> {
334        match o {
335            Object::String(b) => Some(text_string(b)),
336            Object::Dict(d) => self.text_of(d, "UF").or_else(|| self.text_of(d, "F")).or_else(|| self.text_of(d, "Unix")).or_else(|| self.text_of(d, "DOS")),
337            _ => None,
338        }
339    }
340
341    /// the outline (bookmarks)
342    pub fn outlines(&self) -> Vec<Outline> {
343        let root = self.dict(&self.catalog().get("Outlines").cloned().unwrap_or_default());
344        let mut seen = BTreeSet::new();
345        let mut budget = BUDGET;
346        self.outline_level(root.get("First"), &mut seen, &mut budget, 0)
347    }
348
349    fn outline_level(&self, first: Option<&Object>, seen: &mut BTreeSet<Ref>, budget: &mut usize, depth: u32) -> Vec<Outline> {
350        let mut out = Vec::new();
351        let mut cur = first.cloned();
352        while let Some(o) = cur.take() {
353            if *budget == 0 || depth > 64 {
354                break;
355            }
356            *budget -= 1;
357            match o.as_ref() {
358                Some(r) if !seen.insert(r) => break,
359                None => break, // items are indirect objects
360                _ => {}
361            }
362            let d = self.dict(&o);
363            if d.is_empty() {
364                break;
365            }
366            let action = match d.get("Dest") {
367                Some(dest) => self.dest(dest).map(Action::GoTo),
368                None => d.get("A").and_then(|a| self.action(a)),
369            };
370            let children = self.outline_level(d.get("First"), seen, budget, depth + 1);
371            out.push(Outline {
372                title: self.text_of(&d, "Title").unwrap_or_default(),
373                action,
374                open: d.get("Count").map(|c| self.resolve(c)).and_then(|c| c.as_int()).is_some_and(|c| c > 0),
375                children,
376            });
377            cur = d.get("Next").cloned();
378        }
379        out
380    }
381
382    /// the annotations of a page
383    pub fn annotations(&self, page: usize) -> Result<Vec<Annotation>, Error> {
384        let p = self.page(page)?;
385        let Object::Array(list) = self.key(&p.dict, "Annots") else { return Ok(Vec::new()) };
386        let mut out = Vec::new();
387        for a in list.iter().take(BUDGET) {
388            let d = self.dict(a);
389            let Some(sub) = d.name("Subtype") else { continue };
390            let action = match d.get("A") {
391                Some(act) => self.action(act),
392                None => d.get("Dest").and_then(|x| self.dest(x)).map(Action::GoTo),
393            };
394            out.push(Annotation {
395                subtype: String::from_utf8_lossy(sub).into_owned(),
396                rect: rect_of(&self.key(&d, "Rect")),
397                contents: self.text_of(&d, "Contents"),
398                author: self.text_of(&d, "T"),
399                modified: self.text_of(&d, "M").and_then(|t| parse_date(&t)),
400                action,
401                obj: a.as_ref(),
402            });
403        }
404        Ok(out)
405    }
406
407    /// the links of a page: (rectangle, action)
408    pub fn links(&self, page: usize) -> Result<Vec<([f64; 4], Action)>, Error> {
409        Ok(self.annotations(page)?.into_iter().filter(|a| a.subtype == "Link").filter_map(|a| Some((a.rect, a.action?))).collect())
410    }
411
412    /// the fields of the interactive form (the AcroForm), terminal fields only
413    pub fn fields(&self) -> Vec<Field> {
414        let form = self.dict(&self.catalog().get("AcroForm").cloned().unwrap_or_default());
415        let Object::Array(roots) = self.key(&form, "Fields") else { return Vec::new() };
416        let mut out = Vec::new();
417        let mut seen = BTreeSet::new();
418        let mut annot_page: Option<alloc::collections::BTreeMap<Ref, usize>> = None;
419        // (field, parent's full name, inherited FT, Ff, V); what is inherited is shared by the
420        // kids (a /T of a megabyte with a million kids copied it for each before anything was
421        // checked), and the names and values all fields give stay within max_stream bytes
422        type Up = (Object, Rc<str>, Option<Rc<[u8]>>, Option<u32>, Option<Rc<Object>>, u32);
423        let mut stack: Vec<Up> = roots.into_iter().rev().map(|o| (o, Rc::from(""), None, None, None, 0)).collect();
424        let mut n = 0;
425        let mut text_left = self.max_stream;
426        while let Some((o, parent, ft, ff, v, depth)) = stack.pop() {
427            n += 1;
428            if n > BUDGET || depth > 64 {
429                break;
430            }
431            if let Some(r) = o.as_ref() {
432                if !seen.insert(r) {
433                    continue;
434                }
435            }
436            let d = self.dict(&o);
437            if d.is_empty() {
438                continue;
439            }
440            let name: Rc<str> = match self.text_of(&d, "T") {
441                Some(t) if parent.is_empty() => Rc::from(t),
442                Some(t) => Rc::from(format!("{parent}.{t}")),
443                None => parent.clone(),
444            };
445            if name.len() > text_left {
446                break;
447            }
448            let ft = d.name("FT").map(Rc::from).or(ft);
449            let ff = self.key(&d, "Ff").as_int().map(|f| f as u32).or(ff);
450            let v = d.get("V").map(|x| Rc::new(self.resolve(x))).or(v);
451            // kids that are fields (they have /T); kids without are this field's widgets
452            let kids = match self.key(&d, "Kids") {
453                Object::Array(a) => a,
454                _ => Vec::new(),
455            };
456            let field_kids: Vec<Object> = kids.iter().filter(|k| self.dict(k).contains("T")).cloned().collect();
457            if !field_kids.is_empty() {
458                for k in field_kids.into_iter().rev() {
459                    if k.as_ref().is_some_and(|r| seen.contains(&r)) {
460                        continue;
461                    }
462                    stack.push((k, name.clone(), ft.clone(), ff, v.clone(), depth + 1));
463                }
464                continue;
465            }
466            let flags = ff.unwrap_or(0);
467            let kind = match ft.as_deref() {
468                Some(b"Tx") => FieldKind::Text,
469                Some(b"Btn") if flags & (1 << 16) != 0 => FieldKind::PushButton,
470                Some(b"Btn") if flags & (1 << 15) != 0 => FieldKind::Radio,
471                Some(b"Btn") => FieldKind::CheckBox,
472                Some(b"Ch") if flags & (1 << 17) != 0 => FieldKind::ComboBox,
473                Some(b"Ch") => FieldKind::ListBox,
474                Some(b"Sig") => FieldKind::Signature,
475                _ => FieldKind::Unknown,
476            };
477            let mut value = Vec::new();
478            let mut signature = None;
479            match v.as_deref() {
480                Some(Object::String(b)) => value.push(text_string(b)),
481                Some(Object::Name(nm)) => value.push(nm.to_text()),
482                Some(Object::Array(a)) => {
483                    for x in a {
484                        if let Object::String(b) = self.resolve(x) {
485                            value.push(text_string(&b));
486                        }
487                    }
488                }
489                Some(Object::Dict(sd)) if kind == FieldKind::Signature => signature = Some(self.signature(sd)),
490                _ => {}
491            }
492            let options = match self.key(&d, "Opt") {
493                Object::Array(a) => a
494                    .iter()
495                    .filter_map(|x| match self.resolve(x) {
496                        Object::String(b) => Some(text_string(&b)),
497                        // [export shown]
498                        Object::Array(p) => p.get(1).or(p.first()).and_then(|e| self.resolve(e).as_bytes().map(text_string)),
499                        _ => None,
500                    })
501                    .collect(),
502                _ => Vec::new(),
503            };
504            // a button's state that is a place in /Opt stands for that export value (12.7.4.2.4)
505            if matches!(kind, FieldKind::CheckBox | FieldKind::Radio) && !options.is_empty() {
506                for v in value.iter_mut() {
507                    if let Some(o) = v.parse::<usize>().ok().and_then(|i| options.get(i)) {
508                        *v = o.clone();
509                    }
510                }
511            }
512            let mut widgets = Vec::new();
513            let wlist: Vec<Object> = if kids.is_empty() { alloc::vec![o.clone()] } else { kids };
514            for w in &wlist {
515                let wd = self.dict(w);
516                if !wd.contains("Rect") {
517                    continue;
518                }
519                let page = wd.get("P").and_then(Object::as_ref).and_then(|r| self.page_of(r)).or_else(|| {
520                    let map = annot_page.get_or_insert_with(|| self.annot_pages());
521                    map.get(&w.as_ref()?).copied()
522                });
523                widgets.push((page, rect_of(&self.key(&wd, "Rect"))));
524            }
525            let size = name.len() + value.iter().chain(&options).map(String::len).sum::<usize>();
526            if size > text_left {
527                break;
528            }
529            text_left -= size;
530            out.push(Field { name: String::from(&*name), kind, value, flags, read_only: flags & 1 != 0, required: flags & 2 != 0, options, widgets, signature });
531        }
532        out
533    }
534
535    /// the page of each annotation that /Annots lists (for widgets without /P)
536    fn annot_pages(&self) -> alloc::collections::BTreeMap<Ref, usize> {
537        let mut m = alloc::collections::BTreeMap::new();
538        for (i, p) in self.pages.iter().enumerate() {
539            if let Object::Array(a) = self.key(&p.dict, "Annots") {
540                for r in a.iter().filter_map(Object::as_ref) {
541                    m.entry(r).or_insert(i);
542                }
543            }
544        }
545        m
546    }
547
548    fn signature(&self, d: &Dict) -> Signature {
549        let name = |k: &str| d.name(k).map(|n| String::from_utf8_lossy(n).into_owned()).unwrap_or_default();
550        let br: Vec<i64> = match self.key(d, "ByteRange") {
551            Object::Array(a) => a.iter().filter_map(Object::as_int).collect(),
552            _ => Vec::new(),
553        };
554        let byte_range: Vec<(u64, u64)> = br.chunks_exact(2).filter_map(|p| Some((u64::try_from(p[0]).ok()?, u64::try_from(p[1]).ok()?))).collect();
555        let len = self.data.len() as u64;
556        let covers_file = byte_range.len() == 2 && byte_range[0].0 == 0 && byte_range[1].0.checked_add(byte_range[1].1) == Some(len) && byte_range[0].1 <= byte_range[1].0;
557        Signature {
558            filter: name("Filter"),
559            sub_filter: name("SubFilter"),
560            name: self.text_of(d, "Name"),
561            reason: self.text_of(d, "Reason"),
562            location: self.text_of(d, "Location"),
563            time: self.text_of(d, "M").and_then(|t| parse_date(&t)),
564            byte_range,
565            contents: self.key(d, "Contents").as_bytes().map(<[u8]>::to_vec).unwrap_or_default(),
566            covers_file,
567        }
568    }
569
570    /// the embedded files: the /EmbeddedFiles name tree, then file attachment annotations
571    pub fn attachments(&self) -> Vec<Attachment> {
572        let mut out = Vec::new();
573        let cat = self.catalog();
574        let names = self.dict(&cat.get("Names").cloned().unwrap_or_default());
575        let mut specs: Vec<Object> = Vec::new();
576        if let Some(root) = names.get("EmbeddedFiles") {
577            let mut seen = BTreeSet::new();
578            self.walk_tree(root, "Names", &mut seen, &mut |_, v| specs.push(v.clone()));
579        }
580        for i in 0..self.page_count() {
581            if let Ok(list) = self.annotations(i) {
582                for a in list.into_iter().filter(|a| a.subtype == "FileAttachment") {
583                    if let Some(r) = a.obj {
584                        if let Some(fs) = self.dict(&Object::Ref(r)).get("FS") {
585                            specs.push(fs.clone());
586                        }
587                    }
588                }
589            }
590        }
591        let mut seen = BTreeSet::new();
592        for s in specs {
593            if let Some(r) = s.as_ref() {
594                if !seen.insert(r) {
595                    continue;
596                }
597            }
598            let d = self.dict(&s);
599            let ef = self.dict(&d.get("EF").cloned().unwrap_or_default());
600            let stream = match ef.get("UF").or_else(|| ef.get("F")).map(|o| self.resolve(o)) {
601                Some(Object::Stream(st)) => Some(*st),
602                _ => None,
603            };
604            let params = stream.as_ref().map(|st| self.dict(&st.dict.get("Params").cloned().unwrap_or_default())).unwrap_or_default();
605            out.push(Attachment {
606                name: self.file_name(&Object::Dict(d.clone())).unwrap_or_default(),
607                description: self.text_of(&d, "Desc"),
608                mime: stream.as_ref().and_then(|st| st.dict.name("Subtype")).map(|n| String::from_utf8_lossy(n).into_owned()),
609                size: self.key(&params, "Size").as_int().and_then(|n| u64::try_from(n).ok()),
610                modified: self.text_of(&params, "ModDate").and_then(|t| parse_date(&t)),
611                relationship: d.name("AFRelationship").map(|n| String::from_utf8_lossy(n).into_owned()),
612                stream,
613            });
614        }
615        out
616    }
617
618    /// a page's label (12.4.2: "iv", "A-3"); None when the document sets no labels
619    pub fn page_label(&self, page: usize) -> Option<String> {
620        if page >= self.page_count() {
621            return None;
622        }
623        let root = self.catalog().get("PageLabels")?.clone();
624        let mut best: Option<(usize, Dict)> = None;
625        let mut seen = BTreeSet::new();
626        self.walk_tree(&root, "Nums", &mut seen, &mut |k, v| {
627            if let Some(start) = k.as_int().and_then(|n| usize::try_from(n).ok()) {
628                if start <= page && best.as_ref().is_none_or(|b| b.0 <= start) {
629                    best = Some((start, self.dict(v)));
630                }
631            }
632        });
633        let (start, d) = best?;
634        let n = ((page - start) as i64).saturating_add(d.int("St").unwrap_or(1).max(1));
635        let prefix = self.text_of(&d, "P").unwrap_or_default();
636        let num = match d.name("S") {
637            Some(b"D") => format!("{n}"),
638            Some(b"R") => roman(n).to_uppercase(),
639            Some(b"r") => roman(n),
640            Some(b"A") => letters(n).to_uppercase(),
641            Some(b"a") => letters(n),
642            _ => String::new(),
643        };
644        Some(prefix + &num)
645    }
646}
647
648fn roman(mut n: i64) -> String {
649    let mut s = String::new();
650    if !(1..=100_000).contains(&n) {
651        return format!("{n}");
652    }
653    for (v, t) in [(1000, "m"), (900, "cm"), (500, "d"), (400, "cd"), (100, "c"), (90, "xc"), (50, "l"), (40, "xl"), (10, "x"), (9, "ix"), (5, "v"), (4, "iv"), (1, "i")] {
654        while n >= v {
655            s.push_str(t);
656            n -= v;
657        }
658    }
659    s
660}
661
662/// a, b, ..., z, aa, bb, ... (12.4.2)
663fn letters(n: i64) -> String {
664    if !(1..=10_000).contains(&n) {
665        return format!("{n}");
666    }
667    let c = (b'a' + ((n - 1) % 26) as u8) as char;
668    core::iter::repeat_n(c, ((n - 1) / 26 + 1) as usize).collect()
669}