1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
//! Font-resource collection helpers.
//!
//! Aggregates the fonts referenced from every `Page` node's `/Resources /Font`
//! dictionary into a single `BTreeMap` keyed by resource name. Uses the same recursion
//! limit and cycle protection as [`crate::pages`].
use crate::ref_chain::resolve_ref_chain;
use crate::{Error, Object, ObjectRef, Pdf, Result};
use std::collections::{BTreeMap, BTreeSet};
use std::io::{Read, Seek};
/// Default recursion limit when walking the page tree to collect fonts.
pub const DEFAULT_MAX_PAGE_TREE_DEPTH: usize = 100;
/// Collect every font referenced by any page's `/Resources /Font` dictionary.
///
/// Fonts may be referenced indirectly (`/F1 7 0 R`) or inlined as a dictionary or
/// stream; in every case the returned [`Object`] is normalized to either the resolved
/// font dictionary or, for streams, the stream's font dictionary. Names that appear in
/// multiple pages are deduplicated and the latest definition wins, matching qpdf's
/// `--show-fonts` semantics.
///
/// # Errors
///
/// - [`Error::Missing`] when `/Root` or `/Pages` is absent.
/// - [`Error::Unsupported`] when the document catalog is not a dictionary, or when the
/// page tree exceeds the depth limit.
/// - Any [`Error`] propagated from [`Pdf::resolve_borrowed`] while resolving the catalog
/// or page-tree nodes.
pub fn font_entries<R: Read + Seek>(pdf: &mut Pdf<R>) -> Result<BTreeMap<Vec<u8>, Object>> {
font_entries_with_max_depth(pdf, DEFAULT_MAX_PAGE_TREE_DEPTH)
}
/// Like [`font_entries`] but with a caller-supplied recursion limit.
///
/// # Errors
///
/// - [`Error::Missing`] when `/Root` or `/Pages` is absent.
/// - [`Error::Unsupported`] when the document catalog is not a dictionary, or when the
/// page tree exceeds `max_depth`.
/// - Any [`Error`] propagated from [`Pdf::resolve_borrowed`] while resolving the catalog
/// or page-tree nodes.
pub fn font_entries_with_max_depth<R: Read + Seek>(
pdf: &mut Pdf<R>,
max_depth: usize,
) -> Result<BTreeMap<Vec<u8>, Object>> {
let catalog_ref = pdf.root_ref().ok_or(Error::Missing("/Root"))?;
let catalog = pdf.resolve_borrowed(catalog_ref)?;
let Object::Dictionary(catalog) = catalog else {
return Err(Error::Unsupported(format!(
"document catalog {catalog_ref} is not a dictionary"
)));
};
let pages_ref = catalog.get_ref("Pages").ok_or(Error::Missing("/Pages"))?;
let mut seen = BTreeSet::new();
let mut fonts = BTreeMap::new();
walk_font_resources(pdf, pages_ref, &mut seen, &mut fonts, 0, max_depth)?;
Ok(fonts)
}
fn walk_font_resources<R: Read + Seek>(
pdf: &mut Pdf<R>,
node: ObjectRef,
seen: &mut BTreeSet<ObjectRef>,
fonts: &mut BTreeMap<Vec<u8>, Object>,
depth: usize,
max_depth: usize,
) -> Result<()> {
if depth >= max_depth {
return Err(Error::Unsupported(format!(
"page tree depth exceeds maximum of {max_depth} at {node}"
)));
}
if !seen.insert(node) {
return Ok(());
}
let node_obj = pdf.resolve_borrowed(node)?;
let Object::Dictionary(dict) = node_obj else {
return Ok(());
};
let node_type = dict
.get("Type")
.and_then(Object::as_name)
.map(ToOwned::to_owned)
.unwrap_or_default();
if node_type.as_slice() == b"Pages" {
let kid_refs: Vec<ObjectRef> = dict
.get("Kids")
.and_then(Object::as_array)
.map(|kids| kids.iter().filter_map(Object::as_ref_id).collect())
.unwrap_or_default();
for reference in kid_refs {
walk_font_resources(pdf, reference, seen, fonts, depth + 1, max_depth)?;
}
return Ok(());
}
if node_type.as_slice() == b"Page" {
let page_dict = dict.clone();
collect_page_fonts(pdf, &page_dict, fonts)?;
}
Ok(())
}
fn collect_page_fonts<R: Read + Seek>(
pdf: &mut Pdf<R>,
page: &crate::Dictionary,
fonts: &mut BTreeMap<Vec<u8>, Object>,
) -> Result<()> {
let resources = match page.get("Resources") {
Some(resources) => {
if let Some(resources) = resources.as_dict() {
Some(resources.clone())
} else if resources.as_ref_id().is_some() {
// /Resources may be reached through more than one indirect hop
// (ref -> ref -> dict); follow the chain to its terminal.
let (terminal, _) = resolve_ref_chain(pdf, resources)?;
terminal.into_dict()
} else {
None
}
}
_ => None,
};
let Some(resources) = resources else {
return Ok(());
};
let fonts_dict = match resources.get("Font") {
Some(fonts_dict) => {
if let Some(fonts_dict) = fonts_dict.as_dict() {
Some(fonts_dict.clone())
} else if fonts_dict.as_ref_id().is_some() {
// The /Font value may be reached through more than one indirect
// hop (ref -> ref -> dict); follow the chain to its terminal.
let (terminal, _) = resolve_ref_chain(pdf, fonts_dict)?;
terminal.into_dict()
} else {
None
}
}
_ => None,
};
let Some(fonts_dict) = fonts_dict else {
return Ok(());
};
for (font_name, value) in fonts_dict.iter() {
// A font value may be inlined as a dictionary, embedded as a stream, or
// (most commonly) stored indirectly — possibly through more than one
// indirect hop (ref -> ref -> dict), so follow the chain to its
// terminal. Then normalize to the font dictionary: dictionaries are kept
// as-is and streams contribute their dictionary. PDF streams are always
// indirect objects, so a stream-valued font is only ever seen through
// the reference arm; the direct Object::Stream arm below mirrors it for
// completeness. Anything that is not a font dictionary is skipped.
//
// The reference arm yields an owned terminal, so the Dictionary/Stream
// dictionary is moved out below rather than cloned again. Inline dict
// and stream values are cloned once from `fonts_dict` (it is borrowed
// here); the skip path borrows and never clones.
//
// Resolution errors propagate via `?`, matching how /Resources and
// /Font are resolved above; a missing or deleted reference is not an
// error (it resolves to `Object::Null`) and is skipped by the match
// below.
let resolved: Object = match value {
Object::Reference(_) => resolve_ref_chain(pdf, value)?.0,
Object::Dictionary(_) | Object::Stream(_) => value.clone(),
_ => continue,
};
match resolved {
Object::Dictionary(font_dict) => {
fonts.insert(font_name.to_vec(), Object::Dictionary(font_dict));
}
Object::Stream(stream) => {
fonts.insert(font_name.to_vec(), Object::Dictionary(stream.dict));
}
_ => {}
}
}
Ok(())
}