flpdf 0.9.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
//! Typed accessor helpers for annotation objects.
//!
//! qpdf correspondence: `QPDFAnnotationObjectHelper.cc`.
//!
//! [`AnnotationObjectHelper`] wraps one annotation [`ObjectHandle`] and
//! exposes typed, fail-soft read-only accessors for common annotation
//! attributes. Each accessor resolves through the handle at the qpdf
//! `QPDFObjectHandle` boundary.
//!
//! # Design
//!
//! - Annotation attributes (`/Subtype`, `/Rect`, `/AP`, `/AS`, `/F`) are
//!   **leaf-only** โ€” they are read directly from the annotation dictionary
//!   without walking any `/Parent` chain (per ISO 32000-1 ยง12.5, these keys
//!   are not inheritable).
//! - Accessors are **fail-soft**, matching qpdf: a missing key or a value of
//!   the wrong type yields a default (zero flags, a `(0, 0, 0, 0)` rectangle,
//!   a null handle) rather than an error. Only an I/O, parse, filter, or
//!   decryption failure while resolving an [`ObjectHandle`] surfaces as
//!   `Err`. [`AnnotationObjectHelper::get_subtype`] is the one exception:
//!   qpdf's own `getSubtype` skips the type check its siblings perform, so
//!   it defaults to qpdf's dummy-name sentinel rather than an empty name.
//! - `/Rect` reuses [`PageBox`] from [`crate::page_object_helper`].
//!
//! # Examples
//!
//! ## Inspect a highlight annotation
//!
//! ```no_run
//! use std::fs::File;
//! use std::io::BufReader;
//! use flpdf::{pages, Pdf, PageObjectHelper, AnnotationObjectHelper};
//!
//! let mut pdf = Pdf::open(BufReader::new(File::open("annotated.pdf")?))?;
//! let page_refs = pages::page_refs(&mut pdf)?;
//! if let Some(&page_ref) = page_refs.first() {
//!     let mut page_helper = PageObjectHelper::new(page_ref, &mut pdf);
//!     let annot_handles = page_helper.get_annotation_handles(None)?;
//!     drop(page_helper);
//!     for annot_handle in annot_handles {
//!         let mut annot = AnnotationObjectHelper::new(annot_handle);
//!         let subtype = annot.get_subtype()?;
//!         println!("annotation subtype: {}", String::from_utf8_lossy(&subtype));
//!         let rect = annot.get_rect()?;
//!         println!("rect: [{} {} {} {}]", rect.llx, rect.lly, rect.urx, rect.ury);
//!     }
//! }
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

use crate::object_handle::ObjectHandle;
use crate::page_object_helper::PageBox;
use crate::{Matrix, Rectangle, Result};

// ---------------------------------------------------------------------------
// AnnotationObjectHelper
// ---------------------------------------------------------------------------

/// Typed read-only accessor helper for a PDF annotation dictionary.
///
/// Construct with [`AnnotationObjectHelper::new`], passing a canonical
/// annotation [`ObjectHandle`] (for example one returned by
/// [`crate::PageObjectHelper::get_annotation_handles`]).
///
/// All accessors are **leaf-only**: they read only the annotation dictionary
/// itself, consistent with ISO 32000-1 ยง12.5 which specifies that annotation
/// attributes are not inheritable.
pub struct AnnotationObjectHelper {
    annot: ObjectHandle,
}

/// qpdf's `QPDFObjectHandle::getName` dummy-name sentinel
/// (`libqpdf/QPDFObjectHandle.cc:634-643`), returned in place of an error
/// when a name accessor runs on a non-name value. The crate's own name
/// accessors strip the leading `/` that qpdf's C++ literal `"/QPDFFakeName"`
/// carries.
const QPDF_FAKE_NAME: &[u8] = b"QPDFFakeName";

impl AnnotationObjectHelper {
    /// Construct a helper from the canonical annotation handle.
    ///
    /// Passing the handle directly preserves direct annotation dictionaries,
    /// which have no indirect object reference, and matches qpdf's
    /// `QPDFAnnotationObjectHelper(QPDFObjectHandle)` constructor.
    pub fn new(annot: ObjectHandle) -> Self {
        Self { annot }
    }

    /// Resolve `self.annot` and return the key's resolved child handle.
    fn resolved_key(&self, key: &[u8]) -> Result<ObjectHandle> {
        let child = self.annot.try_get_key(key)?;
        child.try_dereference()?;
        Ok(child)
    }

    // -----------------------------------------------------------------------
    // get_subtype โ€” /Subtype (Name, leaf-only)
    // -----------------------------------------------------------------------

    /// Return the annotation subtype (`/Subtype`) as raw name bytes.
    ///
    /// Common values include `b"Text"`, `b"Link"`, `b"Highlight"`,
    /// `b"Widget"`, etc. (ISO 32000-1 Table 169).
    ///
    /// Mirrors `QPDFAnnotationObjectHelper::getSubtype`
    /// (`libqpdf/QPDFAnnotationObjectHelper.cc:14-17`), which unconditionally
    /// calls `QPDFObjectHandle::getName` without checking the key's type
    /// first (unlike this crate's [`Self::get_appearance_state`] and
    /// [`Self::get_flags`]). When `/Subtype` is absent or not a name,
    /// `getName` returns qpdf's dummy-name sentinel `"QPDFFakeName"` (with
    /// its leading `/` stripped, matching this crate's other name
    /// accessors) rather than an empty `Vec`, and never an error for that
    /// reason.
    ///
    /// # Errors
    ///
    /// Propagates any error from resolving the annotation object.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use flpdf::{AnnotationObjectHelper, ObjectRef, Pdf};
    /// use std::fs::File;
    /// use std::io::BufReader;
    ///
    /// let mut pdf = Pdf::open(BufReader::new(File::open("a.pdf")?))?;
    /// let handle = pdf.get_object_handle(ObjectRef::new(5, 0));
    /// let mut annot = AnnotationObjectHelper::new(handle);
    /// let subtype = annot.get_subtype()?;
    /// println!("subtype: {}", String::from_utf8_lossy(&subtype));
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn get_subtype(&mut self) -> Result<Vec<u8>> {
        Ok(self
            .resolved_key(b"/Subtype")?
            .as_name()
            .unwrap_or_else(|| QPDF_FAKE_NAME.to_vec()))
    }

    // -----------------------------------------------------------------------
    // get_rect โ€” /Rect (4-element numeric array, leaf-only)
    // -----------------------------------------------------------------------

    /// Return the annotation rectangle (`/Rect`) as a [`PageBox`].
    ///
    /// The four numbers are `[llx, lly, urx, ury]` in default user-space
    /// units (ISO 32000-1 ยง12.5.4). Both integer and real elements are
    /// accepted and coerced to `f64`.
    ///
    /// Mirrors `QPDFObjectHandle::getArrayAsRectangle`
    /// (`libqpdf/QPDFObjectHandle.cc:817-836`), used by
    /// `QPDFAnnotationObjectHelper::getRect`: a missing `/Rect`, a
    /// non-array value, an array with a length other than 4, or a
    /// non-numeric element all yield `PageBox::new(0.0, 0.0, 0.0, 0.0)`
    /// rather than an error. The four corners are normalized to
    /// `llx <= urx` and `lly <= ury` via `min`/`max`, so a rectangle array
    /// stored with corners in reverse order is still returned upright.
    ///
    /// # Errors
    ///
    /// Propagates any error from resolving the annotation object or an
    /// indirect `/Rect` array element.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use flpdf::{AnnotationObjectHelper, ObjectRef, Pdf};
    /// use std::fs::File;
    /// use std::io::BufReader;
    ///
    /// let mut pdf = Pdf::open(BufReader::new(File::open("a.pdf")?))?;
    /// let handle = pdf.get_object_handle(ObjectRef::new(5, 0));
    /// let mut annot = AnnotationObjectHelper::new(handle);
    /// let r = annot.get_rect()?;
    /// println!("[{} {} {} {}]", r.llx, r.lly, r.urx, r.ury);
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn get_rect(&mut self) -> Result<PageBox> {
        let rect = self.resolved_key(b"/Rect")?;
        array_as_rectangle(&rect)
    }

    // -----------------------------------------------------------------------
    // get_appearance_dictionary โ€” /AP (leaf-only)
    // -----------------------------------------------------------------------

    /// Return the resolved `/AP` value.
    ///
    /// Mirrors `QPDFAnnotationObjectHelper::getAppearanceDictionary`
    /// (`libqpdf/QPDFAnnotationObjectHelper.cc:24-27`): returns whatever
    /// `/AP` resolves to verbatim, without checking that it is actually a
    /// dictionary. Callers that need the dictionary should check the
    /// returned handle's type; a null handle means `/AP` was absent.
    ///
    /// # Errors
    ///
    /// Propagates any error from resolving the annotation object or `/AP`.
    pub fn get_appearance_dictionary(&mut self) -> Result<ObjectHandle> {
        self.resolved_key(b"/AP")
    }

    // -----------------------------------------------------------------------
    // get_appearance_state โ€” /AS (Name, leaf-only)
    // -----------------------------------------------------------------------

    /// Return the appearance state (`/AS`) as raw name bytes, or an empty
    /// `Vec` if `/AS` is absent or not a name.
    ///
    /// Mirrors `QPDFAnnotationObjectHelper::getAppearanceState`
    /// (`libqpdf/QPDFAnnotationObjectHelper.cc:30-38`).
    ///
    /// # Errors
    ///
    /// Propagates any error from resolving the annotation object or `/AS`.
    pub fn get_appearance_state(&mut self) -> Result<Vec<u8>> {
        Ok(self.resolved_key(b"/AS")?.as_name().unwrap_or_default())
    }

    // -----------------------------------------------------------------------
    // get_flags โ€” /F (Integer, leaf-only)
    // -----------------------------------------------------------------------

    /// Return the annotation flags (`/F`), a logical OR of
    /// `pdf_annotation_flag_e` bits (ISO 32000-1 Table 165), or `0` if `/F`
    /// is absent or not an integer.
    ///
    /// Mirrors `QPDFAnnotationObjectHelper::getFlags`
    /// (`libqpdf/QPDFAnnotationObjectHelper.cc:41-45`).
    ///
    /// # Errors
    ///
    /// Propagates any error from resolving the annotation object or `/F`.
    pub fn get_flags(&mut self) -> Result<i64> {
        Ok(self.resolved_key(b"/F")?.as_integer().unwrap_or(0))
    }

    // -----------------------------------------------------------------------
    // get_appearance_stream โ€” /AP/<which>[/<state>]
    // -----------------------------------------------------------------------

    /// Select an appearance stream from `/AP`.
    ///
    /// `which` selects the entry within `/AP` โ€” typically `b"N"` (normal),
    /// `b"R"` (rollover), or `b"D"` (down), as a decoded PDF name (no
    /// leading `/`, matching [`Self::get_subtype`]/
    /// [`Self::get_appearance_state`]'s own convention โ€” [`ObjectHandle::
    /// get_key`] requires the `/`, so both `which` and `state` get it
    /// prepended internally). If `/AP/<which>` is itself a stream, it is
    /// returned directly. If it is a subdictionary (a state dictionary),
    /// `state` selects a key within it when non-empty, falling back to
    /// [`Self::get_appearance_state`]'s `/AS` value when `state` is `None`
    /// or empty. Returns a null [`ObjectHandle`] when no stream can be
    /// selected.
    ///
    /// Mirrors `QPDFAnnotationObjectHelper::getAppearanceStream`
    /// (`libqpdf/QPDFAnnotationObjectHelper.cc:48-71`), including the behavior
    /// that when `/AP/<which>` is already a stream, the state is disregarded
    /// even if one was requested.
    ///
    /// # Errors
    ///
    /// Propagates any error from resolving the annotation object, `/AP`,
    /// `/AS`, or the selected appearance entries.
    pub fn get_appearance_stream(
        &mut self,
        which: &[u8],
        state: Option<&[u8]>,
    ) -> Result<ObjectHandle> {
        let ap = self.get_appearance_dictionary()?;
        if ap.try_is_dictionary()? {
            let ap_sub = ap.try_get_key(&dict_key(which))?;
            ap_sub.try_dereference()?;
            if ap_sub.as_stream_dict().is_some() {
                // A direct appearance stream disregards state entirely
                // (`QPDFAnnotationObjectHelper.cc:59-63`).
                // `/AS` must not even be resolved on this path โ€” qpdf's own
                // eager `getAppearanceState()` call is infallible in C++,
                // but this crate's `/AS` resolution can genuinely error (a
                // malformed or cyclic indirect reference), and that error
                // must not surface for a state qpdf never consults here.
                return Ok(ap_sub);
            }
            if ap_sub.try_is_dictionary()? {
                let desired_state: Vec<u8> = match state {
                    Some(s) if !s.is_empty() => s.to_vec(),
                    _ => self.get_appearance_state()?,
                };
                if !desired_state.is_empty() {
                    let ap_sub_val = ap_sub.try_get_key(&dict_key(&desired_state))?;
                    ap_sub_val.try_dereference()?;
                    if ap_sub_val.as_stream_dict().is_some() {
                        return Ok(ap_sub_val);
                    }
                }
            } // cov:ignore: llvm-cov brace-region artifact, not untested โ€” reached by both annotation_handle_appearance_stream_missing_state_returns_null and _state_dictionary_key_missing_returns_null, same as the pre-existing single-block version of this brace
        } // cov:ignore: llvm-cov brace-region artifact, not untested โ€” same two tests fall through to this outer brace after the inner one
        Ok(ObjectHandle::null())
    }

    // -----------------------------------------------------------------------
    // get_page_content_for_appearance โ€” qpdf appearance placement
    // -----------------------------------------------------------------------

    /// Generate page content that draws the normal appearance as a Form XObject.
    ///
    /// This is the Rust counterpart of
    /// `QPDFAnnotationObjectHelper::getPageContentForAppearance`
    /// (`libqpdf/QPDFAnnotationObjectHelper.cc:78-226`). `name` is the complete
    /// PDF resource name, including its leading slash (for example,
    /// `"/Fxo1"`). An empty result means that the annotation has no usable
    /// normal appearance, its flags do not satisfy the requested contract, its
    /// rectangle or appearance bounding box is invalid, or its transformed
    /// appearance has zero width or height.
    pub fn get_page_content_for_appearance(
        &mut self,
        name: &str,
        rotate: i32,
        required_flags: i64,
        forbidden_flags: i64,
    ) -> Result<Vec<u8>> {
        let appearance = self.get_appearance_stream(b"N", None)?;
        self.build_page_content_for_appearance(
            name,
            appearance,
            rotate,
            required_flags,
            forbidden_flags,
        )
    }

    fn build_page_content_for_appearance(
        &mut self,
        name: &str,
        appearance: ObjectHandle,
        rotate: i32,
        required_flags: i64,
        forbidden_flags: i64,
    ) -> Result<Vec<u8>> {
        let Some(appearance_dict) = appearance.as_stream_dict() else {
            return Ok(Vec::new());
        };

        let flags = self.get_flags()?;
        if (flags & forbidden_flags) != 0 {
            return Ok(Vec::new());
        }
        if (flags & required_flags) != required_flags {
            return Ok(Vec::new());
        }

        // qpdf's `if (!(bbox_obj.isRectangle() && rect_obj.isRectangle()))`
        // (`QPDFAnnotationObjectHelper.cc:161-163`) short-circuits: `/BBox`
        // is dereferenced first, and a malformed `/BBox` means `/Rect` is
        // never touched at all.
        let bbox_handle = appearance_dict.try_get_key(b"/BBox")?;
        let Some(bbox) = rectangle_from_handle(&bbox_handle)? else {
            return Ok(Vec::new());
        };
        let Some(rect) = self.rectangle_for_key(b"/Rect")? else {
            return Ok(Vec::new());
        };
        let matrix_handle = appearance_dict.try_get_key(b"/Matrix")?;
        let matrix = matrix_from_handle(&matrix_handle)?.unwrap_or_default();

        let do_rotate = rotate != 0 && (flags & 0x10) != 0;
        let (rect, matrix) = if do_rotate {
            let mut rotated_matrix = Matrix::default();
            rotated_matrix.rotatex90(rotate);
            rotated_matrix.concat(matrix);
            let rect_width = rect.urx - rect.llx;
            let rect_height = rect.ury - rect.lly;
            let rotated_rect = match rotate {
                90 => Rectangle::new(
                    rect.llx,
                    rect.ury,
                    rect.llx + rect_height,
                    rect.ury + rect_width,
                ),
                180 => Rectangle::new(
                    rect.llx - rect_width,
                    rect.ury,
                    rect.llx,
                    rect.ury + rect_height,
                ),
                270 => Rectangle::new(
                    rect.llx - rect_height,
                    rect.ury - rect_width,
                    rect.llx,
                    rect.ury,
                ),
                _ => rect,
            };
            (rotated_rect, rotated_matrix)
        } else {
            (rect, matrix)
        };

        let transformed_bbox = matrix.transform_rectangle(bbox);
        let width = transformed_bbox.urx - transformed_bbox.llx;
        let height = transformed_bbox.ury - transformed_bbox.lly;
        if width == 0.0 || height == 0.0 {
            return Ok(Vec::new());
        }

        let mut placement = Matrix::default();
        placement.translate(rect.llx, rect.lly);
        placement.scale(
            (rect.urx - rect.llx) / width,
            (rect.ury - rect.lly) / height,
        );
        placement.translate(-transformed_bbox.llx, -transformed_bbox.lly);
        if do_rotate {
            placement.rotatex90(rotate);
        }

        appearance_dict.replace_key(b"/Subtype", ObjectHandle::name(b"Form".to_vec()))?;

        Ok(format!("q\n{} cm\n{} Do\nQ\n", placement.unparse(), name).into_bytes())
    }

    /// Return a normalized rectangle for a required numeric array key.
    fn rectangle_for_key(&mut self, key: &[u8]) -> Result<Option<Rectangle>> {
        let handle = self.resolved_key(key)?;
        rectangle_from_handle(&handle)
    }
}

// ---------------------------------------------------------------------------
// Private free functions
// ---------------------------------------------------------------------------

/// Prepend the `/` [`ObjectHandle::try_get_key`] requires to a decoded PDF name
/// value (e.g. from [`AnnotationObjectHelper::get_appearance_state`], which
/// like every other name-valued accessor in this crate returns the name
/// without it).
fn dict_key(name: &[u8]) -> Vec<u8> {
    let mut key = Vec::with_capacity(name.len() + 1);
    key.push(b'/');
    key.extend_from_slice(name);
    key
}

/// Resolve `handle` and coerce it to `f64` if it is an integer or real,
/// mirroring `QPDFObjectHandle::getValueAsNumber`.
fn as_number(handle: &ObjectHandle) -> Result<Option<f64>> {
    handle.try_dereference()?;
    Ok(handle
        .as_integer()
        .map(|n| n as f64)
        .or_else(|| handle.as_real()))
}

/// Resolve `handle` as a 4-element numeric array into a [`PageBox`],
/// mirroring `QPDFObjectHandle::getArrayAsRectangle`.
fn array_as_rectangle(handle: &ObjectHandle) -> Result<PageBox> {
    let zero = PageBox::new(0.0, 0.0, 0.0, 0.0);
    let Some(items) = handle.as_array() else {
        return Ok(zero);
    };
    if items.len() != 4 {
        return Ok(zero);
    }
    let mut nums = [0.0f64; 4];
    for (i, item) in items.iter().enumerate() {
        let Some(n) = as_number(item)? else {
            return Ok(zero);
        };
        nums[i] = n;
    }
    Ok(PageBox::new(
        nums[0].min(nums[2]),
        nums[1].min(nums[3]),
        nums[0].max(nums[2]),
        nums[1].max(nums[3]),
    ))
}

/// Return a normalized rectangle when `handle` is a valid four-number array.
fn rectangle_from_handle(handle: &ObjectHandle) -> Result<Option<Rectangle>> {
    let Some(items) = handle.try_as_array()? else {
        return Ok(None);
    };
    if items.len() != 4 {
        return Ok(None);
    }
    let mut numbers = [0.0; 4];
    for (index, item) in items.iter().enumerate() {
        let Some(number) = as_number(item)? else {
            return Ok(None);
        };
        numbers[index] = number;
    }
    Ok(Some(Rectangle::new(
        numbers[0].min(numbers[2]),
        numbers[1].min(numbers[3]),
        numbers[0].max(numbers[2]),
        numbers[1].max(numbers[3]),
    )))
}

/// Return a six-number matrix, or `None` when qpdf would use identity.
fn matrix_from_handle(handle: &ObjectHandle) -> Result<Option<Matrix>> {
    let Some(items) = handle.try_as_array()? else {
        return Ok(None);
    };
    if items.len() != 6 {
        return Ok(None);
    }
    let mut numbers = [0.0; 6];
    for (index, item) in items.iter().enumerate() {
        let Some(number) = as_number(item)? else {
            return Ok(None);
        };
        numbers[index] = number;
    }
    Ok(Some(Matrix::from(numbers)))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ObjectRef;

    #[test]
    fn appearance_stream_propagates_unresolved_child_error() {
        let unresolved = ObjectHandle::new_indirect_unresolved(ObjectRef::new(99, 0), -1);
        let appearance = ObjectHandle::dictionary(vec![(b"/N".to_vec(), unresolved)]);
        let annot = ObjectHandle::dictionary(vec![(b"/AP".to_vec(), appearance)]);
        let mut helper = AnnotationObjectHelper::new(annot);

        let error = helper
            .get_appearance_stream(b"N", None)
            .expect_err("unresolved appearance stream child must be reported");
        assert!(matches!(
            error,
            crate::Error::Internal(message) if message == "object 99 0 belongs to a dropped PDF"
        ));
    }
}