exprim 0.4.1

A concurrent, memory-bounded PDF reader and renderer: parse, extract text, and rasterize pages on an immutable document snapshot
Documentation
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
use std::collections::{HashMap, HashSet};
use std::sync::Arc;

use crate::document::{PageIndex, ParseContext};
use crate::object::{Dictionary, ObjectId, PdfObject};

use crate::reader::RenderSession;

const MAX_OUTLINE_DEPTH: usize = 64;
const MAX_OUTLINE_NODES: usize = 100_000;

/// One resolved source-outline node. Page indexes are zero-based source space.
#[derive(Debug, Clone, PartialEq)]
pub struct OwnedBookmarkNode {
    /// The bookmark's label.
    pub title: String,
    /// Zero-based index of the page the bookmark points to.
    pub source_page: usize,
    /// Destination Y in PDF user space, when the destination form carries it.
    pub top: Option<f32>,
    /// Nested bookmarks, in document order.
    pub children: Vec<OwnedBookmarkNode>,
}

/// Extract the source outline without rasterizing any page.
///
/// Malformed and unresolved nodes are omitted. Their resolvable children are
/// promoted so one bad parent does not discard an otherwise useful subtree.
///
/// # Examples
///
/// Print the bookmarks as an indented list:
///
/// ```no_run
/// use exprim::OwnedBookmarkNode;
///
/// fn print(nodes: &[OwnedBookmarkNode], depth: usize) {
///     for node in nodes {
///         println!("{}{} (page {})", "  ".repeat(depth), node.title, node.source_page + 1);
///         print(&node.children, depth + 1);
///     }
/// }
///
/// # let bytes: std::sync::Arc<[u8]> = std::fs::read("document.pdf")?.into();
/// let session = exprim::RenderSession::open(bytes, None)?;
/// print(&exprim::extract_outline(&session), 0);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn extract_outline(session: &RenderSession) -> Vec<OwnedBookmarkNode> {
    OutlineReader::new(session).read()
}

struct OutlineReader<'a> {
    session: &'a RenderSession,
    context: ParseContext,
    page_by_object: HashMap<ObjectId, usize>,
    named_destinations: HashMap<Vec<u8>, PdfObject>,
    visited_nodes: HashSet<ObjectId>,
    visited_name_tree_nodes: HashSet<ObjectId>,
    nodes_seen: usize,
}

impl<'a> OutlineReader<'a> {
    fn new(session: &'a RenderSession) -> Self {
        let page_by_object = (0..session.page_count())
            .filter_map(|index| {
                session
                    .snapshot
                    .page(PageIndex(index))
                    .ok()
                    .and_then(|page| page.object.map(|object| (object, index as usize)))
            })
            .collect();
        Self {
            session,
            context: ParseContext::new(),
            page_by_object,
            named_destinations: HashMap::new(),
            visited_nodes: HashSet::new(),
            visited_name_tree_nodes: HashSet::new(),
            nodes_seen: 0,
        }
    }

    fn read(mut self) -> Vec<OwnedBookmarkNode> {
        let Some(catalog) = self.catalog() else {
            return Vec::new();
        };
        self.collect_named_destinations(&catalog);

        let Some(catalog_dict) = catalog.as_dict() else {
            return Vec::new();
        };
        let Some(outlines) = catalog_dict.get(self.key(b"Outlines")).cloned() else {
            return Vec::new();
        };
        let Some(outline_root) = self.resolve_value(&outlines) else {
            return Vec::new();
        };
        let Some(root_dict) = outline_root.as_dict() else {
            return Vec::new();
        };
        let Some(first) = root_dict.get(self.key(b"First")).cloned() else {
            return Vec::new();
        };
        self.walk_siblings(first, 0)
    }

    fn catalog(&mut self) -> Option<Arc<PdfObject>> {
        let root = self.session.snapshot.structure().trailer.root;
        self.resolve_reference(root)
    }

    fn collect_named_destinations(&mut self, catalog_object: &PdfObject) {
        let Some(catalog) = catalog_object.as_dict() else {
            return;
        };

        // The legacy catalog /Dests dictionary is the fallback. Populate it
        // first so the PDF 1.2+ name tree wins on duplicate names.
        if let Some(legacy) = catalog.get(self.key(b"Dests")).cloned()
            && let Some(legacy) = self.resolve_value(&legacy)
            && let Some(dict) = legacy.as_dict()
        {
            let entries = dict
                .iter()
                .map(|(name, value)| {
                    (
                        self.session.snapshot.names().resolve(name).to_vec(),
                        value.clone(),
                    )
                })
                .collect::<Vec<_>>();
            self.named_destinations.extend(entries);
        }

        let Some(names_object) = catalog.get(self.key(b"Names")).cloned() else {
            return;
        };
        let Some(names_object) = self.resolve_value(&names_object) else {
            return;
        };
        let Some(names_dict) = names_object.as_dict() else {
            return;
        };
        let Some(dests_tree) = names_dict.get(self.key(b"Dests")).cloned() else {
            return;
        };
        self.collect_name_tree(dests_tree, 0);
    }

    fn collect_name_tree(&mut self, node: PdfObject, depth: usize) {
        if depth > MAX_OUTLINE_DEPTH {
            return;
        }
        if let Some(id) = node.as_reference()
            && !self.visited_name_tree_nodes.insert(id)
        {
            return;
        }
        let Some(node) = self.resolve_value(&node) else {
            return;
        };
        let Some(dict) = node.as_dict() else {
            return;
        };

        if let Some(PdfObject::Array(entries)) = dict.get(self.key(b"Names")) {
            for pair in entries.chunks_exact(2) {
                if let Some(name) = destination_name(&pair[0], self.session) {
                    self.named_destinations.insert(name, pair[1].clone());
                }
            }
        }

        if let Some(PdfObject::Array(kids)) = dict.get(self.key(b"Kids")) {
            for kid in kids.iter().cloned() {
                self.collect_name_tree(kid, depth + 1);
            }
        }
    }

    fn walk_siblings(&mut self, first: PdfObject, depth: usize) -> Vec<OwnedBookmarkNode> {
        if depth > MAX_OUTLINE_DEPTH {
            return Vec::new();
        }

        let mut output = Vec::new();
        let mut current = Some(first);
        while let Some(raw_node) = current.take() {
            if self.nodes_seen >= MAX_OUTLINE_NODES {
                break;
            }
            self.nodes_seen += 1;
            if let Some(id) = raw_node.as_reference()
                && !self.visited_nodes.insert(id)
            {
                break;
            }

            let Some(node) = self.resolve_value(&raw_node) else {
                break;
            };
            let Some(dict) = node.as_dict() else {
                break;
            };

            let title = dict
                .get(self.key(b"Title"))
                .cloned()
                .and_then(|value| self.resolve_value(&value))
                .and_then(|value| match &*value {
                    PdfObject::String(text) => Some(decode_pdf_text_string(text.as_bytes())),
                    _ => None,
                })
                .unwrap_or_default();
            let first_child = dict.get(self.key(b"First")).cloned();
            let next = dict.get(self.key(b"Next")).cloned();
            let destination = dict
                .get(self.key(b"Dest"))
                .cloned()
                .or_else(|| self.action_destination(dict));

            let children = first_child
                .map(|child| self.walk_siblings(child, depth + 1))
                .unwrap_or_default();
            if let Some((source_page, top)) = destination
                .as_ref()
                .and_then(|value| self.resolve_destination(value, &mut HashSet::new()))
            {
                output.push(OwnedBookmarkNode {
                    title,
                    source_page,
                    top,
                    children,
                });
            } else {
                output.extend(children);
            }

            current = next;
        }
        output
    }

    fn action_destination(&mut self, node: &Dictionary) -> Option<PdfObject> {
        let action = node.get(self.key(b"A"))?.clone();
        let action = self.resolve_value(&action)?;
        let action = action.as_dict()?;
        let kind = action.get(self.key(b"S"))?.as_name()?;
        if self.session.snapshot.names().resolve(kind).as_ref() != b"GoTo" {
            return None;
        }
        action.get(self.key(b"D")).cloned()
    }

    fn resolve_destination(
        &mut self,
        value: &PdfObject,
        named_seen: &mut HashSet<Vec<u8>>,
    ) -> Option<(usize, Option<f32>)> {
        let value = self.resolve_value(value)?;
        match &*value {
            PdfObject::Array(items) => self.resolve_destination_array(items),
            PdfObject::Dictionary(dict) => {
                let nested = dict.get(self.key(b"D"))?;
                self.resolve_destination(nested, named_seen)
            }
            PdfObject::Name(_) | PdfObject::String(_) => {
                let name = destination_name(&value, self.session)?;
                if !named_seen.insert(name.clone()) {
                    return None;
                }
                let destination = self.named_destinations.get(&name)?.clone();
                self.resolve_destination(&destination, named_seen)
            }
            _ => None,
        }
    }

    fn resolve_destination_array(&mut self, items: &[PdfObject]) -> Option<(usize, Option<f32>)> {
        let source_page = match items.first()? {
            PdfObject::Reference(id) => *self.page_by_object.get(id)?,
            PdfObject::Integer(index) => usize::try_from(*index)
                .ok()
                .filter(|index| *index < self.session.page_count() as usize)?,
            _ => return None,
        };

        let fit = items
            .get(1)
            .and_then(PdfObject::as_name)
            .map(|name| self.session.snapshot.names().resolve(name));
        // Where the destination's Y coordinate sits inside the array depends
        // on the fit mode: `[page /XYZ left top zoom]`, `[page /FitH top]`,
        // `[page /FitR left bottom right top]`. Other modes carry no Y at all.
        let top_index = match fit.as_deref() {
            Some(b"XYZ") => Some(3),
            Some(b"FitH" | b"FitBH") => Some(2),
            Some(b"FitR") => Some(5),
            _ => None,
        };
        let top = top_index
            .and_then(|index| items.get(index))
            .and_then(|value| self.resolve_value(value))
            .and_then(|value| value.as_number())
            .filter(|value| value.is_finite())
            .map(|value| value as f32);
        Some((source_page, top))
    }

    fn resolve_value(&mut self, value: &PdfObject) -> Option<Arc<PdfObject>> {
        match value {
            PdfObject::Reference(id) => self.resolve_reference(*id),
            other => Some(Arc::new(other.clone())),
        }
    }

    fn resolve_reference(&mut self, id: ObjectId) -> Option<Arc<PdfObject>> {
        self.session
            .snapshot
            .objects()
            .resolve(&self.session.snapshot, id, &mut self.context)
            .ok()
    }

    fn key(&self, name: &[u8]) -> crate::object::NameId {
        self.session.snapshot.names().intern(name)
    }
}

fn destination_name(value: &PdfObject, session: &RenderSession) -> Option<Vec<u8>> {
    match value {
        PdfObject::Name(name) => Some(session.snapshot.names().resolve(*name).to_vec()),
        PdfObject::String(text) => Some(text.as_bytes().to_vec()),
        _ => None,
    }
}

pub(crate) fn decode_pdf_text_string(bytes: &[u8]) -> String {
    if let Some(body) = bytes.strip_prefix(&[0xFE, 0xFF]) {
        return decode_utf16_body(body, u16::from_be_bytes);
    }
    if let Some(body) = bytes.strip_prefix(&[0xFF, 0xFE]) {
        return decode_utf16_body(body, u16::from_le_bytes);
    }
    if let Some(body) = bytes.strip_prefix(&[0xEF, 0xBB, 0xBF]) {
        return String::from_utf8_lossy(body).into_owned();
    }

    bytes
        .iter()
        .filter_map(|byte| pdf_doc_char(*byte))
        .collect()
}

/// Decode a BOM-stripped UTF-16 body of one endianness. Damaged text strings
/// degrade rather than fail: a trailing odd byte is dropped and an unpaired
/// surrogate becomes U+FFFD.
fn decode_utf16_body(body: &[u8], to_unit: fn([u8; 2]) -> u16) -> String {
    let units = body.chunks_exact(2).map(|pair| to_unit([pair[0], pair[1]]));
    char::decode_utf16(units)
        .map(|result| result.unwrap_or(char::REPLACEMENT_CHARACTER))
        .collect()
}

fn pdf_doc_char(byte: u8) -> Option<char> {
    let value = match byte {
        0x18 => 0x02D8,
        0x19 => 0x02C7,
        0x1A => 0x02C6,
        0x1B => 0x02D9,
        0x1C => 0x02DD,
        0x1D => 0x02DB,
        0x1E => 0x02DA,
        0x1F => 0x02DC,
        0x20..=0x7E => byte as u32,
        0x80 => 0x2022,
        0x81 => 0x2020,
        0x82 => 0x2021,
        0x83 => 0x2026,
        0x84 => 0x2014,
        0x85 => 0x2013,
        0x86 => 0x0192,
        0x87 => 0x2044,
        0x88 => 0x2039,
        0x89 => 0x203A,
        0x8A => 0x2212,
        0x8B => 0x2030,
        0x8C => 0x201E,
        0x8D => 0x201C,
        0x8E => 0x201D,
        0x8F => 0x2018,
        0x90 => 0x2019,
        0x91 => 0x201A,
        0x92 => 0x2122,
        0x93 => 0xFB01,
        0x94 => 0xFB02,
        0x95 => 0x0141,
        0x96 => 0x0152,
        0x97 => 0x0160,
        0x98 => 0x0178,
        0x99 => 0x017D,
        0x9A => 0x0131,
        0x9B => 0x0142,
        0x9C => 0x0153,
        0x9D => 0x0161,
        0x9E => 0x017E,
        0xA0 => 0x20AC,
        0xA1..=0xAC | 0xAE..=0xFF => byte as u32,
        _ => return None,
    };
    char::from_u32(value)
}

#[cfg(test)]
mod tests {
    use super::decode_pdf_text_string;

    #[test]
    fn decodes_utf16be_titles() {
        assert_eq!(
            decode_pdf_text_string(&[0xFE, 0xFF, 0x00, 0xDC, 0x00, 0x62, 0x00, 0x65, 0x00, 0x72]),
            "Über"
        );
    }

    #[test]
    fn decodes_pdf_doc_encoding_titles() {
        assert_eq!(
            decode_pdf_text_string(b"Price \xA0 5 \x95uvre"),
            "Price € 5 Łuvre"
        );
    }
}