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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
//! The page tree and pages.
use crate::content::{Content, Operation};
use crate::document::Document;
use crate::error::{Error, Result};
use crate::object::{Dictionary, Object, ObjectId};
use std::collections::BTreeSet;
/// A rectangle in default user space, normalised so that `x0 <= x1` and
/// `y0 <= y1`.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Rect {
/// Left edge.
pub x0: f64,
/// Bottom edge.
pub y0: f64,
/// Right edge.
pub x1: f64,
/// Top edge.
pub y1: f64,
}
impl Rect {
/// US Letter, what readers assume when a page has no usable `/MediaBox`.
pub const LETTER: Self = Self { x0: 0.0, y0: 0.0, x1: 612.0, y1: 792.0 };
/// From two opposite corners, in any order.
#[must_use]
pub fn new(xa: f64, ya: f64, xb: f64, yb: f64) -> Self {
Self { x0: xa.min(xb), y0: ya.min(yb), x1: xa.max(xb), y1: ya.max(yb) }
}
/// Width.
#[must_use]
pub fn width(&self) -> f64 {
self.x1 - self.x0
}
/// Height.
#[must_use]
pub fn height(&self) -> f64 {
self.y1 - self.y0
}
/// The part of `self` inside `other`, if any.
#[must_use]
pub fn intersect(&self, other: &Self) -> Option<Self> {
let r = Self {
x0: self.x0.max(other.x0),
y0: self.y0.max(other.y0),
x1: self.x1.min(other.x1),
y1: self.y1.min(other.y1),
};
(r.x0 < r.x1 && r.y0 < r.y1).then_some(r)
}
}
/// Walk the page tree from the catalog, left to right.
pub(crate) fn collect_pages(doc: &Document) -> Result<Vec<ObjectId>> {
let limit = doc.limits.max_pages;
let mut pages = Vec::new();
let mut visited = BTreeSet::new();
let mut stack: Vec<ObjectId> = Vec::new();
if let Some(Object::Reference(root)) = doc.catalog()?.get(b"Pages") {
stack.push(*root);
}
// Depth-first with an explicit stack: page trees in the wild include
// degenerate ones thousands of levels deep, and hostile ones that loop.
while let Some(id) = stack.pop() {
if !visited.insert(id.0) {
continue;
}
let Ok(dict) = doc.get_dictionary(id) else { continue };
let kids = doc.lookup(dict, b"Kids")?;
match kids {
Object::Array(kids) if !dict.is_type(b"Page") => {
stack.extend(kids.iter().rev().filter_map(|k| k.as_reference().ok()));
}
_ => {
if pages.len() >= limit {
return Err(Error::Limit { what: "page count", limit: limit as u64 });
}
pages.push(id);
}
}
}
if pages.is_empty() {
// No usable tree. Any object that says it is a page is one, in
// object order: what other readers recover in this state.
for id in doc.object_ids() {
if doc.get_object(id).is_ok_and(|o| o.as_dict().is_ok_and(|d| d.is_type(b"Page"))) {
if pages.len() >= limit {
return Err(Error::Limit { what: "page count", limit: limit as u64 });
}
pages.push(id);
}
}
}
Ok(pages)
}
/// One page of a [`Document`].
#[derive(Debug, Clone, Copy)]
pub struct Page<'a> {
doc: &'a Document,
id: ObjectId,
dict: &'a Dictionary,
}
impl<'a> Page<'a> {
pub(crate) fn new(doc: &'a Document, id: ObjectId) -> Result<Self> {
Ok(Self { doc, id, dict: doc.get_dictionary(id)? })
}
/// The page object's id.
#[must_use]
pub const fn id(&self) -> ObjectId {
self.id
}
/// The page dictionary.
#[must_use]
pub const fn dict(&self) -> &'a Dictionary {
self.dict
}
/// The document this page belongs to.
#[must_use]
pub const fn document(&self) -> &'a Document {
self.doc
}
/// An attribute of the page, resolved, looked up through `/Parent` when
/// the page itself lacks it (`/Resources`, `/MediaBox`, `/CropBox` and
/// `/Rotate` are inheritable).
#[must_use]
pub fn attribute(&self, key: &[u8]) -> Option<&'a Object> {
let mut dict = self.dict;
for _ in 0..=self.doc.limits.max_page_tree_depth {
match self.doc.lookup(dict, key) {
Ok(Object::Null) | Err(_) => {}
Ok(o) => return Some(o),
}
dict = self.doc.lookup_dict(dict, b"Parent")?;
}
None
}
fn rect(&self, key: &[u8]) -> Option<Rect> {
let a = self.attribute(key)?.as_array().ok()?;
let mut v = [0.0f64; 4];
for (slot, o) in v.iter_mut().zip(a) {
*slot = self.doc.resolve(o).ok()?.as_f64().ok()?;
}
(a.len() >= 4 && v.iter().all(|x| x.is_finite())).then(|| Rect::new(v[0], v[1], v[2], v[3]))
}
/// The media box. A page with none, or an empty or unreadable one, gets
/// US Letter, as in other readers.
#[must_use]
pub fn media_box(&self) -> Rect {
self.rect(b"MediaBox")
.filter(|r| r.width() > 0.0 && r.height() > 0.0)
.unwrap_or(Rect::LETTER)
}
/// The crop box: the visible region, clipped to the media box. Defaults
/// to the media box.
#[must_use]
pub fn crop_box(&self) -> Rect {
let media = self.media_box();
self.rect(b"CropBox").and_then(|c| c.intersect(&media)).unwrap_or(media)
}
/// Clockwise rotation for display: 0, 90, 180 or 270.
#[must_use]
pub fn rotate(&self) -> u16 {
let r = self.attribute(b"Rotate").and_then(|o| o.as_i64().ok()).unwrap_or(0);
// rem_euclid(360) is 0..=359; a value that is not a multiple of 90
// rounds down.
u16::try_from(r.rem_euclid(360) / 90 * 90).unwrap_or(0)
}
/// Size of a user-space unit in 1/72 inch. Default 1.
#[must_use]
pub fn user_unit(&self) -> f64 {
self.dict
.get(b"UserUnit")
.and_then(|o| self.doc.resolve(o).ok())
.and_then(|o| o.as_f64().ok())
.filter(|u| u.is_finite() && *u > 0.0)
.unwrap_or(1.0)
}
/// The page's resource dictionary (inherited if need be).
#[must_use]
pub fn resources(&self) -> Option<&'a Dictionary> {
self.attribute(b"Resources").and_then(|o| o.as_dict().ok())
}
/// The page's content streams, decoded and joined, at most `max` bytes.
/// A page with no `/Contents` has empty content.
///
/// Damaged stream data is an error here. A caller that would rather draw
/// part of a page than none uses
/// [`content_lenient`](Self::content_lenient).
pub fn content(&self, max: usize) -> Result<Vec<u8>> {
let (data, complete) = self.content_lenient(max)?;
if complete {
Ok(data)
} else {
Err(Error::Filter {
filter: "page content".into(),
message: "encoded data is damaged or ends early".into(),
})
}
}
/// Like [`content`](Self::content), but damaged stream data yields what
/// could be decoded, with `false` for "not complete".
pub fn content_lenient(&self, max: usize) -> Result<(Vec<u8>, bool)> {
let contents = self.doc.lookup(self.dict, b"Contents")?;
let mut out = Vec::new();
let mut complete = true;
let mut append = |o: &Object| -> Result<()> {
let Object::Stream(s) = self.doc.resolve(o)? else {
return Ok(());
};
let (data, whole) = self.doc.decode_stream_lenient(s, max - out.len())?;
complete &= whole;
out.extend_from_slice(&data);
// The streams of a page are one stream split at token
// boundaries; a separator keeps the last token of one from
// fusing with the first of the next.
if out.len() < max {
out.push(b'\n');
}
Ok(())
};
match contents {
Object::Array(parts) => {
for part in parts {
append(part)?;
}
}
other => append(other)?,
}
Ok((out, complete))
}
/// The page's content as operations. The content is bounded by
/// [`Limits::max_stream_bytes`](crate::Limits::max_stream_bytes).
pub fn operations(&self) -> Result<Vec<Operation>> {
let data = self.content(self.doc.limits.max_stream_bytes)?;
Ok(Content::parse_with(&data, &self.doc.limits)?.operations)
}
/// The page's annotation dictionaries, whether `/Annots` lists them by
/// reference or holds them inline. An entry that is not a dictionary is
/// an error: skipping an annotation that cannot be read would be
/// skipping, for instance, a redaction.
pub fn annotations(&self) -> Result<Vec<&'a Dictionary>> {
match self.doc.lookup(self.dict, b"Annots")? {
Object::Null => Ok(Vec::new()),
Object::Array(items) => items
.iter()
.map(|item| {
self.doc
.resolve(item)?
.as_dict()
.map_err(|_| Error::Page("an annotation is not a dictionary".into()))
})
.collect(),
_ => Err(Error::Page("/Annots is not an array".into())),
}
}
}