rpdfium 7676.6.0

A faithful Rust port of Google's PDFium PDF rendering engine
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
#![forbid(unsafe_code)]
#![doc = "rpdfium — a faithful Rust port of Google's PDFium PDF rendering engine."]

pub mod arc;
pub use arc::{ArcDocument, ArcLibrary, ArcPage};

mod image_decode;

use std::sync::{Arc, OnceLock};

use rpdfium_core::Name;
use rpdfium_font::{DashMapFontCache, FontCache as _, FontRef, ResolvedFont};
use rpdfium_page::display::{DisplayTree, walk};
use rpdfium_page::resource::ResourceDict;
use rpdfium_page::{InterpreterContext, collect_page_ids, interpret, resolve_resources};
use rpdfium_parser::{ObjectStore, tokenize_content_stream};

// Re-exports from rpdfium-core
pub use rpdfium_core::error::{ObjectId, ParseError, PdfError, PdfResult};
pub use rpdfium_core::{PdfString, PdfStringEncoding};

// Re-exports from rpdfium-parser
pub use rpdfium_parser::object::{Object, StreamData};

// Re-exports from rpdfium-render
pub use rpdfium_render::{
    RenderError, RgbaColor, compute_page_transform, render, render_with_images,
};

// Re-exports from rpdfium-font
pub use rpdfium_font::{
    FolderFontScanner, FontMapper, FontMatch, FontRequest, FontWeight, GlyphUsageTracker,
    base14_substitute, subset_truetype_font,
};

// Re-exports from rpdfium-doc
pub use rpdfium_doc::{
    Action, Annotation, AnnotationBorder, AnnotationFlags, AnnotationSubtypeData, AnnotationType,
    Bookmark, BorderStyle, Destination, DocError, DocMdpPermission, DocResult, DocumentMetadata,
    FdfData, FieldValue, InteractiveForm, NameTree, NumberTree, PageLabel, PageLabelStyle,
    SignatureObject, collect_signatures, export_fdf, format_label, import_fdf, parse_annotations,
    parse_bookmarks, parse_destination, parse_metadata, parse_page_labels,
};

// Re-exports from rpdfium-text
pub use rpdfium_text::{
    CharOrigin, CharRect, CharType, Link, LinkKind, SearchOptions, SearchResult, TextCharacter,
    TextExtractor, TextPage, TextPageFind, extract_links, search, search_case_insensitive,
    search_consecutive, search_normalized, search_normalized_case_insensitive, search_whole_word,
    search_whole_word_case_insensitive, segment_lines, segment_words,
};

// Re-exports from rpdfium-graphics
pub use rpdfium_graphics::{Bitmap, BitmapFormat, Color};

// Re-exports from rpdfium-page
pub use rpdfium_page::{DisplayNode, DisplayVisitor, OCContext, PageError, UsageType};

// Additional re-exports from rpdfium-core
pub use rpdfium_core::{Matrix, OpenOptions, ParsingMode, Point, Rect, Size};

// Re-export RenderConfig
pub use rpdfium_render::RenderConfig;

// ---------------------------------------------------------------------------
// Unified Error type
// ---------------------------------------------------------------------------

/// Unified error type for the rpdfium facade.
#[derive(Debug, thiserror::Error)]
pub enum Error {
    /// An error from the PDF parser layer.
    #[error(transparent)]
    Parse(#[from] PdfError),

    /// An error from the page interpreter.
    #[error(transparent)]
    Page(#[from] PageError),

    /// An error from the renderer.
    #[error(transparent)]
    Render(#[from] RenderError),

    /// An error from the document structure layer.
    #[error(transparent)]
    Doc(#[from] DocError),

    /// Page index is out of range.
    #[error("page index out of range: {index} (document has {count} pages)")]
    PageOutOfRange {
        /// The requested page index.
        index: u32,
        /// The total page count.
        count: u32,
    },
}

/// Convenience result alias for [`Error`].
pub type Result<T> = std::result::Result<T, Error>;

// ---------------------------------------------------------------------------
// Font cache bridge
// ---------------------------------------------------------------------------

/// Bridges the rpdfium-page `FontCache` trait to the rpdfium-font
/// `DashMapFontCache` implementation.
pub(crate) struct FontCacheBridge<'a> {
    pub(crate) font_cache: &'a DashMapFontCache,
    pub(crate) store: &'a ObjectStore<Arc<[u8]>>,
    pub(crate) resources: &'a ResourceDict,
}

impl rpdfium_page::FontCache for FontCacheBridge<'_> {
    fn glyph_width(&self, font_name: &Name, char_code: u16) -> Option<f32> {
        let font_id = self.resources.fonts.get(font_name)?;
        let font_ref = FontRef::new(*font_id);
        let resolved = self.font_cache.get_or_load(&font_ref, self.store).ok()?;
        Some(resolved.char_width(char_code) as f32)
    }

    fn get_resolved_font(&self, font_name: &Name) -> Option<Arc<ResolvedFont>> {
        let font_id = self.resources.fonts.get(font_name)?;
        let font_ref = FontRef::new(*font_id);
        self.font_cache.get_or_load(&font_ref, self.store).ok()
    }
}

// ---------------------------------------------------------------------------
// Library
// ---------------------------------------------------------------------------

/// The top-level library instance.
///
/// In the lifetime-based API, all documents and pages borrow from
/// the `Library`, ensuring they cannot outlive the engine context.
pub struct Library {
    _private: (),
    font_mapper: Option<Box<dyn FontMapper>>,
}

impl Library {
    /// Create a new `Library` instance with default system font discovery.
    pub fn new() -> Self {
        Self {
            _private: (),
            font_mapper: Some(Box::new(FolderFontScanner::new())),
        }
    }

    /// Create a `Library` with a custom font mapper.
    ///
    /// Use this for WASM targets, embedded systems, or when you want to
    /// provide fonts from a custom source.
    pub fn with_font_mapper(mapper: Box<dyn FontMapper>) -> Self {
        Self {
            _private: (),
            font_mapper: Some(mapper),
        }
    }

    /// Returns a reference to the font mapper, if configured.
    pub fn font_mapper(&self) -> Option<&dyn FontMapper> {
        self.font_mapper.as_deref()
    }
}

impl Default for Library {
    fn default() -> Self {
        Self::new()
    }
}

// ---------------------------------------------------------------------------
// Document
// ---------------------------------------------------------------------------

/// A parsed PDF document, borrowing from the [`Library`].
pub struct Document<'lib> {
    #[allow(dead_code)]
    library: &'lib Library,
    store: ObjectStore<Arc<[u8]>>,
    font_cache: DashMapFontCache,
    page_ids: Vec<ObjectId>,
    catalog_id: ObjectId,
    options: OpenOptions,
    oc_context: Option<rpdfium_page::OCContext>,
}

impl<'lib> Document<'lib> {
    /// Open a PDF document from in-memory data.
    ///
    /// Parses the file structure, resolves the page tree, and prepares
    /// the document for page access.
    pub fn open(
        library: &'lib Library,
        data: Vec<u8>,
        options: &OpenOptions,
    ) -> Result<Document<'lib>> {
        let arc_data: Arc<[u8]> = Arc::from(data);
        let store = ObjectStore::open_with_password(
            arc_data,
            options.parsing_mode,
            options.password.as_deref(),
        )?;
        let page_ids = collect_page_ids(&store)?;
        let catalog_id = store.trailer().root;
        let font_cache = DashMapFontCache::new();
        let oc_context = rpdfium_page::OCContext::from_catalog(&store, catalog_id);

        Ok(Document {
            library,
            store,
            font_cache,
            page_ids,
            catalog_id,
            options: options.clone(),
            oc_context,
        })
    }

    /// Open a PDF document from a file path.
    ///
    /// This is a convenience wrapper around [`Document::open()`] that reads
    /// the file contents into memory before parsing.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use rpdfium::{Library, OpenOptions};
    /// let lib = Library::new();
    /// let opts = OpenOptions::default();
    /// let doc = rpdfium::Document::open_file(&lib, "document.pdf", &opts)?;
    /// # Ok::<(), rpdfium::Error>(())
    /// ```
    pub fn open_file(
        library: &'lib Library,
        path: impl AsRef<std::path::Path>,
        options: &OpenOptions,
    ) -> Result<Document<'lib>> {
        let data = std::fs::read(path).map_err(PdfError::Io)?;
        Self::open(library, data, options)
    }

    /// Returns the number of pages in the document.
    pub fn page_count(&self) -> u32 {
        self.page_ids.len() as u32
    }

    /// Get a page by its zero-based index.
    pub fn page(&self, index: u32) -> Result<Page<'_>> {
        let count = self.page_count();
        if index >= count {
            return Err(Error::PageOutOfRange { index, count });
        }
        let page_dict_id = self.page_ids[index as usize];

        // Resolve the page dictionary to extract /MediaBox
        let page_obj = self.store.resolve(page_dict_id)?;
        let page_dict = page_obj
            .as_dict()
            .ok_or(PdfError::UnknownObject(page_dict_id))?;

        let media_box = parse_rect(page_dict, &Name::media_box(), &self.store)
            .or_else(|| {
                // Inherit /MediaBox from parent Pages node (PDF spec 7.7.3.4)
                let inherited =
                    rpdfium_page::find_inherited_entry(&self.store, page_dict, &Name::media_box())
                        .ok()??;
                parse_rect_from_obj(&inherited)
            })
            .unwrap_or(Rect::new(0.0, 0.0, 612.0, 792.0));

        Ok(Page {
            store: &self.store,
            font_cache: &self.font_cache,
            page_index: index,
            page_dict_id,
            media_box,
            display_tree: OnceLock::new(),
            options: &self.options,
            oc_context: self.oc_context.as_ref(),
        })
    }

    /// Parse document metadata from the `/Info` dictionary.
    pub fn metadata(&self) -> Result<Option<DocumentMetadata>> {
        match self.store.trailer().info {
            Some(info_id) => {
                let info_obj = self.store.resolve(info_id)?;
                let meta = parse_metadata(info_obj, &self.store)?;
                Ok(Some(meta))
            }
            None => Ok(None),
        }
    }

    /// Parse the document's bookmark (outline) tree.
    pub fn bookmarks(&self) -> Result<Vec<Bookmark>> {
        let catalog_obj = self.store.resolve(self.catalog_id)?;
        let bookmarks = parse_bookmarks(catalog_obj, &self.store)?;
        Ok(bookmarks)
    }

    /// Collect all digital signature fields from the document's AcroForm.
    ///
    /// Returns an empty `Vec` if the document has no AcroForm or no signature
    /// fields. Corresponds to `FPDF_GetSignatureCount` /
    /// `FPDF_GetSignatureObject` in PDFium's `fpdf_signature.h`.
    pub fn signatures(&self) -> Result<Vec<SignatureObject>> {
        let catalog = self.store.resolve(self.catalog_id)?;
        Ok(collect_signatures(catalog, &self.store)?)
    }

    /// Returns a reference to the underlying object store.
    pub fn store(&self) -> &ObjectStore<Arc<[u8]>> {
        &self.store
    }
}

// ---------------------------------------------------------------------------
// Page
// ---------------------------------------------------------------------------

/// A single page within a [`Document`].
pub struct Page<'doc> {
    store: &'doc ObjectStore<Arc<[u8]>>,
    font_cache: &'doc DashMapFontCache,
    page_index: u32,
    page_dict_id: ObjectId,
    media_box: Rect,
    display_tree: OnceLock<DisplayTree>,
    options: &'doc OpenOptions,
    oc_context: Option<&'doc rpdfium_page::OCContext>,
}

impl<'doc> Page<'doc> {
    /// Returns the page's media box (the bounding box of the physical medium).
    pub fn media_box(&self) -> Rect {
        self.media_box
    }

    /// Returns the page's crop box, if explicitly set.
    ///
    /// Defaults to the media box per the PDF spec if not present, but this
    /// method returns `None` when the key is absent.
    pub fn crop_box(&self) -> Result<Option<Rect>> {
        let page_obj = self.store.resolve(self.page_dict_id)?;
        let page_dict = page_obj
            .as_dict()
            .ok_or(PdfError::UnknownObject(self.page_dict_id))?;
        Ok(parse_rect(page_dict, &Name::crop_box(), self.store))
    }

    /// Returns the page rotation in degrees (0, 90, 180, or 270).
    pub fn rotation(&self) -> Result<u32> {
        let page_obj = self.store.resolve(self.page_dict_id)?;
        let page_dict = page_obj
            .as_dict()
            .ok_or(PdfError::UnknownObject(self.page_dict_id))?;
        let rotation = page_dict
            .get(&Name::rotate())
            .and_then(|obj| self.store.deep_resolve(obj).ok().and_then(|o| o.as_i64()))
            .unwrap_or(0);
        // Normalize to 0-359 range (handles negative values from malformed PDFs)
        Ok(rotation.rem_euclid(360) as u32)
    }

    /// Interpret the page content stream into a display tree.
    ///
    /// The result is cached in a `OnceLock` so subsequent calls return
    /// the same tree without re-interpretation.
    pub fn interpret(&self) -> Result<&DisplayTree> {
        if let Some(tree) = self.display_tree.get() {
            return Ok(tree);
        }

        let tree = self.interpret_inner()?;

        // Store the tree; if another thread raced us, that's fine — we
        // just discard ours and use theirs.
        let _ = self.display_tree.set(tree);
        Ok(self.display_tree.get().unwrap())
    }

    /// Internal interpretation logic.
    fn interpret_inner(&self) -> Result<DisplayTree> {
        let page_obj = self.store.resolve(self.page_dict_id)?;
        let page_dict = page_obj
            .as_dict()
            .ok_or(PdfError::UnknownObject(self.page_dict_id))?;

        // Decode content stream(s)
        let content_bytes = decode_page_contents(page_dict, self.store)?;

        // Tokenize
        let operators = tokenize_content_stream(&content_bytes)?;

        // Resolve resources
        let resources = resolve_resources(self.store, page_dict)?;

        // Create the font cache bridge
        let bridge = FontCacheBridge {
            font_cache: self.font_cache,
            store: self.store,
            resources: &resources,
        };

        let ctx = InterpreterContext {
            store: self.store,
            font_cache: &bridge,
            mode: self.options.parsing_mode,
            oc_context: self.oc_context,
        };

        let tree = interpret(
            &operators,
            &ctx,
            &resources,
            self.options.max_operators_per_page,
        )?;
        Ok(tree)
    }

    /// Render the page to a bitmap.
    pub fn render(&self, config: &RenderConfig) -> Result<rpdfium_graphics::Bitmap> {
        let tree = self.interpret()?;
        let decoder = image_decode::PdfImageDecoder::new(self.store);
        let bitmap = rpdfium_render::render_with_images(tree, config, &decoder)?;
        Ok(bitmap)
    }

    /// Extract text from the page.
    pub fn text(&self) -> Result<TextPage> {
        let tree = self.interpret()?;
        let mut extractor = TextExtractor::new();
        walk(tree, &mut extractor);
        let (characters, run_ids) = extractor.into_characters();
        Ok(TextPage::new_with_run_ids(characters, run_ids, false))
    }

    /// Parse annotations on this page.
    pub fn annotations(&self) -> Result<Vec<Annotation>> {
        let page_obj = self.store.resolve(self.page_dict_id)?;
        let page_dict = page_obj
            .as_dict()
            .ok_or(PdfError::UnknownObject(self.page_dict_id))?;
        match page_dict.get(&Name::annots()) {
            Some(annots_obj) => {
                let annots = parse_annotations(annots_obj, self.store)?;
                Ok(annots)
            }
            None => Ok(Vec::new()),
        }
    }

    /// Returns the zero-based page index.
    pub fn index(&self) -> u32 {
        self.page_index
    }
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Parse a rectangle from a dictionary key (e.g. /MediaBox, /CropBox).
pub(crate) fn parse_rect(
    dict: &std::collections::HashMap<Name, Object>,
    key: &Name,
    store: &ObjectStore<Arc<[u8]>>,
) -> Option<Rect> {
    let obj = dict.get(key)?;
    let resolved = store.deep_resolve(obj).ok()?;
    parse_rect_from_obj(resolved)
}

/// Parse a rectangle from an already-resolved Object.
pub(crate) fn parse_rect_from_obj(obj: &Object) -> Option<Rect> {
    let arr = obj.as_array()?;
    if arr.len() < 4 {
        return None;
    }
    let vals: Vec<f64> = arr.iter().take(4).filter_map(|o| o.as_f64()).collect();
    if vals.len() < 4 {
        return None;
    }
    Some(Rect::new(vals[0], vals[1], vals[2], vals[3]))
}

/// Decode page /Contents into a single byte buffer.
///
/// /Contents can be a single stream reference or an array of stream references.
pub(crate) fn decode_page_contents(
    page_dict: &std::collections::HashMap<Name, Object>,
    store: &ObjectStore<Arc<[u8]>>,
) -> std::result::Result<Vec<u8>, PdfError> {
    let contents_obj = match page_dict.get(&Name::contents()) {
        Some(obj) => obj,
        None => return Ok(Vec::new()),
    };

    let resolved = store.deep_resolve(contents_obj)?;
    match resolved {
        Object::Stream { .. } => {
            // Single stream — decode it
            store.decode_stream(resolved)
        }
        Object::Array(arr) => {
            // Array of stream references — concatenate decoded bytes
            let mut all_bytes = Vec::new();
            for item in arr {
                if let Some(ref_id) = item.as_reference() {
                    let stream_obj = store.resolve(ref_id)?;
                    if let Object::Stream { .. } = stream_obj {
                        let decoded = store.decode_stream(stream_obj)?;
                        if !all_bytes.is_empty() {
                            // Ensure streams are separated by whitespace
                            all_bytes.push(b' ');
                        }
                        all_bytes.extend_from_slice(&decoded);
                    }
                }
            }
            Ok(all_bytes)
        }
        Object::Reference(id) => {
            // A reference that resolved to something — try to decode it as a stream
            let stream_obj = store.resolve(*id)?;
            if let Object::Stream { .. } = stream_obj {
                store.decode_stream(stream_obj)
            } else {
                Ok(Vec::new())
            }
        }
        _ => Ok(Vec::new()),
    }
}