flpdf 0.10.0

A pure-Rust PDF toolkit modeled on qpdf — read, rewrite, linearize, and inspect PDFs.
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
//! Repair the page tree before optimization and return its effective page order.
//! The normal non-linearized writer does not call this path.
//!
//! qpdf correspondence: QPDF_pages.cc page-tree preparation responsibilities.
//!

use std::collections::{BTreeSet, HashSet};
use std::io::{Read, Seek};

use crate::object_handle::{ObjectHandle, ObjectHandleIdentity};
use crate::qpdf_obj_gen::QpdfObjGen;
use crate::ObjectRef;
use crate::{Error, Pdf, QpdfErrorCode, QpdfExc, Result};

/// The effective `/Pages` root and leaf order after qpdf-compatible repair.
///
/// Returned by [`prepare_for_optimization`]; see that function for what "repair" covers.
#[derive(Debug, Clone)]
pub struct PreparedPages {
    /// The effective `/Pages` root, after correcting a catalog whose `/Pages` points
    /// into the tree instead of at the true root.
    pub root: PageTreeRoot,
    /// Every `Page` leaf in document order, with qpdf's `getAllPagesInternal` repairs
    /// applied (see [`prepare_for_optimization`]).
    pub pages: Vec<ObjectHandle>,
}

/// Location of the repaired `/Pages` root.
///
/// qpdf's object handles preserve a direct `/Pages` dictionary embedded in the
/// catalog. `Direct` therefore records its catalog owner instead of minting an
/// object for the page-tree root.
#[derive(Debug, Clone)]
pub enum PageTreeRoot {
    Indirect(ObjectHandle),
    Direct {
        catalog: ObjectHandle,
    },
    /// The `/Pages` root is direct and its Catalog is also direct in the
    /// trailer. The Catalog itself has no `ObjectRef`; consumers recover the
    /// same canonical handle through `Pdf::root_handle()`.
    DirectCatalog,
}

/// Repair the `/Pages` tree and return its effective root and leaf order.
///
/// # Errors
///
/// Propagates any [`Error`] from resolving an object while walking the tree, and
/// follows qpdf's unbounded default page-tree walk and returns
/// [`Error::Unsupported`] only for other traversal failures.
pub fn prepare_for_optimization<R: Read + Seek>(pdf: &mut Pdf<R>) -> Result<Option<PreparedPages>> {
    prepare_for_optimization_canonical(pdf, None)
}

/// Like [`prepare_for_optimization`], but uses the caller's page-tree depth
/// bound for both qpdf-style repair and page enumeration.
pub(crate) fn prepare_for_optimization_with_max_depth<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    max_depth: usize,
) -> Result<Option<PreparedPages>> {
    prepare_for_optimization_canonical(pdf, Some(max_depth))
}

/// Canonical qpdf-style page-tree preparation.
///
/// The complete repair walk is intentionally expressed in terms of live
/// [`ObjectHandle`]s. This is the `QPDF::getAllPages` / `getAllPagesInternal`
/// boundary (`libqpdf/QPDF_pages.cc:39-150`): the catalog, `/Pages` root,
/// `/Kids` array, and every leaf all retain their canonical identity while
/// repair mutates them.
fn prepare_for_optimization_canonical<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    max_depth: Option<usize>,
) -> Result<Option<PreparedPages>> {
    if max_depth.is_none() {
        if let Some(cached) = pdf.cached_page_list() {
            pdf.mark_get_all_pages_called();
            return Ok(Some(cached));
        }
    } else {
        // The public qpdf path has one fixed traversal contract. A caller
        // using flpdf's explicit test/depth variant may perform a different
        // repair walk, so it must not leave the default page cache stale.
        pdf.invalidate_page_list_cache();
    }
    pdf.mark_get_all_pages_called();

    let root_candidate = pdf.trailer_key_handle(b"Root");
    if root_candidate.try_is_null()? {
        return Ok(None);
    }
    root_candidate.try_dereference()?;
    if !root_candidate.try_is_dictionary()? {
        return Ok(None);
    }
    let catalog = root_candidate;
    let mut pages = catalog.try_get_key(b"/Pages")?;

    // qpdf corrects a catalog that points into the tree by following
    // `/Parent` until the true root (`QPDF_pages.cc:50-67`). Track raw
    // `QpdfObjGen` identity for indirect slots and canonical handle identity
    // for direct dictionaries that share the same live allocation.
    let mut seen_parent: BTreeSet<QpdfObjGen> = BTreeSet::new();
    // The key hashes only the canonical slot pointer; its Rc is retained so
    // that an allocation cannot be dropped and reused while it is tracked.
    #[allow(
        clippy::mutable_key_type,
        reason = "identity key compares only Rc pointer identity and retains the slot deliberately"
    )]
    let mut seen_parent_direct: HashSet<ObjectHandleIdentity> = HashSet::new();
    let mut changed_pages = false;
    let mut warned = false;
    loop {
        let repeated = if let Some(object_gen) = pages
            .qpdf_obj_gen()
            .filter(|object_gen| object_gen.is_indirect())
        {
            !seen_parent.insert(object_gen)
        } else {
            !seen_parent_direct.insert(pages.identity_key())
        };
        if repeated {
            break;
        }
        // QPDF::getAllPages checks isDictionary before asking the current
        // node for /Parent. This keeps a missing or scalar /Pages value on
        // qpdf's warning-tolerant empty-page path rather than manufacturing
        // a hard page-tree error.
        if !pages.try_is_dictionary()? {
            break;
        }
        if !pages.try_has_key(b"/Parent")? {
            break;
        }
        let parent = pages.try_get_key(b"/Parent")?;
        if parent.try_is_null()? {
            break; // cov:ignore: qpdf-compatible try_has_key hides direct and indirect null values first
        }
        if !warned {
            catalog.warn_if_possible(
                "document page tree root (root -> /Pages) doesn't point to the root of the page tree; attempting to correct",
            )?; // cov:ignore: warning-sink failure is not injectable through the qpdf success oracle
            warned = true;
        }
        pages = parent;
        changed_pages = true;
    }
    if changed_pages {
        catalog.replace_key(b"/Pages", pages.clone())?;
    }

    // qpdf's getAllPages asks the final node for /Kids even when it is not a
    // dictionary. That access is observable as a type warning for a missing
    // or scalar /Pages entry and is followed by an empty page cache.
    let has_kids = pages.try_has_key(b"/Kids")?;
    if !pages.try_is_dictionary()? {
        return Ok(None);
    }

    let mut state = CanonicalRepairState {
        seen: BTreeSet::new(),
        visited: BTreeSet::new(),
        visited_direct: HashSet::new(),
        pages: Vec::new(),
    };
    if has_kids {
        repair_page_tree_handle(pdf, pages.clone(), &mut state, 0, false, max_depth)?;
    }

    let root = match pages
        .qpdf_obj_gen()
        .filter(|object_gen| object_gen.is_indirect())
    {
        Some(_) => PageTreeRoot::Indirect(pages.clone()),
        None if catalog.is_indirect() => PageTreeRoot::Direct {
            catalog: catalog.clone(),
        },
        None => PageTreeRoot::DirectCatalog,
    };
    let prepared = PreparedPages {
        root,
        pages: state.pages,
    };
    if max_depth.is_none() {
        pdf.cache_page_list(&prepared);
    }
    Ok(Some(prepared))
}

struct CanonicalRepairState {
    seen: BTreeSet<QpdfObjGen>,
    visited: BTreeSet<QpdfObjGen>,
    visited_direct: HashSet<ObjectHandleIdentity>,
    pages: Vec<ObjectHandle>,
}

/// One suspended `getAllPagesInternal` frame.
///
/// qpdf uses the native call stack for this walk. Keep the same parent-before-
/// child and child-array order while moving the Rust stack frames to the heap,
/// so deeply nested valid trees do not hit the debug thread-stack limit.
struct RepairFrame {
    node: ObjectHandle,
    kids: ObjectHandle,
    next_kid: usize,
    kid_count: usize,
    depth: usize,
    inherited_media_box: bool,
}

/// Canonical `QPDF::getAllPagesInternal` walk (`QPDF_pages.cc:77-138`).
///
/// The holder and every child remain live handles throughout this function.
/// In particular, a direct child is promoted through
/// `QPDF::makeIndirectObject`'s shared-allocation counterpart before the
/// containing `/Kids` array is updated; no raw-object replacement is used.
fn repair_page_tree_handle<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    node: ObjectHandle,
    state: &mut CanonicalRepairState,
    depth: usize,
    inherited_media_box: bool,
    max_depth: Option<usize>,
) -> Result<()> {
    let Some(frame) =
        repair_page_tree_frame(pdf, node, state, depth, inherited_media_box, max_depth)?
    else {
        return Ok(());
    };
    let mut frames = vec![frame];

    while let Some(frame) = frames.last_mut() {
        if frame.next_kid >= frame.kid_count {
            frames.pop();
            continue;
        }

        let index = frame.next_kid;
        frame.next_kid += 1;
        let parent = frame.node.clone();
        let kids = frame.kids.clone();
        let frame_depth = frame.depth;
        let media_box = frame.inherited_media_box;
        let Some(mut kid) = kids.try_array_item(index)? else {
            continue;
        };

        if kid.try_has_key(b"/Kids")? {
            if let Some(child) =
                repair_page_tree_frame(pdf, kid, state, frame_depth + 1, media_box, max_depth)?
            {
                frames.push(child);
            }
            continue;
        }

        // qpdf applies the default before either direct promotion or duplicate
        // cloning (`QPDF_pages.cc:104-130`). This order is observable because a
        // duplicate receives the already-repaired page dictionary.
        if !media_box && !is_rectangle_handle(&kid.try_get_key(b"/MediaBox")?)? {
            kid.warn_if_possible(
                format!("kid {index} (from 0) MediaBox is undefined; setting to letter / ANSI A")
                    .as_str(),
            )?; // cov:ignore: warning-sink failure is not injectable through the qpdf success oracle
            replace_handle_key(
                &kid,
                b"/MediaBox",
                ObjectHandle::array(vec![
                    ObjectHandle::integer(0),
                    ObjectHandle::integer(0),
                    ObjectHandle::integer(612),
                    ObjectHandle::integer(792),
                ]),
            )?; // cov:ignore: canonical page owners make this replacement infallible here
        }

        if kid.is_direct() {
            parent.warn_if_possible(
                format!("kid {index} (from 0) is direct; converting to indirect").as_str(),
            )?; // cov:ignore: warning-sink failure is not injectable through the qpdf success oracle
            kid = promote_page_handle(pdf, kid)?;
            // cov:ignore-start: make_indirect_from_object_handle always
            // returns a handle carrying the newly allocated QpdfObjGen.
            let promoted_object_gen = kid
                .qpdf_obj_gen()
                .filter(|object_gen| object_gen.is_indirect())
                .ok_or_else(|| {
                    Error::Internal("promoted page lost its indirect identity".to_owned())
                })?;
            // cov:ignore-end
            state.seen.insert(promoted_object_gen);
            kids.set_array_item(index, kid.clone())?;
        } else if let Some(object_gen) = kid
            .qpdf_obj_gen()
            .filter(|object_gen| object_gen.is_indirect())
        {
            if !state.seen.insert(object_gen) {
                parent.warn_if_possible(
                    format!(
                        "kid {index} (from 0) appears more than once in the pages tree; creating a new page object as a copy"
                    )
                    .as_str(),
                )?; // cov:ignore: LLVM maps this covered duplicate-repair warning terminator separately
                let copied = kid.shallow_copy()?;
                kid = promote_page_handle(pdf, copied)?;
                // cov:ignore-start: make_indirect_from_object_handle always
                // returns a handle carrying the newly allocated QpdfObjGen.
                let copied_object_gen = kid
                    .qpdf_obj_gen()
                    .filter(|object_gen| object_gen.is_indirect())
                    .ok_or_else(|| {
                        Error::Internal("copied page lost its indirect identity".to_owned())
                    })?;
                // cov:ignore-end
                state.seen.insert(copied_object_gen);
                kids.set_array_item(index, kid.clone())?;
            }
        }

        if !kid.try_is_dictionary_of_type(b"Page", b"")? {
            kid.warn_if_possible("/Type key should be /Page but is not; overriding")?;
            replace_handle_key(&kid, b"/Type", ObjectHandle::name(b"Page".to_vec()))?;
        }
        let page_object_gen = kid
            .qpdf_obj_gen()
            .filter(|object_gen| object_gen.is_indirect());
        // cov:ignore-start: every direct leaf is promoted above and every
        // remaining leaf is an indirect handle with its QpdfObjGen identity.
        page_object_gen.ok_or_else(|| {
            Error::Internal("page-tree leaf lost its indirect identity".to_owned())
        })?;
        // cov:ignore-end
        state.pages.push(kid.clone());
    }
    Ok(())
}

fn repair_page_tree_frame<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    node: ObjectHandle,
    state: &mut CanonicalRepairState,
    depth: usize,
    inherited_media_box: bool,
    max_depth: Option<usize>,
) -> Result<Option<RepairFrame>> {
    if max_depth.is_some_and(|max_depth| depth >= max_depth) {
        let location = node
            .qpdf_obj_gen()
            .filter(|object_gen| object_gen.is_indirect())
            .map_or_else(
                || "direct /Pages node".to_owned(),
                |object_gen| format!("{} {}", object_gen.get_obj(), object_gen.get_gen()),
            );
        return Err(Error::Unsupported(format!(
            "page tree depth exceeds maximum of {} at {location}",
            max_depth.expect("checked above")
        )));
    }
    if let Some(object_gen) = node
        .qpdf_obj_gen()
        .filter(|object_gen| object_gen.is_indirect())
    {
        if !state.visited.insert(object_gen) {
            return Err(page_tree_cycle_error(pdf));
        }
    } else if !state.visited_direct.insert(node.identity_key()) {
        return Err(page_tree_cycle_error(pdf)); // cov:ignore: parsed PDF /Pages nodes are indirect; retain this defensive direct-handle cycle guard for canonical ObjectHandle callers.
    }

    node.try_dereference()?;
    if !node.try_is_dictionary()? || !node.try_has_key(b"/Kids")? {
        return Ok(None); // cov:ignore: callers recurse only after observing a dictionary /Kids key
    }

    if !node.try_is_dictionary_of_type(b"Pages", b"")? {
        node.warn_if_possible("/Type key should be /Pages but is not; overriding")?;
        replace_handle_key(&node, b"/Type", ObjectHandle::name(b"Pages".to_vec()))?;
    }

    let media_box = if inherited_media_box {
        true
    } else {
        is_rectangle_handle(&node.try_get_key(b"/MediaBox")?)?
    };
    let kids = node.try_get_key(b"/Kids")?;
    let Some(kid_count) = kids.try_array_len()? else {
        // QPDFObjectHandle::getArrayNItems warns and treats a non-array as
        // empty (`QPDFObjectHandle.cc:758-768`).
        let type_name = kids.type_name()?;
        kids.warn_if_possible(
            format!(
                "operation for array attempted on object of type {}: treating as empty",
                type_name
            )
            .as_str(),
        )?; // cov:ignore: warning-sink failure is not injectable through the qpdf success oracle
        return Ok(None);
    };
    Ok(Some(RepairFrame {
        node,
        kids,
        next_kid: 0,
        kid_count,
        depth,
        inherited_media_box: media_box,
    }))
}

/// Construct qpdf's `QPDFExc(qpdf_e_pages, ...)` for a repeated page-tree
/// node. qpdf uses the document's current `m->last_object_description`, not
/// the repeated node's object number, so preserve that state independently
/// from the rendered `what()` string (`QPDF_pages.cc:81-87`).
pub(crate) fn page_tree_cycle_error<R: Read + Seek>(pdf: &Pdf<R>) -> Error {
    Error::QpdfExc(QpdfExc::new(
        QpdfErrorCode::Pages,
        pdf.input_source_description(),
        pdf.resolver.last_object_description(),
        0,
        b"Loop detected in /Pages structure (getAllPages)",
    ))
}

fn promote_page_handle<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    handle: ObjectHandle,
) -> Result<ObjectHandle> {
    let promoted = pdf.make_indirect_from_object_handle(handle)?;
    Ok(promoted)
}

pub(crate) fn page_ref_from_handle(handle: &ObjectHandle) -> Result<ObjectRef> {
    let object_gen = handle
        .qpdf_obj_gen()
        .filter(|object_gen| object_gen.is_indirect())
        .ok_or_else(|| Error::Unsupported("page handle has no indirect identity".to_owned()))?;
    object_gen.to_object_ref().ok_or_else(|| {
        Error::Unsupported(format!(
            "page object {} {} cannot be represented as a valid ObjectRef",
            object_gen.get_obj(),
            object_gen.get_gen()
        ))
    })
}

impl PreparedPages {
    pub(crate) fn page_refs(self) -> Result<Vec<ObjectRef>> {
        self.pages.iter().map(page_ref_from_handle).collect()
    }
}

fn replace_handle_key(holder: &ObjectHandle, key: &[u8], value: ObjectHandle) -> Result<()> {
    holder.replace_key(key, value)?;
    Ok(())
}

fn is_rectangle_handle(value: &ObjectHandle) -> Result<bool> {
    let Some(length) = value.try_array_len()? else {
        return Ok(false);
    };
    if length != 4 {
        return Ok(false);
    }
    for index in 0..length {
        let Some(item) = value.try_array_item(index)? else {
            return Ok(false);
        };
        if item.try_as_integer()?.is_none() {
            item.try_dereference()?;
            if item.as_real().is_none() {
                return Ok(false);
            }
        }
    }
    Ok(true)
}

#[cfg(test)]
mod tests {
    use super::prepare_for_optimization;
    use super::prepare_for_optimization_with_max_depth;
    use crate::object_handle::ObjectValue;
    use crate::{ObjectHandle, Pdf};
    use std::io::Cursor;

    #[test]
    fn direct_pages_root_depth_error_keeps_its_explicit_location() {
        let mut bytes = b"%PDF-1.4\n".to_vec();
        let object_offset = bytes.len();
        bytes.extend_from_slice(
            b"1 0 obj\n<< /Type /Catalog /Pages << /Type /Pages /Kids [] /Count 0 >> >>\nendobj\n",
        );
        let xref_offset = bytes.len();
        bytes.extend_from_slice(
            format!("xref\n0 2\n0000000000 65535 f \n{object_offset:010} 00000 n \n").as_bytes(),
        );
        bytes.extend_from_slice(
            format!("trailer\n<< /Size 2 /Root 1 0 R >>\nstartxref\n{xref_offset}\n%%EOF\n")
                .as_bytes(),
        );
        let mut pdf = Pdf::open(Cursor::new(bytes)).expect("direct-pages fixture should open");

        let error = prepare_for_optimization_with_max_depth(&mut pdf, 0)
            .expect_err("the explicit depth bound should stop at the direct root");

        assert!(error.to_string().contains("direct /Pages node"));
    }

    #[test]
    fn prepared_pages_keeps_a_raw_page_identity_live() {
        let mut pdf = Pdf::empty().expect("empty PDF should open");
        let catalog = pdf.root_handle().expect("empty PDF has a catalog");
        let pages = catalog
            .try_get_key(b"/Pages")
            .expect("catalog has a page-tree root");
        let raw_page = pdf.get_object_handle_by_raw_identity(3, 65_535);
        raw_page.set_resolved(ObjectValue::Dictionary(
            [
                (b"/Type".to_vec(), ObjectHandle::name(b"Page".to_vec())),
                (
                    b"/MediaBox".to_vec(),
                    ObjectHandle::array(vec![
                        ObjectHandle::integer(0),
                        ObjectHandle::integer(0),
                        ObjectHandle::integer(612),
                        ObjectHandle::integer(792),
                    ]),
                ),
            ]
            .into_iter()
            .collect(),
        ));
        pages
            .replace_key(b"/Kids", ObjectHandle::array(vec![raw_page.clone()]))
            .expect("replace page-tree kids");
        pages
            .replace_key(b"/Count", ObjectHandle::integer(1))
            .expect("replace page count");

        let prepared = prepare_for_optimization(&mut pdf)
            .expect("raw page identity must not fail during canonical repair")
            .expect("the empty document has a page tree");

        assert_eq!(prepared.pages.len(), 1);
        assert_eq!(prepared.pages[0].qpdf_obj_gen(), raw_page.qpdf_obj_gen());
        assert_eq!(prepared.pages[0].object_ref(), None);

        crate::optimization::inherited_attrs::push(&mut pdf, &prepared, true, false)
            .expect("raw page identity must survive inherited-attribute push");
        crate::optimization::Optimization::optimize(
            &mut pdf,
            &std::collections::BTreeMap::new(),
            true,
            |_, _| Ok(0),
        )
        .expect("raw page identity must survive qpdf optimization traversal");
    }
}