rpdfium 7676.6.4

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
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
//! Arc-based wrappers for WASM and async use cases.
//!
//! These types wrap the core engine in `Arc` so they can be sent across
//! threads and held in `'static` contexts (e.g. `wasm_bindgen` futures,
//! async runtimes). All types are `Send + Sync + 'static`.

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

use rpdfium_core::error::{ObjectId, PdfError};
use rpdfium_core::{Matrix, Name, OpenOptions, Rect};
use rpdfium_doc::{
    Annotation, Bookmark, DocumentMetadata, FileSpec, PageStructure, StructTree, ViewerPreferences,
    collect_attachments, collect_signatures,
};
use rpdfium_font::DashMapFontCache;
use rpdfium_page::display::{DisplayTree, walk};
use rpdfium_page::{InterpreterContext, collect_page_ids, interpret, resolve_resources};
use rpdfium_parser::{ObjectStore, tokenize_content_stream};
use rpdfium_text::{TextExtractor, TextPage};

use rpdfium_graphics::Bitmap;

use crate::{
    Error, FontCacheBridge, PdfReader, RenderConfig, Result, SignatureObject, decode_page_contents,
    decode_page_thumbnail, parse_annotations, parse_bookmarks, parse_metadata, parse_rect,
    parse_rect_from_obj, thumbnail_raw_or_decoded,
};

// ---------------------------------------------------------------------------
// ArcLibrary
// ---------------------------------------------------------------------------

/// Arc-wrapped library instance for WASM/async contexts.
#[derive(Clone)]
pub struct ArcLibrary {
    #[allow(dead_code)]
    inner: Arc<LibraryInner>,
}

struct LibraryInner {
    _private: (),
}

impl ArcLibrary {
    /// Create a new `ArcLibrary` instance.
    pub fn new() -> Self {
        Self {
            inner: Arc::new(LibraryInner { _private: () }),
        }
    }
}

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

// ---------------------------------------------------------------------------
// ArcDocument
// ---------------------------------------------------------------------------

/// Arc-wrapped document for WASM/async contexts.
///
/// Unlike [`Document`](crate::Document) which borrows from [`ArcLibrary`],
/// `ArcDocument` uses `Arc` internally and is `Send + Sync + 'static`.
#[derive(Clone)]
pub struct ArcDocument {
    inner: Arc<DocumentInner>,
}

struct DocumentInner {
    store: ObjectStore<Arc<[u8]>>,
    font_cache: DashMapFontCache,
    page_ids: Vec<ObjectId>,
    catalog_id: ObjectId,
    options: OpenOptions,
    oc_context: Option<rpdfium_page::OCContext>,
}

impl ArcDocument {
    /// 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: &ArcLibrary, data: Vec<u8>, options: &OpenOptions) -> Result<Self> {
        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(ArcDocument {
            inner: Arc::new(DocumentInner {
                store,
                font_cache,
                page_ids,
                catalog_id,
                options: options.clone(),
                oc_context,
            }),
        })
    }

    /// Upstream-aligned alias for [`open()`](Self::open).
    ///
    /// Corresponds to `FPDF_LoadMemDocument`.
    #[inline]
    pub fn load_mem_document(
        library: &ArcLibrary,
        data: Vec<u8>,
        options: &OpenOptions,
    ) -> Result<Self> {
        Self::open(library, data, options)
    }

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

    /// Upstream-aligned alias for [`open_file()`](Self::open_file).
    ///
    /// Corresponds to `FPDF_LoadDocument`.
    #[inline]
    pub fn load_document(
        library: &ArcLibrary,
        path: impl AsRef<std::path::Path>,
        options: &OpenOptions,
    ) -> Result<Self> {
        Self::open_file(library, path, options)
    }

    /// Load a PDF document from a custom reader.
    ///
    /// Reads all data from `reader` into memory, then delegates to
    /// [`ArcDocument::open()`].  This is the idiomatic way to load PDFs from
    /// non-filesystem sources (network, encrypted containers, custom VFS).
    ///
    /// Corresponds to `FPDF_LoadCustomDocument` in PDFium's `fpdf_view.h`.
    pub fn open_custom(
        library: &ArcLibrary,
        reader: impl PdfReader,
        options: &OpenOptions,
    ) -> Result<Self> {
        let len = reader.file_len() as usize;
        let mut data = vec![0u8; len];
        let mut offset = 0;
        while offset < data.len() {
            let n = reader
                .read_at(offset as u64, &mut data[offset..])
                .map_err(PdfError::Io)?;
            if n == 0 {
                break;
            }
            offset += n;
        }
        data.truncate(offset);
        Self::open(library, data, options)
    }

    /// Upstream-aligned alias for [`open_custom()`](Self::open_custom).
    ///
    /// Corresponds to `FPDF_LoadCustomDocument`.
    #[inline]
    pub fn load_custom_document(
        library: &ArcLibrary,
        reader: impl PdfReader,
        options: &OpenOptions,
    ) -> Result<Self> {
        Self::open_custom(library, reader, options)
    }

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

    /// Upstream-aligned alias for [`page_count()`](Self::page_count).
    ///
    /// Corresponds to `FPDF_GetPageCount`.
    #[inline]
    pub fn get_page_count(&self) -> u32 {
        self.page_count()
    }

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

        // Resolve the page dictionary to extract /MediaBox
        let page_obj = self.inner.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.inner.store)
            .or_else(|| {
                let inherited = rpdfium_page::find_inherited_entry(
                    &self.inner.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(ArcPage {
            doc: self.clone(),
            page_index: index,
            page_dict_id,
            media_box,
            display_tree: OnceLock::new(),
        })
    }

    /// Upstream-aligned alias for [`page()`](Self::page).
    ///
    /// Corresponds to `FPDF_LoadPage`.
    #[inline]
    pub fn load_page(&self, index: u32) -> Result<ArcPage> {
        self.page(index)
    }

    /// Parse document metadata from the `/Info` dictionary.
    pub fn metadata(&self) -> Result<Option<DocumentMetadata>> {
        match self.inner.store.trailer().info {
            Some(info_id) => {
                let info_obj = self.inner.store.resolve(info_id)?;
                let meta = parse_metadata(info_obj, &self.inner.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.inner.store.resolve(self.inner.catalog_id)?;
        let bookmarks = parse_bookmarks(catalog_obj, &self.inner.store)?;
        Ok(bookmarks)
    }

    /// Collect all digital signature fields from the document's AcroForm.
    pub fn signatures(&self) -> Result<Vec<SignatureObject>> {
        let catalog = self.inner.store.resolve(self.inner.catalog_id)?;
        Ok(collect_signatures(catalog, &self.inner.store)?)
    }

    /// Returns the PDF file version as `(major, minor)`.
    ///
    /// Corresponds to `FPDF_GetFileVersion`.
    pub fn pdf_version(&self) -> (u8, u8) {
        let v = self.inner.store.file_version();
        (v.major, v.minor)
    }

    /// Upstream-aligned alias for [`pdf_version()`](Self::pdf_version).
    ///
    /// Corresponds to `FPDF_GetFileVersion`.
    #[inline]
    pub fn get_file_version(&self) -> (u8, u8) {
        self.pdf_version()
    }

    /// Returns the document access permissions as a raw bit field.
    ///
    /// Returns `None` if the document is not encrypted.
    /// Corresponds to `FPDF_GetDocPermissions`.
    pub fn permissions(&self) -> Option<u32> {
        self.inner
            .store
            .security_handler()
            .map(|h| h.permissions().bits() as u32)
    }

    /// Upstream-aligned alias for [`permissions()`](Self::permissions).
    ///
    /// Corresponds to `FPDF_GetDocPermissions`.
    #[inline]
    pub fn get_doc_permissions(&self) -> Option<u32> {
        self.permissions()
    }

    /// Upstream-aligned alias for [`permissions()`](Self::permissions).
    ///
    /// Corresponds to `FPDF_GetDocUserPermissions`.
    #[inline]
    pub fn get_doc_user_permissions(&self) -> Option<u32> {
        self.permissions()
    }

    /// Non-upstream convenience alias for [`permissions()`](Self::permissions).
    ///
    /// Prefer [`get_doc_user_permissions()`](Self::get_doc_user_permissions),
    /// which matches the upstream `FPDF_GetDocUserPermissions` name exactly.
    ///
    /// Corresponds to `FPDF_GetDocUserPermissions`.
    #[deprecated(
        note = "use `get_doc_user_permissions()` — matches upstream FPDF_GetDocUserPermissions"
    )]
    #[inline]
    pub fn user_permissions(&self) -> Option<u32> {
        self.permissions()
    }

    /// Returns the security handler revision number.
    ///
    /// Returns `None` if the document is not encrypted.
    /// Corresponds to `FPDF_GetSecurityHandlerRevision`.
    pub fn security_revision(&self) -> Option<u32> {
        self.inner.store.security_handler().map(|h| h.revision())
    }

    /// Upstream-aligned alias for [`security_revision()`](Self::security_revision).
    ///
    /// Corresponds to `FPDF_GetSecurityHandlerRevision`.
    #[inline]
    pub fn get_security_handler_revision(&self) -> Option<u32> {
        self.security_revision()
    }

    /// Parse the document's viewer preferences from `/ViewerPreferences`.
    ///
    /// Returns `None` if no `/ViewerPreferences` dictionary is present in
    /// the catalog.
    pub fn viewer_preferences(&self) -> Result<Option<ViewerPreferences>> {
        let store = &self.inner.store;
        let catalog = store.resolve(self.inner.catalog_id)?;
        let catalog_dict = catalog
            .as_dict()
            .ok_or(PdfError::UnknownObject(self.inner.catalog_id))?;
        let vp_obj = match catalog_dict
            .get(&Name::viewer_preferences())
            .and_then(|o| store.deep_resolve(o).ok())
        {
            Some(o) => o,
            None => return Ok(None),
        };
        let vp_dict = match vp_obj.as_dict() {
            Some(d) => d,
            None => return Ok(None),
        };
        Ok(Some(ViewerPreferences::from_dict(vp_dict, store)))
    }

    /// Collect all embedded file attachments from `/Root/Names/EmbeddedFiles`.
    ///
    /// Corresponds to `FPDFDoc_GetAttachmentCount` / `FPDFDoc_GetAttachment`.
    pub fn attachments(&self) -> Result<Vec<FileSpec>> {
        let catalog = self.inner.store.resolve(self.inner.catalog_id)?;
        Ok(collect_attachments(catalog, &self.inner.store)?)
    }

    /// Returns the number of embedded file attachments in the document.
    ///
    /// Corresponds to `FPDFDoc_GetAttachmentCount`.
    pub fn attachment_count(&self) -> Result<usize> {
        Ok(self.attachments()?.len())
    }

    /// Upstream-aligned alias for [`attachment_count()`](Self::attachment_count).
    ///
    /// Corresponds to `FPDFDoc_GetAttachmentCount`.
    #[inline]
    pub fn doc_get_attachment_count(&self) -> Result<usize> {
        self.attachment_count()
    }

    /// Non-upstream alias — use [`doc_get_attachment_count()`](Self::doc_get_attachment_count).
    ///
    /// Corresponds to `FPDFDoc_GetAttachmentCount`.
    #[deprecated(
        note = "use `doc_get_attachment_count()` — matches upstream `FPDFDoc_GetAttachmentCount`"
    )]
    #[inline]
    pub fn get_attachment_count(&self) -> Result<usize> {
        self.attachment_count()
    }

    /// Returns the embedded file attachment at the given zero-based index.
    ///
    /// Returns `Ok(None)` if `index` is out of range.
    ///
    /// Corresponds to `FPDFDoc_GetAttachment`.
    pub fn attachment_at(&self, index: usize) -> Result<Option<FileSpec>> {
        let all = self.attachments()?;
        Ok(all.into_iter().nth(index))
    }

    /// Upstream-aligned alias for [`attachment_at()`](Self::attachment_at).
    ///
    /// Corresponds to `FPDFDoc_GetAttachment`.
    #[inline]
    pub fn doc_get_attachment(&self, index: usize) -> Result<Option<FileSpec>> {
        self.attachment_at(index)
    }

    /// Non-upstream alias — use [`doc_get_attachment()`](Self::doc_get_attachment).
    ///
    /// Corresponds to `FPDFDoc_GetAttachment`.
    #[deprecated(note = "use `doc_get_attachment()` — matches upstream `FPDFDoc_GetAttachment`")]
    #[inline]
    pub fn get_attachment(&self, index: usize) -> Result<Option<FileSpec>> {
        self.attachment_at(index)
    }

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

    /// Render multiple pages in parallel using rayon.
    ///
    /// Each page is interpreted and rendered independently. Individual page
    /// errors are captured per-page; other pages still succeed.
    pub fn render_pages_parallel(
        &self,
        page_indices: &[u32],
        config: &RenderConfig,
    ) -> Vec<Result<rpdfium_graphics::Bitmap>> {
        use rayon::prelude::*;

        page_indices
            .par_iter()
            .map(|&page_idx| {
                let page = self.page(page_idx)?;
                let tree = page.interpret()?;
                let decoder = crate::image_decode::PdfImageDecoder::new(&page.doc.inner.store);
                let bitmap = rpdfium_render::render_with_images(tree, config, &decoder)?;
                Ok(bitmap)
            })
            .collect()
    }

    /// Render all pages in parallel.
    pub fn render_all_pages_parallel(
        &self,
        config: &RenderConfig,
    ) -> Vec<Result<rpdfium_graphics::Bitmap>> {
        let count = self.page_count();
        let indices: Vec<u32> = (0..count).collect();
        self.render_pages_parallel(&indices, config)
    }
}

// ---------------------------------------------------------------------------
// ArcPage
// ---------------------------------------------------------------------------

/// Arc-wrapped page for WASM/async contexts.
///
/// Unlike [`Page`](crate::Page) which borrows from [`Document`](crate::Document),
/// `ArcPage` holds a cloned `ArcDocument` and is `Send + Sync + 'static`.
#[derive(Clone)]
pub struct ArcPage {
    doc: ArcDocument,
    page_index: u32,
    page_dict_id: ObjectId,
    media_box: Rect,
    display_tree: OnceLock<DisplayTree>,
}

impl ArcPage {
    /// Returns the page's media box (the bounding box of the physical medium).
    ///
    /// Corresponds to `FPDFPage_GetMediaBox`.
    pub fn media_box(&self) -> Rect {
        self.media_box
    }

    /// ADR-019 T2 alias for [`media_box()`](Self::media_box).
    ///
    /// Corresponds to `FPDFPage_GetMediaBox`.
    #[inline]
    pub fn page_get_media_box(&self) -> Rect {
        self.media_box()
    }

    /// Deprecated — use [`page_get_media_box()`](Self::page_get_media_box).
    ///
    /// Corresponds to `FPDFPage_GetMediaBox`.
    #[deprecated(note = "use `page_get_media_box()` — matches upstream `FPDFPage_GetMediaBox`")]
    #[inline]
    pub fn get_media_box(&self) -> Rect {
        self.media_box()
    }

    /// Returns the page width in points as `f32`.
    ///
    /// Corresponds to `FPDF_GetPageWidthF`.
    pub fn page_width_f(&self) -> f32 {
        self.media_box.width() as f32
    }

    /// Upstream-aligned alias for [`page_width_f()`](Self::page_width_f).
    ///
    /// Corresponds to `FPDF_GetPageWidthF`.
    #[inline]
    pub fn get_page_width_f(&self) -> f32 {
        self.page_width_f()
    }

    /// Returns the page width in points as `f64`.
    ///
    /// Corresponds to `FPDF_GetPageWidth`.
    pub fn page_width(&self) -> f64 {
        self.media_box.width()
    }

    /// Upstream-aligned alias for [`page_width()`](Self::page_width).
    ///
    /// Corresponds to `FPDF_GetPageWidth`.
    #[inline]
    pub fn get_page_width(&self) -> f64 {
        self.page_width()
    }

    /// Returns the page height in points as `f32`.
    ///
    /// Corresponds to `FPDF_GetPageHeightF`.
    pub fn page_height_f(&self) -> f32 {
        self.media_box.height() as f32
    }

    /// Upstream-aligned alias for [`page_height_f()`](Self::page_height_f).
    ///
    /// Corresponds to `FPDF_GetPageHeightF`.
    #[inline]
    pub fn get_page_height_f(&self) -> f32 {
        self.page_height_f()
    }

    /// Returns the page height in points as `f64`.
    ///
    /// Corresponds to `FPDF_GetPageHeight`.
    pub fn page_height(&self) -> f64 {
        self.media_box.height()
    }

    /// Upstream-aligned alias for [`page_height()`](Self::page_height).
    ///
    /// Corresponds to `FPDF_GetPageHeight`.
    #[inline]
    pub fn get_page_height(&self) -> f64 {
        self.page_height()
    }

    /// Returns the page's crop box, if explicitly set.
    ///
    /// Corresponds to `FPDFPage_GetCropBox`.
    pub fn crop_box(&self) -> Result<Option<Rect>> {
        let store = &self.doc.inner.store;
        let page_obj = 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(), store))
    }

    /// ADR-019 T2 alias for [`crop_box()`](Self::crop_box).
    ///
    /// Corresponds to `FPDFPage_GetCropBox`.
    #[inline]
    pub fn page_get_crop_box(&self) -> Result<Option<Rect>> {
        self.crop_box()
    }

    /// Deprecated — use [`page_get_crop_box()`](Self::page_get_crop_box).
    ///
    /// Corresponds to `FPDFPage_GetCropBox`.
    #[deprecated(note = "use `page_get_crop_box()` — matches upstream `FPDFPage_GetCropBox`")]
    #[inline]
    pub fn get_crop_box(&self) -> Result<Option<Rect>> {
        self.crop_box()
    }

    /// Returns the page's bleed box, if explicitly set.
    ///
    /// Corresponds to `FPDFPage_GetBleedBox`.
    pub fn bleed_box(&self) -> Result<Option<Rect>> {
        let store = &self.doc.inner.store;
        let page_obj = 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::bleed_box(), store))
    }

    /// ADR-019 T2 alias for [`bleed_box()`](Self::bleed_box).
    ///
    /// Corresponds to `FPDFPage_GetBleedBox`.
    #[inline]
    pub fn page_get_bleed_box(&self) -> Result<Option<Rect>> {
        self.bleed_box()
    }

    /// Deprecated — use [`page_get_bleed_box()`](Self::page_get_bleed_box).
    ///
    /// Corresponds to `FPDFPage_GetBleedBox`.
    #[deprecated(note = "use `page_get_bleed_box()` — matches upstream `FPDFPage_GetBleedBox`")]
    #[inline]
    pub fn get_bleed_box(&self) -> Result<Option<Rect>> {
        self.bleed_box()
    }

    /// Returns the page's trim box, if explicitly set.
    ///
    /// Corresponds to `FPDFPage_GetTrimBox`.
    pub fn trim_box(&self) -> Result<Option<Rect>> {
        let store = &self.doc.inner.store;
        let page_obj = 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::trim_box(), store))
    }

    /// ADR-019 T2 alias for [`trim_box()`](Self::trim_box).
    ///
    /// Corresponds to `FPDFPage_GetTrimBox`.
    #[inline]
    pub fn page_get_trim_box(&self) -> Result<Option<Rect>> {
        self.trim_box()
    }

    /// Deprecated — use [`page_get_trim_box()`](Self::page_get_trim_box).
    ///
    /// Corresponds to `FPDFPage_GetTrimBox`.
    #[deprecated(note = "use `page_get_trim_box()` — matches upstream `FPDFPage_GetTrimBox`")]
    #[inline]
    pub fn get_trim_box(&self) -> Result<Option<Rect>> {
        self.trim_box()
    }

    /// Returns the page's art box, if explicitly set.
    ///
    /// Corresponds to `FPDFPage_GetArtBox`.
    pub fn art_box(&self) -> Result<Option<Rect>> {
        let store = &self.doc.inner.store;
        let page_obj = 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::art_box(), store))
    }

    /// ADR-019 T2 alias for [`art_box()`](Self::art_box).
    ///
    /// Corresponds to `FPDFPage_GetArtBox`.
    #[inline]
    pub fn page_get_art_box(&self) -> Result<Option<Rect>> {
        self.art_box()
    }

    /// Deprecated — use [`page_get_art_box()`](Self::page_get_art_box).
    ///
    /// Corresponds to `FPDFPage_GetArtBox`.
    #[deprecated(note = "use `page_get_art_box()` — matches upstream `FPDFPage_GetArtBox`")]
    #[inline]
    pub fn get_art_box(&self) -> Result<Option<Rect>> {
        self.art_box()
    }

    /// Returns the page bounding box: intersection of media box and crop box.
    ///
    /// If no crop box is set, returns the media box.
    /// Corresponds to `FPDF_GetPageBoundingBox`.
    pub fn bounding_box(&self) -> Result<Rect> {
        let crop = self.crop_box()?;
        let media = self.media_box;
        Ok(match crop {
            Some(c) => Rect::new(
                media.left.max(c.left),
                media.bottom.max(c.bottom),
                media.right.min(c.right),
                media.top.min(c.top),
            ),
            None => media,
        })
    }

    /// Upstream-aligned alias for [`bounding_box()`](Self::bounding_box).
    ///
    /// Corresponds to `FPDF_GetPageBoundingBox`.
    #[inline]
    pub fn get_page_bounding_box(&self) -> Result<Rect> {
        self.bounding_box()
    }

    /// Returns the page rotation in degrees (0, 90, 180, or 270).
    ///
    /// Corresponds to `FPDFPage_GetRotation`.
    pub fn rotation(&self) -> Result<u32> {
        let store = &self.doc.inner.store;
        let page_obj = 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| 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)
    }

    /// ADR-019 T2 alias for [`rotation()`](Self::rotation).
    ///
    /// Corresponds to `FPDFPage_GetRotation`.
    #[inline]
    pub fn page_get_rotation(&self) -> Result<u32> {
        self.rotation()
    }

    /// Deprecated — use [`page_get_rotation()`](Self::page_get_rotation).
    ///
    /// Corresponds to `FPDFPage_GetRotation`.
    #[deprecated(note = "use `page_get_rotation()` — matches upstream `FPDFPage_GetRotation`")]
    #[inline]
    pub fn get_rotation(&self) -> Result<u32> {
        self.rotation()
    }

    /// Deprecated — use [`page_get_rotation()`](Self::page_get_rotation).
    ///
    /// Corresponds to `FPDFPage_GetRotation`.
    #[deprecated(note = "use `page_get_rotation()` — matches upstream `FPDFPage_GetRotation`")]
    #[inline]
    pub fn get_page_rotation(&self) -> Result<u32> {
        self.rotation()
    }

    /// 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.
        let _ = self.display_tree.set(tree);
        Ok(self.display_tree.get().unwrap())
    }

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

        let content_bytes = decode_page_contents(page_dict, store)?;
        let operators = tokenize_content_stream(&content_bytes)?;
        let resources = resolve_resources(store, page_dict)?;

        let bridge = FontCacheBridge {
            font_cache: &self.doc.inner.font_cache,
            store,
            resources: &resources,
        };

        let ctx = InterpreterContext {
            store,
            font_cache: &bridge,
            mode: self.doc.inner.options.parsing_mode,
            oc_context: self.doc.inner.oc_context.as_ref(),
        };

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

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

    /// Upstream-aligned alias for [`render()`](Self::render).
    ///
    /// Corresponds to `FPDF_RenderPageBitmap`.
    #[inline]
    pub fn render_page_bitmap(&self, config: &RenderConfig) -> Result<rpdfium_graphics::Bitmap> {
        self.render(config)
    }

    /// Render the page using a custom transformation matrix and optional
    /// device-space clip rectangle.
    ///
    /// Corresponds to `FPDF_RenderPageBitmapWithMatrix`.
    pub fn render_with_matrix(
        &self,
        matrix: Matrix,
        clip: Option<Rect>,
        width: u32,
        height: u32,
    ) -> Result<rpdfium_graphics::Bitmap> {
        let mut config = RenderConfig::default()
            .with_size(width, height)
            .with_transform(matrix);
        if let Some(r) = clip {
            config = config.with_clip(r);
        }
        self.render(&config)
    }

    /// Upstream-aligned alias for [`render_with_matrix()`](Self::render_with_matrix).
    ///
    /// Corresponds to `FPDF_RenderPageBitmapWithMatrix`.
    #[inline]
    pub fn render_page_bitmap_with_matrix(
        &self,
        matrix: Matrix,
        clip: Option<Rect>,
        width: u32,
        height: u32,
    ) -> Result<rpdfium_graphics::Bitmap> {
        self.render_with_matrix(matrix, clip, width, height)
    }

    /// 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 store = &self.doc.inner.store;
        let page_obj = 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, store)?;
                Ok(annots)
            }
            None => Ok(Vec::new()),
        }
    }

    /// Get the structure tree elements for this page.
    ///
    /// Returns `Some(PageStructure)` if the document has a tagged PDF structure tree.
    /// Returns `None` if the document is not tagged or has no structure tree.
    pub fn page_structure(&self) -> Option<PageStructure> {
        let store = &self.doc.inner.store;
        let catalog_id = self.doc.inner.catalog_id;

        let catalog_obj = match store.resolve(catalog_id) {
            Ok(obj) => obj,
            Err(_) => return None,
        };

        let catalog_dict = catalog_obj.as_dict()?;

        let struct_tree = match StructTree::from_catalog(catalog_dict, store) {
            Ok(Some(tree)) => tree,
            _ => return None,
        };

        Some(PageStructure::for_page(&struct_tree, self.page_dict_id))
    }

    /// Returns the page's embedded thumbnail image, if present.
    ///
    /// Returns `Ok(None)` if the page has no thumbnail.
    ///
    /// Corresponds to `FPDFPage_GetThumbnailAsBitmap`.
    pub fn thumbnail(&self) -> Result<Option<Bitmap>> {
        let store = &self.doc.inner.store;
        decode_page_thumbnail(store, self.page_dict_id)
    }

    /// ADR-019 T2 alias for [`thumbnail()`](Self::thumbnail).
    ///
    /// Corresponds to `FPDFPage_GetThumbnailAsBitmap`.
    #[inline]
    pub fn page_get_thumbnail_as_bitmap(&self) -> Result<Option<Bitmap>> {
        self.thumbnail()
    }

    /// Deprecated — use [`page_get_thumbnail_as_bitmap()`](Self::page_get_thumbnail_as_bitmap).
    ///
    /// Corresponds to `FPDFPage_GetThumbnailAsBitmap`.
    #[deprecated(
        note = "use `page_get_thumbnail_as_bitmap()` — matches upstream `FPDFPage_GetThumbnailAsBitmap`"
    )]
    #[inline]
    pub fn get_thumbnail_as_bitmap(&self) -> Result<Option<Bitmap>> {
        self.thumbnail()
    }

    /// Returns the decoded (decompressed) thumbnail image data, if present.
    ///
    /// Corresponds to `FPDFPage_GetDecodedThumbnailData`.
    pub fn thumbnail_decoded_bytes(&self) -> Result<Option<Vec<u8>>> {
        let store = &self.doc.inner.store;
        thumbnail_raw_or_decoded(store, self.page_dict_id, true)
    }

    /// ADR-019 T2 alias for [`thumbnail_decoded_bytes()`](Self::thumbnail_decoded_bytes).
    ///
    /// Corresponds to `FPDFPage_GetDecodedThumbnailData`.
    #[inline]
    pub fn page_get_decoded_thumbnail_data(&self) -> Result<Option<Vec<u8>>> {
        self.thumbnail_decoded_bytes()
    }

    /// Deprecated — use [`page_get_decoded_thumbnail_data()`](Self::page_get_decoded_thumbnail_data).
    ///
    /// Corresponds to `FPDFPage_GetDecodedThumbnailData`.
    #[deprecated(
        note = "use `page_get_decoded_thumbnail_data()` — matches upstream `FPDFPage_GetDecodedThumbnailData`"
    )]
    #[inline]
    pub fn get_decoded_thumbnail_data(&self) -> Result<Option<Vec<u8>>> {
        self.thumbnail_decoded_bytes()
    }

    /// Returns the raw (compressed) thumbnail stream data, if present.
    ///
    /// Corresponds to `FPDFPage_GetRawThumbnailData`.
    pub fn thumbnail_raw_bytes(&self) -> Result<Option<Vec<u8>>> {
        let store = &self.doc.inner.store;
        thumbnail_raw_or_decoded(store, self.page_dict_id, false)
    }

    /// ADR-019 T2 alias for [`thumbnail_raw_bytes()`](Self::thumbnail_raw_bytes).
    ///
    /// Corresponds to `FPDFPage_GetRawThumbnailData`.
    #[inline]
    pub fn page_get_raw_thumbnail_data(&self) -> Result<Option<Vec<u8>>> {
        self.thumbnail_raw_bytes()
    }

    /// Deprecated — use [`page_get_raw_thumbnail_data()`](Self::page_get_raw_thumbnail_data).
    ///
    /// Corresponds to `FPDFPage_GetRawThumbnailData`.
    #[deprecated(
        note = "use `page_get_raw_thumbnail_data()` — matches upstream `FPDFPage_GetRawThumbnailData`"
    )]
    #[inline]
    pub fn get_raw_thumbnail_data(&self) -> Result<Option<Vec<u8>>> {
        self.thumbnail_raw_bytes()
    }

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

    /// Returns a reference to the parent document.
    pub fn document(&self) -> &ArcDocument {
        &self.doc
    }
}

// Compile-time assertions: all Arc types must be Send + Sync.
#[allow(dead_code)]
const _: () = {
    fn assert_send<T: Send>() {}
    fn assert_sync<T: Sync>() {}
    fn assertions() {
        assert_send::<ArcLibrary>();
        assert_sync::<ArcLibrary>();
        assert_send::<ArcDocument>();
        assert_sync::<ArcDocument>();
        assert_send::<ArcPage>();
        assert_sync::<ArcPage>();
    }
};