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
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
#![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};

#[cfg(feature = "edit")]
pub mod edit;

mod image_decode;

use image_decode::{convert_to_rgba, get_dict_int, read_decode_array, resolve_image_color_space};

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

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::{Name, 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, ActionType, Annotation, AnnotationBorder, AnnotationFlags, AnnotationSubtypeData,
    AnnotationType, AttributeValue, Bookmark, BorderStyle, Destination, DocError, DocMdpPermission,
    DocResult, DocumentMetadata, DuplexMode, ElementsForPage, FdfData, FieldValue, FileSpec,
    FormFieldFlags, HitTestResult, InteractiveForm, JavaScriptAction, LinkObject, McidMapping,
    NameTree, NumberTree, PageFit, PageLabel, PageLabelStyle, PageMode, PageStructure, PdfFormType,
    ReadingDirection, SignatureObject, StructAttribute, StructElement, StructTree,
    ViewerPreferences, collect_attachments, collect_javascript_actions, collect_links,
    collect_named_destinations, collect_signatures, export_fdf, find_bookmark,
    find_link_at_position, format_label, import_fdf, is_tagged, link_at_point, link_enumerate,
    link_get_link_at_point, next_sibling_bookmark, page_mode, parse_annotations, parse_bookmarks,
    parse_destination, parse_metadata, parse_page_labels,
};
#[allow(deprecated)]
pub use rpdfium_doc::{enumerate, enumerate_links, get_bookmark_by_title, get_link_at_point};

// Re-exports from rpdfium-parser
pub use rpdfium_parser::PdfVersion;

// 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 and ColorScheme
pub use rpdfium_render::{ColorScheme, 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>;

// ---------------------------------------------------------------------------
// FileIdentifierType
// ---------------------------------------------------------------------------

/// Selects which of the two PDF file identifiers to retrieve.
///
/// The PDF trailer `/ID` array always contains exactly two identifiers:
/// - `Permanent` (index 0): assigned when the document is first created.
/// - `Changing` (index 1): updated each time the document is saved.
///
/// Corresponds to `FPDF_FILEIDTYPE` in PDFium (`fpdf_view.h`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(usize)]
pub enum FileIdentifierType {
    /// The permanent (original) document identifier — index 0 in the `/ID` array.
    Permanent = 0,
    /// The changing (revision) document identifier — index 1 in the `/ID` array.
    Changing = 1,
}

// ---------------------------------------------------------------------------
// 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()
    }
}

// ---------------------------------------------------------------------------
// PageActionType
// ---------------------------------------------------------------------------

/// Event type for page-level additional actions (`/AA` on a page dict).
///
/// PDF pages can have an `/AA` dictionary (ISO 32000-2 Table 197) with two
/// keys:
/// - `/O` — triggered when the page is opened.
/// - `/C` — triggered when the page is closed.
///
/// Corresponds to `FPDF_PAGE_AACTION_OPEN`/`FPDF_PAGE_AACTION_CLOSE` in
/// PDFium's `fpdf_doc.h`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PageActionType {
    /// Page opened (`/O`). Corresponds to `FPDF_PAGE_AACTION_OPEN = 0`.
    Open = 0,
    /// Page closed (`/C`). Corresponds to `FPDF_PAGE_AACTION_CLOSE = 1`.
    Close = 1,
}

impl PageActionType {
    /// Returns the PDF dictionary key string for this page action type.
    pub fn pdf_key(self) -> &'static str {
        match self {
            Self::Open => "O",
            Self::Close => "C",
        }
    }
}

// ---------------------------------------------------------------------------
// PdfReader trait (FPDF_LoadCustomDocument equivalent)
// ---------------------------------------------------------------------------

/// Custom PDF data source, equivalent to `FPDF_FILEACCESS`.
///
/// Implement this trait to load a PDF from any source (network stream,
/// encrypted container, memory-mapped file, etc.).  Pass the implementor to
/// [`Document::open_custom()`] or [`ArcDocument::open_custom()`].
///
/// Corresponds to `FPDF_FILEACCESS` in PDFium's `fpdf_view.h`.
///
/// # Contract
///
/// Implementations **must** satisfy the following:
///
/// - [`file_len()`](Self::file_len) returns the total number of bytes in the
///   source.  It must be stable for the lifetime of the reader.
/// - [`read_at()`](Self::read_at) reads up to `buf.len()` bytes starting at
///   byte position `offset` into `buf`.  The number of bytes actually read is
///   returned.  Returning fewer bytes than `buf.len()` is allowed (short
///   read); the caller will continue issuing further reads.
/// - When `offset >= file_len()`, [`read_at()`](Self::read_at) **must** return
///   `Ok(0)` (EOF) rather than panicking or returning an error.
/// - Implementations may be called from multiple threads concurrently; they
///   must be `Send + Sync`.
pub trait PdfReader: Send + Sync {
    /// Total size of the PDF data in bytes.
    ///
    /// Must be stable; called once before the first [`read_at()`](Self::read_at).
    fn file_len(&self) -> u64;

    /// Read bytes into `buf` starting at `offset`.
    ///
    /// Returns the number of bytes actually copied into `buf`.  Returns `Ok(0)`
    /// when `offset >= file_len()` (EOF).  Partial reads are allowed.
    fn read_at(&self, offset: u64, buf: &mut [u8]) -> std::io::Result<usize>;
}

// ---------------------------------------------------------------------------
// 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,
        })
    }

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

    /// 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)
    }

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

    /// Load a PDF document from a custom reader.
    ///
    /// Reads all data from `reader` into memory, then delegates to
    /// [`Document::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: &'lib Library,
        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: &'lib Library,
        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.page_ids.len() as u32
    }

    /// Upstream-aligned alias for [`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<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(),
        })
    }

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

    /// 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)
    }

    /// Search the document's bookmark tree for the first bookmark with the
    /// given title (case-sensitive, exact Unicode match).
    ///
    /// Returns `Ok(None)` if no matching bookmark is found.
    /// Corresponds to `FPDFBookmark_Find`.
    pub fn find_bookmark(&self, title: &str) -> Result<Option<Bookmark>> {
        let bookmarks = self.bookmarks()?;
        Ok(find_bookmark(&bookmarks, title).cloned())
    }

    /// Upstream-aligned alias for [`find_bookmark()`](Self::find_bookmark).
    ///
    /// Corresponds to `FPDFBookmark_Find`.
    #[inline]
    pub fn bookmark_find(&self, title: &str) -> Result<Option<Bookmark>> {
        self.find_bookmark(title)
    }

    /// Deprecated — use [`bookmark_find()`](Self::bookmark_find) instead.
    ///
    /// Corresponds to `FPDFBookmark_Find`.
    #[deprecated(note = "use `bookmark_find()` — matches upstream `FPDFBookmark_Find`")]
    #[inline]
    pub fn find(&self, title: &str) -> Result<Option<Bookmark>> {
        self.find_bookmark(title)
    }

    /// Legacy alias — use [`bookmark_find()`](Self::bookmark_find) instead.
    ///
    /// Corresponds to `FPDFBookmark_Find`.
    #[deprecated(note = "use `bookmark_find()` — matches upstream `FPDFBookmark_Find`")]
    #[inline]
    pub fn get_bookmark_by_title(&self, title: &str) -> Result<Option<Bookmark>> {
        self.find_bookmark(title)
    }

    /// Returns the next sibling of `bookmark` within `siblings`, or `None`
    /// if `bookmark` is the last sibling.
    ///
    /// **Architectural note**: PDFium's `FPDFBookmark_GetNextSibling` takes a
    /// document handle and a bookmark handle and follows the PDF `/Next` link
    /// in the raw outline dictionary.  In rpdfium the outline is eagerly
    /// parsed into an owned `Vec<Bookmark>` tree, so the caller must provide
    /// the parent's children slice (or the root slice for top-level siblings).
    ///
    /// Typical usage:
    /// ```ignore
    /// let bms = doc.bookmarks()?;
    /// let second = doc.next_sibling_bookmark(&bms, &bms[0]);
    /// ```
    ///
    /// Corresponds to `FPDFBookmark_GetNextSibling`.
    pub fn next_sibling_bookmark<'a>(
        &self,
        siblings: &'a [Bookmark],
        bookmark: &Bookmark,
    ) -> Option<&'a Bookmark> {
        next_sibling_bookmark(siblings, bookmark)
    }

    /// Upstream-aligned alias for [`next_sibling_bookmark()`](Self::next_sibling_bookmark).
    ///
    /// Corresponds to `FPDFBookmark_GetNextSibling`.
    #[inline]
    pub fn bookmark_get_next_sibling<'a>(
        &self,
        siblings: &'a [Bookmark],
        bookmark: &Bookmark,
    ) -> Option<&'a Bookmark> {
        self.next_sibling_bookmark(siblings, bookmark)
    }

    /// Non-upstream alias — use [`bookmark_get_next_sibling()`](Self::bookmark_get_next_sibling).
    #[deprecated(
        note = "use `bookmark_get_next_sibling()` — matches upstream `FPDFBookmark_GetNextSibling`"
    )]
    #[inline]
    pub fn get_next_sibling<'a>(
        &self,
        siblings: &'a [Bookmark],
        bookmark: &Bookmark,
    ) -> Option<&'a Bookmark> {
        self.next_sibling_bookmark(siblings, bookmark)
    }

    /// 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 the total number of digital signature fields in the document.
    ///
    /// Corresponds to `FPDF_GetSignatureCount`.
    pub fn signature_count(&self) -> Result<usize> {
        Ok(self.signatures()?.len())
    }

    /// ADR-019 alias for [`signature_count()`](Self::signature_count).
    ///
    /// Corresponds to `FPDF_GetSignatureCount`.
    #[inline]
    pub fn get_signature_count(&self) -> Result<usize> {
        self.signature_count()
    }

    /// Returns the Nth digital signature field (zero-based index).
    ///
    /// Returns `Ok(None)` if `index` is out of range.
    /// Corresponds to `FPDF_GetSignatureObject`.
    pub fn signature_object(&self, index: usize) -> Result<Option<SignatureObject>> {
        let sigs = self.signatures()?;
        Ok(sigs.into_iter().nth(index))
    }

    /// ADR-019 alias for [`signature_object()`](Self::signature_object).
    ///
    /// Corresponds to `FPDF_GetSignatureObject`.
    #[inline]
    pub fn get_signature_object(&self, index: usize) -> Result<Option<SignatureObject>> {
        self.signature_object(index)
    }

    /// Returns one of the file identifier bytes from the PDF trailer `/ID` array.
    ///
    /// PDFs contain a two-element `/ID` array in the trailer dictionary:
    /// - Index 0 (`FileIdentifierType::Permanent`): set when the document is created and
    ///   never changes, even through edits.
    /// - Index 1 (`FileIdentifierType::Changing`): updated each time the document is modified.
    ///
    /// Returns `None` if the document has no `/ID` entry in its trailer.
    /// Corresponds to `FPDF_GetFileIdentifier`.
    pub fn file_identifier(&self, id_type: FileIdentifierType) -> Option<Vec<u8>> {
        self.store
            .trailer()
            .id
            .as_ref()
            .map(|ids| ids[id_type as usize].clone())
    }

    /// ADR-019 alias — see [`Self::file_identifier`].
    #[inline]
    pub fn get_file_identifier(&self, id_type: FileIdentifierType) -> Option<Vec<u8>> {
        self.file_identifier(id_type)
    }

    /// Returns the effective PDF version for this document.
    ///
    /// Per ISO 32000-1 §7.7.2, the document catalog's `/Version` entry overrides
    /// the file header version when present. Returns `(major, minor)`.
    ///
    /// Returns the PDF version as `(major, minor)` — e.g. `(1, 7)` for PDF 1.7.
    /// Corresponds to `FPDF_GetFileVersion`.
    pub fn pdf_version(&self) -> (u8, u8) {
        let header = self.store.file_version();
        let header_pair = (header.major, header.minor);

        // Check catalog /Version override per ISO 32000-1 Table 28
        let catalog_id = self.store.trailer().root;
        let override_ver = (|| -> Option<(u8, u8)> {
            let catalog_obj = self.store.resolve(catalog_id).ok()?;
            let dict = catalog_obj.as_dict()?;
            let ver_val = dict.get(&Name::from_bytes(b"Version".to_vec()))?;
            let resolved = self.store.deep_resolve(ver_val).ok()?;
            let ver_name = resolved.as_name()?;
            let b = ver_name.as_bytes();
            // Must be exactly "M.m" format (e.g. "1.7")
            if b.len() == 3 && b[1] == b'.' && b[0].is_ascii_digit() && b[2].is_ascii_digit() {
                Some((b[0] - b'0', b[2] - b'0'))
            } else {
                None
            }
        })();

        override_ver.unwrap_or(header_pair)
    }

    /// Upstream-aligned alias for [`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.store
            .security_handler()
            .map(|h| h.permissions().bits() as u32)
    }

    /// 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()
    }

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

    /// Upstream-aligned alias for [`Self::permissions()`].
    ///
    /// Corresponds to `FPDF_GetDocUserPermissions`.
    #[inline]
    pub fn get_doc_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.store.security_handler().map(|h| h.revision())
    }

    /// Upstream-aligned alias for [`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.  Corresponds to the `FPDF_VIEWERREF_*` family.
    pub fn viewer_preferences(&self) -> Result<Option<ViewerPreferences>> {
        let catalog = self.store.resolve(self.catalog_id)?;
        let catalog_dict = catalog
            .as_dict()
            .ok_or(PdfError::UnknownObject(self.catalog_id))?;
        let vp_obj = match catalog_dict
            .get(&Name::viewer_preferences())
            .and_then(|o| self.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, &self.store)))
    }

    /// Returns whether print scaling is enabled for this document.
    ///
    /// Returns `true` (scaling enabled) when `/PrintScaling` is absent or not
    /// `"None"`; returns `false` when scaling is suppressed.
    ///
    /// Corresponds to `FPDF_VIEWERREF_GetPrintScaling`.
    pub fn viewerref_get_print_scaling(&self) -> Result<bool> {
        Ok(self
            .viewer_preferences()?
            .map(|vp| vp.print_scaling())
            .unwrap_or(true))
    }

    /// Returns the number of copies to print as specified in viewer preferences.
    ///
    /// Returns `1` if no `/NumCopies` entry is present.
    ///
    /// Corresponds to `FPDF_VIEWERREF_GetNumCopies`.
    pub fn viewerref_get_num_copies(&self) -> Result<i32> {
        Ok(self
            .viewer_preferences()?
            .and_then(|vp| vp.num_copies())
            .map(|n| n as i32)
            .unwrap_or(1))
    }

    /// Returns the print page range from viewer preferences, if any.
    ///
    /// Corresponds to `FPDF_VIEWERREF_GetPrintPageRange`.
    pub fn viewerref_get_print_page_range(&self) -> Result<Option<Vec<i64>>> {
        Ok(self
            .viewer_preferences()?
            .and_then(|vp| vp.print_page_range().map(|r| r.to_vec())))
    }

    /// Returns the number of elements in a print page range slice.
    ///
    /// Corresponds to `FPDF_VIEWERREF_GetPrintPageRangeCount`.
    pub fn viewerref_get_print_page_range_count(&self, range: &[i64]) -> usize {
        range.len()
    }

    /// Returns the element at `index` within a print page range slice.
    ///
    /// Corresponds to `FPDF_VIEWERREF_GetPrintPageRangeElement`.
    pub fn viewerref_get_print_page_range_element(
        &self,
        range: &[i64],
        index: usize,
    ) -> Option<i64> {
        range.get(index).copied()
    }

    /// Returns the duplex printing mode from viewer preferences.
    ///
    /// Returns `DuplexMode::Simplex` if no `/Duplex` entry is present.
    ///
    /// Corresponds to `FPDF_VIEWERREF_GetDuplex`.
    pub fn viewerref_get_duplex(&self) -> Result<DuplexMode> {
        Ok(self
            .viewer_preferences()?
            .map(|vp| vp.duplex_mode())
            .unwrap_or(DuplexMode::Simplex))
    }

    /// Returns the value of a named viewer preference entry.
    ///
    /// Looks up `key` in the `/ViewerPreferences` dictionary and returns the
    /// value as a string. Returns `None` if absent or not a string/name.
    ///
    /// Corresponds to `FPDF_VIEWERREF_GetName`.
    pub fn viewerref_get_name(&self, key: &str) -> Result<Option<String>> {
        Ok(self
            .viewer_preferences()?
            .and_then(|vp| vp.generic_name(key).map(|s| s.to_owned())))
    }

    /// Collect all embedded file attachments from `/Root/Names/EmbeddedFiles`.
    ///
    /// Returns an empty `Vec` if the document has no attachments.
    /// Corresponds to `FPDFDoc_GetAttachmentCount` / `FPDFDoc_GetAttachment`.
    pub fn attachments(&self) -> Result<Vec<FileSpec>> {
        let catalog = self.store.resolve(self.catalog_id)?;
        Ok(collect_attachments(catalog, &self.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()
    }

    #[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)
    }

    #[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)
    }

    /// Collect all named destinations from the document catalog.
    ///
    /// Returns a `Vec` of `(name, Destination)` pairs from the `/Names/Dests`
    /// name tree, or from the old-style `/Dests` dictionary.
    /// Corresponds to `FPDF_CountNamedDests` / `FPDF_GetNamedDest`.
    pub fn named_destinations(&self) -> Result<Vec<(String, Destination)>> {
        let catalog = self.store.resolve(self.catalog_id)?;
        Ok(collect_named_destinations(catalog, &self.store)?)
    }

    /// Look up a named destination by name.
    ///
    /// Searches the document's named-destination table (`/Names/Dests` or the
    /// old-style `/Dests` dictionary) for an entry whose key matches `name`
    /// exactly (case-sensitive).
    ///
    /// Returns `Ok(Some(dest))` if found, `Ok(None)` if no such name exists.
    ///
    /// Corresponds to `FPDF_GetNamedDestByName`.
    pub fn named_dest_by_name(&self, name: &str) -> Result<Option<Destination>> {
        let catalog = self.store.resolve(self.catalog_id)?;
        let dests = collect_named_destinations(catalog, &self.store)?;
        Ok(dests.into_iter().find(|(n, _)| n == name).map(|(_, d)| d))
    }

    /// Upstream-aligned alias for [`Self::named_dest_by_name()`].
    ///
    /// Corresponds to `FPDF_GetNamedDestByName`.
    #[inline]
    pub fn get_named_dest_by_name(&self, name: &str) -> Result<Option<Destination>> {
        self.named_dest_by_name(name)
    }

    /// Returns the total number of named destinations in the document.
    ///
    /// Counts entries in `/Names/Dests` (name tree) or the legacy `/Dests`
    /// dictionary in the document catalog.
    ///
    /// Corresponds to `FPDF_CountNamedDests`.
    pub fn named_dest_count(&self) -> Result<u32> {
        let dests = self.named_destinations()?;
        Ok(dests.len() as u32)
    }

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

    /// Returns the named destination at the given 0-based index.
    ///
    /// Returns the `(name, Destination)` pair at `index` in the collection
    /// returned by [`named_destinations()`](Self::named_destinations), or
    /// `Ok(None)` if the index is out of range.
    ///
    /// Corresponds to `FPDF_GetNamedDest`.
    pub fn named_dest_at(&self, index: usize) -> Result<Option<(String, Destination)>> {
        let dests = self.named_destinations()?;
        Ok(dests.into_iter().nth(index))
    }

    /// ADR-019 alias for [`named_dest_at()`](Self::named_dest_at).
    ///
    /// Corresponds to `FPDF_GetNamedDest`.
    #[inline]
    pub fn get_named_dest(&self, index: usize) -> Result<Option<(String, Destination)>> {
        self.named_dest_at(index)
    }

    /// Returns a specific metadata tag value from the document's `/Info`
    /// dictionary.
    ///
    /// `tag` is one of: `"Title"`, `"Author"`, `"Subject"`, `"Keywords"`,
    /// `"Creator"`, `"Producer"`, `"CreationDate"`, `"ModDate"`.
    ///
    /// Returns `Ok(None)` if the tag is not present in the document or if
    /// the document has no `/Info` dictionary.
    ///
    /// Corresponds to `FPDF_GetMetaText`.
    pub fn meta_text(&self, tag: &str) -> Result<Option<String>> {
        let meta = match self.metadata()? {
            Some(m) => m,
            None => return Ok(None),
        };
        let value = match tag {
            "Title" => meta.title,
            "Author" => meta.author,
            "Subject" => meta.subject,
            "Keywords" => meta.keywords,
            "Creator" => meta.creator,
            "Producer" => meta.producer,
            "CreationDate" => meta.creation_date,
            "ModDate" => meta.mod_date,
            _ => None,
        };
        Ok(value)
    }

    /// ADR-019 alias for [`meta_text()`](Self::meta_text).
    ///
    /// Corresponds to `FPDF_GetMetaText`.
    #[inline]
    pub fn get_meta_text(&self, tag: &str) -> Result<Option<String>> {
        self.meta_text(tag)
    }

    /// Returns the formatted page label for the given 0-based page index.
    ///
    /// The label is computed by resolving the page label ranges from the
    /// document's `/PageLabels` number tree, then formatting the label for
    /// the specific page using [`format_label`].
    ///
    /// Returns `Ok(None)` if the document has no page labels or the page
    /// index is out of range.
    ///
    /// Corresponds to `FPDF_GetPageLabel`.
    pub fn page_label(&self, page_index: u32) -> Result<Option<String>> {
        let catalog = self.store.resolve(self.catalog_id)?;
        let labels = parse_page_labels(catalog, &self.store)?;
        if labels.is_empty() {
            return Ok(None);
        }
        let idx = page_index as i64;
        // Find the last label range whose start is <= page_index.
        let range_entry = labels.iter().rfind(|(start, _)| *start <= idx);
        match range_entry {
            Some((range_start, label)) => {
                let offset = idx - range_start;
                Ok(Some(format_label(label, offset)))
            }
            None => Ok(None),
        }
    }

    /// ADR-019 alias for [`page_label()`](Self::page_label).
    ///
    /// Corresponds to `FPDF_GetPageLabel`.
    #[inline]
    pub fn get_page_label(&self, page_index: u32) -> Result<Option<String>> {
        self.page_label(page_index)
    }

    /// Parse the tagged PDF structure tree from the document catalog.
    ///
    /// Returns `Ok(None)` if the document has no `/StructTreeRoot` entry (i.e.,
    /// it is not a tagged PDF document).
    ///
    /// Corresponds to `FPDF_StructTree_GetForPage` in concept — the full document
    /// structure tree is returned rather than just a page-filtered view.
    /// Use [`StructTree::elements_for_page`] or [`PageStructure::for_page`] to
    /// filter the tree to a specific page.
    pub fn structure_tree(&self) -> Result<Option<StructTree>> {
        let catalog = self.store.resolve(self.catalog_id)?;
        let catalog_dict = catalog
            .as_dict()
            .ok_or(PdfError::UnknownObject(self.catalog_id))?;
        Ok(StructTree::from_catalog(catalog_dict, &self.store)?)
    }

    /// ADR-019 T2 alias for [`structure_tree()`](Self::structure_tree).
    ///
    /// Exact snake_case of `FPDF_StructTree_GetForPage` (strip `FPDF_` prefix).
    /// Note: rpdfium returns the full document tree rather than a page-filtered
    /// view, because the parser has no page-level filtering at this layer.
    #[inline]
    pub fn struct_tree_get_for_page(&self) -> Result<Option<StructTree>> {
        self.structure_tree()
    }

    /// Deprecated non-upstream alias — use
    /// [`struct_tree_get_for_page()`](Self::struct_tree_get_for_page) instead.
    ///
    /// `get_for_page` strips too much of the upstream name `FPDF_StructTree_GetForPage`.
    /// The correct T2 alias is [`struct_tree_get_for_page()`](Self::struct_tree_get_for_page).
    #[deprecated(
        note = "use `struct_tree_get_for_page()` — exact T2 alias for FPDF_StructTree_GetForPage"
    )]
    #[inline]
    pub fn get_for_page(&self) -> Result<Option<StructTree>> {
        self.structure_tree()
    }

    /// Deprecated non-upstream alias — use
    /// [`struct_tree_get_for_page()`](Self::struct_tree_get_for_page) instead.
    ///
    /// Corresponds to `FPDF_StructTree_GetForPage`.
    #[deprecated(
        note = "use `struct_tree_get_for_page()` — exact T2 alias for FPDF_StructTree_GetForPage"
    )]
    #[inline]
    pub fn get_structure_tree(&self) -> Result<Option<StructTree>> {
        self.structure_tree()
    }

    /// Returns `true` if the document is a tagged PDF.
    ///
    /// Checks the `/MarkInfo/Marked` boolean in the document catalog.
    /// Returns `false` if the document has no `/MarkInfo` entry or if
    /// `/Marked` is absent or `false`.
    ///
    /// Corresponds to `FPDFCatalog_IsTagged`.
    pub fn is_tagged(&self) -> Result<bool> {
        let catalog = self.store.resolve(self.catalog_id)?;
        Ok(is_tagged(catalog, &self.store))
    }

    /// Upstream-aligned alias for [`is_tagged()`](Self::is_tagged).
    ///
    /// Corresponds to `FPDFCatalog_IsTagged`.
    #[inline]
    pub fn catalog_is_tagged(&self) -> Result<bool> {
        self.is_tagged()
    }

    /// Returns the document's initial page display mode.
    ///
    /// Reads `/PageMode` from the document catalog.
    /// Returns [`PageMode::Unknown`] if the entry is absent or unrecognised.
    ///
    /// Corresponds to `FPDFDoc_GetPageMode`.
    pub fn page_mode(&self) -> Result<PageMode> {
        let catalog = self.store.resolve(self.catalog_id)?;
        Ok(page_mode(catalog, &self.store))
    }

    /// Upstream-aligned alias for [`page_mode()`](Self::page_mode).
    ///
    /// Corresponds to `FPDFDoc_GetPageMode`.
    #[inline]
    pub fn doc_get_page_mode(&self) -> Result<PageMode> {
        self.page_mode()
    }

    /// Deprecated: use [`doc_get_page_mode()`](Self::doc_get_page_mode) — matches upstream `FPDFDoc_GetPageMode`.
    #[deprecated(note = "use `doc_get_page_mode()` — matches upstream `FPDFDoc_GetPageMode`")]
    #[inline]
    pub fn get_page_mode(&self) -> Result<PageMode> {
        self.page_mode()
    }

    /// Returns the type of interactive form contained in the document.
    ///
    /// Inspects `/Root/AcroForm` and the nested `/XFA` key as well as the
    /// catalog's `/NeedsRendering` boolean to distinguish between no form,
    /// AcroForm, XFA-full, and XFA-foreground form types.
    ///
    /// Returns [`PdfFormType::None`] if there is no form or the catalog
    /// cannot be resolved.
    ///
    /// Corresponds to `FPDF_GetFormType` in PDFium's `fpdf_formfill.h`
    /// (implemented in `fpdfsdk/fpdf_view.cpp`).
    pub fn form_type(&self) -> Result<PdfFormType> {
        let catalog = self.store.resolve(self.catalog_id)?;
        Ok(rpdfium_doc::pdf_form_type(catalog, &self.store))
    }

    /// ADR-019 alias for [`form_type()`](Self::form_type).
    ///
    /// Corresponds to `FPDF_GetFormType`.
    #[inline]
    pub fn get_form_type(&self) -> Result<PdfFormType> {
        self.form_type()
    }

    /// Attempt to load XFA form data for the document.
    ///
    /// # Not Supported
    ///
    /// rpdfium does not implement the XFA runtime environment. XFA form
    /// rendering and execution require a full XFA processor which is out of
    /// scope for this library (ADR-017 stub).
    ///
    /// Always returns `Err(NotSupported(...))`. Use [`Self::form_type()`] to
    /// detect whether the document contains XFA forms.
    ///
    /// Corresponds to `FPDF_LoadXFA` in PDFium's `fpdf_formfill.h`.
    pub fn load_xfa(&self) -> Result<()> {
        Err(Error::Doc(DocError::NotSupported(
            "load_xfa: XFA form processing is not implemented in rpdfium".into(),
        )))
    }

    /// Get a page-level additional action from the page's `/AA` dictionary.
    ///
    /// PDF page dictionaries can contain an `/AA` entry (ISO 32000-2 Table 197)
    /// with optional `/O` (open) and `/C` (close) action entries.
    ///
    /// Returns `Ok(None)` if:
    /// - `page_index` is out of range,
    /// - the page has no `/AA` dictionary,
    /// - the requested action key is absent in the `/AA` dict.
    ///
    /// Corresponds to `FPDF_GetPageAAction` in PDFium.
    pub fn page_additional_action(
        &self,
        page_index: usize,
        action_type: PageActionType,
    ) -> Result<Option<Action>> {
        if page_index >= self.page_ids.len() {
            return Ok(None);
        }
        let page_dict_id = self.page_ids[page_index];
        let page_obj = self.store.resolve(page_dict_id)?;
        let page_dict = match page_obj.as_dict() {
            Some(d) => d,
            None => return Ok(None),
        };

        // Look for /AA in the page dict
        let aa_obj = match page_dict.get(&Name::aa()) {
            Some(obj) => obj,
            None => return Ok(None),
        };

        // Resolve /AA to a dict
        let aa_resolved = match self.store.deep_resolve(aa_obj) {
            Ok(obj) => obj,
            Err(_) => return Ok(None),
        };
        let aa_dict = match aa_resolved.as_dict() {
            Some(d) => d,
            None => return Ok(None),
        };

        // Look for the specific action key (/O or /C)
        let key = Name::from(action_type.pdf_key());
        let action_obj = match aa_dict.get(&key) {
            Some(obj) => obj,
            None => return Ok(None),
        };

        // Parse the action
        match rpdfium_doc::action::parse_action(action_obj, &self.store) {
            Ok(action) => Ok(Some(action)),
            Err(_) => Ok(None),
        }
    }

    /// Upstream-aligned alias for [`page_additional_action()`](Self::page_additional_action).
    ///
    /// Corresponds to `FPDF_GetPageAAction`.
    #[inline]
    pub fn get_page_a_action(
        &self,
        page_index: usize,
        action_type: PageActionType,
    ) -> Result<Option<Action>> {
        self.page_additional_action(page_index, action_type)
    }

    /// Legacy alias — use [`get_page_a_action()`](Self::get_page_a_action) instead.
    ///
    /// Corresponds to `FPDF_GetPageAAction`.
    #[deprecated(note = "Use `get_page_a_action()` (strict upstream name)")]
    #[inline]
    pub fn get_page_additional_action(
        &self,
        page_index: usize,
        action_type: PageActionType,
    ) -> Result<Option<Action>> {
        self.page_additional_action(page_index, action_type)
    }

    /// Returns the z-order (painting order) of the link annotation closest to
    /// the given point on the specified page.
    ///
    /// # Not Supported
    ///
    /// rpdfium does not track per-annotation painting order (z-order). This
    /// stub is provided for API completeness per ADR-017.
    ///
    /// Corresponds to `FPDFLink_GetLinkZOrderAtPoint()` in PDFium's
    /// `fpdf_doc.h`.
    pub fn link_z_order_at_point(&self, _page_index: usize, _x: f64, _y: f64) -> Result<i32> {
        Err(Error::Doc(DocError::NotSupported(
            "link_z_order_at_point: annotation z-order tracking is not implemented".into(),
        )))
    }

    /// ADR-019 Tier 2 alias for [`link_z_order_at_point()`](Self::link_z_order_at_point).
    ///
    /// Corresponds to `FPDFLink_GetLinkZOrderAtPoint`.
    #[inline]
    pub fn link_get_link_z_order_at_point(&self, page_index: usize, x: f64, y: f64) -> Result<i32> {
        self.link_z_order_at_point(page_index, x, y)
    }

    /// Use [`link_get_link_z_order_at_point()`](Self::link_get_link_z_order_at_point) — matches
    /// upstream `FPDFLink_GetLinkZOrderAtPoint`.
    #[deprecated(
        note = "use `link_get_link_z_order_at_point()` — matches upstream `FPDFLink_GetLinkZOrderAtPoint`"
    )]
    #[inline]
    pub fn get_link_z_order_at_point(&self, page_index: usize, x: f64, y: f64) -> Result<i32> {
        self.link_z_order_at_point(page_index, x, y)
    }

    /// Returns true if the cross-reference table was rebuilt during parsing (Lenient mode).
    ///
    /// Non-upstream convenience accessor — prefer
    /// [`has_valid_cross_reference_table()`](Self::has_valid_cross_reference_table) which
    /// corresponds to the public `FPDF_DocumentHasValidCrossReferenceTable` API.
    #[deprecated(
        note = "use `has_valid_cross_reference_table()` — matches upstream FPDF_DocumentHasValidCrossReferenceTable"
    )]
    #[inline]
    pub fn xref_rebuilt(&self) -> bool {
        self.store.xref_table_rebuilt()
    }

    /// Returns `true` if the document's cross-reference table was intact when loaded.
    /// Returns `false` if the parser had to rebuild (repair) the xref table due to corruption.
    ///
    /// Corresponds to `FPDF_DocumentHasValidCrossReferenceTable`.
    pub fn has_valid_cross_reference_table(&self) -> bool {
        !self.store.xref_table_rebuilt()
    }

    /// Upstream-aligned alias for [`Self::has_valid_cross_reference_table()`].
    ///
    /// Corresponds to `FPDF_DocumentHasValidCrossReferenceTable`.
    #[inline]
    pub fn document_has_valid_cross_reference_table(&self) -> bool {
        self.has_valid_cross_reference_table()
    }

    /// Returns the byte offsets of all `%%EOF` / trailer section ends in the PDF.
    ///
    /// Corresponds to `FPDF_GetTrailerEnds`. Returns an empty vec if the positions
    /// cannot be determined from in-memory data.
    ///
    /// # Not Supported
    ///
    /// Full trailer-end tracking requires recording positions during parse and is
    /// not currently implemented (ADR: implementation complexity vs. use case).
    pub fn trailer_ends(&self) -> Vec<u64> {
        Vec::new()
    }

    /// Upstream-aligned alias for [`Self::trailer_ends()`].
    ///
    /// Corresponds to `FPDF_GetTrailerEnds`.
    #[inline]
    pub fn get_trailer_ends(&self) -> Vec<u64> {
        self.trailer_ends()
    }

    /// Returns the page dimensions at the given zero-based page index.
    ///
    /// Corresponds to `FPDF_GetPageSizeByIndexF`.
    pub fn page_size_by_index_f(&self, index: u32) -> Result<(f32, f32)> {
        let page = self.page(index)?;
        let mb = page.media_box();
        Ok((mb.width() as f32, mb.height() as f32))
    }

    /// Upstream-aligned alias for [`page_size_by_index_f()`](Self::page_size_by_index_f).
    ///
    /// Corresponds to `FPDF_GetPageSizeByIndexF`.
    #[inline]
    pub fn get_page_size_by_index_f(&self, index: u32) -> Result<(f32, f32)> {
        self.page_size_by_index_f(index)
    }

    // -----------------------------------------------------------------------
    // Catalog language (FPDFCatalog_GetLanguage)
    // -----------------------------------------------------------------------

    /// Returns the document's language tag from the catalog `/Lang` entry.
    ///
    /// Returns `Ok(None)` when the catalog has no `/Lang` entry.
    ///
    /// Corresponds to `FPDFCatalog_GetLanguage`.
    pub fn catalog_language(&self) -> Result<Option<String>> {
        let catalog = self.store.resolve(self.catalog_id)?;
        let dict = match catalog.as_dict() {
            Some(d) => d,
            None => return Ok(None),
        };
        let lang = match dict.get(&Name::lang()) {
            Some(o) => o,
            None => return Ok(None),
        };
        let resolved = self
            .store
            .deep_resolve(lang)
            .map_err(|e| Error::Doc(DocError::NotSupported(e.to_string())))?;
        if let Some(s) = resolved.as_string() {
            return Ok(Some(s.to_string_lossy()));
        }
        Ok(None)
    }

    /// Upstream-aligned alias for [`catalog_language()`](Self::catalog_language).
    ///
    /// Corresponds to `FPDFCatalog_GetLanguage`.
    #[inline]
    pub fn catalog_get_language(&self) -> Result<Option<String>> {
        self.catalog_language()
    }

    // -----------------------------------------------------------------------
    // Page size by index (FPDF_GetPageSizeByIndex)
    // -----------------------------------------------------------------------

    /// Returns the page dimensions (width, height) at the given zero-based page
    /// index as `f64` values.
    ///
    /// Corresponds to `FPDF_GetPageSizeByIndex` (the `double`-returning variant).
    /// For the `float` variant see [`page_size_by_index_f()`](Self::page_size_by_index_f).
    pub fn page_size_by_index(&self, index: u32) -> Result<(f64, f64)> {
        let (w, h) = self.page_size_by_index_f(index)?;
        Ok((f64::from(w), f64::from(h)))
    }

    /// Upstream-aligned alias for [`page_size_by_index()`](Self::page_size_by_index).
    ///
    /// Corresponds to `FPDF_GetPageSizeByIndex`.
    #[inline]
    pub fn get_page_size_by_index(&self, index: u32) -> Result<(f64, f64)> {
        self.page_size_by_index(index)
    }

    // -----------------------------------------------------------------------
    // Document-level JavaScript actions (fpdf_javascript.h)
    // -----------------------------------------------------------------------

    /// Returns all document-level JavaScript actions from the `/Names/JavaScript`
    /// name tree.
    ///
    /// Returns an empty `Vec` when the document has no JavaScript name tree.
    ///
    /// Corresponds to `FPDFDoc_GetJavaScriptActionCount` +
    /// `FPDFDoc_GetJavaScriptAction` from `fpdf_javascript.h`.
    pub fn javascript_actions(&self) -> Result<Vec<JavaScriptAction>> {
        let catalog = self.store.resolve(self.catalog_id)?;
        collect_javascript_actions(catalog, &self.store).map_err(Error::Doc)
    }

    /// Returns the number of document-level JavaScript actions.
    ///
    /// Corresponds to `FPDFDoc_GetJavaScriptActionCount`.
    pub fn javascript_action_count(&self) -> Result<usize> {
        Ok(self.javascript_actions()?.len())
    }

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

    /// Returns the JavaScript action at the given index, or `None` if out of range.
    ///
    /// Corresponds to `FPDFDoc_GetJavaScriptAction`.
    pub fn javascript_action_at(&self, index: usize) -> Result<Option<JavaScriptAction>> {
        let mut actions = self.javascript_actions()?;
        if index < actions.len() {
            Ok(Some(actions.swap_remove(index)))
        } else {
            Ok(None)
        }
    }

    /// Upstream-aligned alias for [`javascript_action_at()`](Self::javascript_action_at).
    ///
    /// Corresponds to `FPDFDoc_GetJavaScriptAction`.
    #[inline]
    pub fn doc_get_javascript_action(&self, index: usize) -> Result<Option<JavaScriptAction>> {
        self.javascript_action_at(index)
    }

    /// 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).
    ///
    /// Corresponds to `FPDFPage_GetMediaBox`.
    pub fn media_box(&self) -> Rect {
        self.media_box
    }

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

    #[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 [`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 [`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 [`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 [`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.
    ///
    /// Defaults to the media box per the PDF spec if not present, but this
    /// method returns `None` when the key is absent.
    /// Corresponds to `FPDFPage_GetCropBox`.
    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))
    }

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

    #[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 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::bleed_box(), self.store))
    }

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

    #[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 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::trim_box(), self.store))
    }

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

    #[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 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::art_box(), self.store))
    }

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

    #[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 [`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 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)
    }

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

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

    /// Non-upstream alias — use [`page_get_rotation()`](Self::page_get_rotation) instead.
    ///
    /// 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 — 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.
    ///
    /// Corresponds to `FPDF_RenderPageBitmap`.
    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)
    }

    /// 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.
    ///
    /// `matrix` maps PDF user-space coordinates to device pixel coordinates,
    /// bypassing the `media_box`/`rotation` calculation in `RenderConfig`.
    /// `clip` is an optional device-space clip rectangle (pixels outside it are
    /// replaced with the background colour).  `width` and `height` define the
    /// output bitmap dimensions.
    ///
    /// 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 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 number of annotations on this page.
    ///
    /// Corresponds to `FPDFPage_GetAnnotCount`.
    pub fn annotation_count(&self) -> Result<usize> {
        Ok(self.annotations()?.len())
    }

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

    /// Deprecated: use [`page_get_annot_count()`](Self::page_get_annot_count) — matches upstream `FPDFPage_GetAnnotCount`.
    #[deprecated(note = "use `page_get_annot_count()` — matches upstream `FPDFPage_GetAnnotCount`")]
    #[inline]
    pub fn get_annot_count(&self) -> Result<usize> {
        self.annotation_count()
    }

    /// Returns the annotation at `index` on this page, or `None` if out of range.
    ///
    /// Corresponds to `FPDFPage_GetAnnot`.
    pub fn annotation_at(&self, index: usize) -> Result<Option<Annotation>> {
        Ok(self.annotations()?.into_iter().nth(index))
    }

    /// Upstream-aligned alias for [`annotation_at()`](Self::annotation_at).
    ///
    /// Corresponds to `FPDFPage_GetAnnot`.
    #[inline]
    pub fn page_get_annot(&self, index: usize) -> Result<Option<Annotation>> {
        self.annotation_at(index)
    }

    /// Deprecated: use [`page_get_annot()`](Self::page_get_annot) — matches upstream `FPDFPage_GetAnnot`.
    #[deprecated(note = "use `page_get_annot()` — matches upstream `FPDFPage_GetAnnot`")]
    #[inline]
    pub fn get_annot(&self, index: usize) -> Result<Option<Annotation>> {
        self.annotation_at(index)
    }

    /// Returns the index of `annot` within this page's annotation list, or `None`.
    ///
    /// Corresponds to `FPDFPage_GetAnnotIndex`.
    pub fn annotation_index(&self, annot: &Annotation) -> Result<Option<usize>> {
        Ok(self
            .annotations()?
            .iter()
            .position(|a| std::ptr::eq(a as *const Annotation, annot as *const Annotation)))
    }

    /// Upstream-aligned alias for [`annotation_index()`](Self::annotation_index).
    ///
    /// Corresponds to `FPDFPage_GetAnnotIndex`.
    #[inline]
    pub fn page_get_annot_index(&self, annot: &Annotation) -> Result<Option<usize>> {
        self.annotation_index(annot)
    }

    /// Deprecated: use [`page_get_annot_index()`](Self::page_get_annot_index) — matches upstream `FPDFPage_GetAnnotIndex`.
    #[deprecated(note = "use `page_get_annot_index()` — matches upstream `FPDFPage_GetAnnotIndex`")]
    #[inline]
    pub fn get_annot_index(&self, annot: &Annotation) -> Result<Option<usize>> {
        self.annotation_index(annot)
    }

    /// Returns the page's embedded thumbnail image, if present.
    ///
    /// PDF pages may contain a `/Thumb` entry pointing to an image XObject
    /// that serves as a thumbnail preview. This method decodes that stream
    /// and returns it as an RGBA32 `Bitmap`.
    ///
    /// Returns `Ok(None)` if the page has no thumbnail.
    ///
    /// Corresponds to `FPDFPage_GetThumbnailAsBitmap`.
    pub fn thumbnail(&self) -> Result<Option<Bitmap>> {
        decode_page_thumbnail(self.store, self.page_dict_id)
    }

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

    /// Non-upstream alias — 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.
    ///
    /// The returned bytes are the raw pixel data after applying the stream's
    /// filter chain (e.g. FlateDecode). Returns `Ok(None)` if the page has
    /// no `/Thumb` entry.
    ///
    /// Corresponds to `FPDFPage_GetDecodedThumbnailData`.
    pub fn thumbnail_decoded_bytes(&self) -> Result<Option<Vec<u8>>> {
        thumbnail_raw_or_decoded(self.store, self.page_dict_id, true)
    }

    /// Upstream-aligned 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()
    }

    /// Non-upstream alias — 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.
    ///
    /// The returned bytes are the stream data as stored in the PDF, before
    /// any filter decoding. Returns `Ok(None)` if the page has no `/Thumb`
    /// entry.
    ///
    /// Corresponds to `FPDFPage_GetRawThumbnailData`.
    pub fn thumbnail_raw_bytes(&self) -> Result<Option<Vec<u8>>> {
        thumbnail_raw_or_decoded(self.store, self.page_dict_id, false)
    }

    /// Upstream-aligned 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()
    }

    /// Non-upstream alias — 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
    }
}

// ---------------------------------------------------------------------------
// 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()),
    }
}

// ---------------------------------------------------------------------------
// Coordinate conversion (FPDF_PageToDevice / FPDF_DeviceToPage equivalents)
// ---------------------------------------------------------------------------

/// Convert PDF page coordinates to device (pixel) coordinates.
///
/// `page_width` and `page_height` are the render target dimensions in pixels.
/// `rotate` is the page rotation in degrees (0, 90, 180, or 270).
///
/// Corresponds to `FPDF_PageToDevice`.
pub fn page_to_device(
    page: &Page<'_>,
    page_width: u32,
    page_height: u32,
    rotate: u32,
    page_x: f64,
    page_y: f64,
) -> (i32, i32) {
    let matrix = compute_page_transform(&page.media_box(), page_width, page_height, rotate);
    let pt = matrix.transform_point(Point {
        x: page_x,
        y: page_y,
    });
    (pt.x.round() as i32, pt.y.round() as i32)
}

/// Convert device (pixel) coordinates to PDF page coordinates.
///
/// `page_width` and `page_height` are the render target dimensions in pixels.
/// `rotate` is the page rotation in degrees (0, 90, 180, or 270).
///
/// Corresponds to `FPDF_DeviceToPage`.
pub fn device_to_page(
    page: &Page<'_>,
    page_width: u32,
    page_height: u32,
    rotate: u32,
    device_x: i32,
    device_y: i32,
) -> (f64, f64) {
    let matrix = compute_page_transform(&page.media_box(), page_width, page_height, rotate);
    match matrix.inverse() {
        Some(inv) => {
            let pt = inv.transform_point(Point {
                x: device_x as f64,
                y: device_y as f64,
            });
            (pt.x, pt.y)
        }
        None => (0.0, 0.0),
    }
}

// ---------------------------------------------------------------------------
// Thumbnail decoding
// ---------------------------------------------------------------------------

/// Decode the `/Thumb` image stream from a page dictionary, if present.
///
/// Returns the thumbnail as an RGBA32 `Bitmap`, or `None` if the page has
/// no `/Thumb` entry. Reuses the same image decoding infrastructure as the
/// render pipeline.
fn decode_page_thumbnail(
    store: &ObjectStore<Arc<[u8]>>,
    page_dict_id: ObjectId,
) -> Result<Option<Bitmap>> {
    let page_obj = store.resolve(page_dict_id)?;
    let page_dict = page_obj
        .as_dict()
        .ok_or(PdfError::UnknownObject(page_dict_id))?;

    let thumb_obj = match page_dict.get(&Name::thumb()) {
        Some(obj) => obj,
        None => return Ok(None),
    };

    // Resolve the /Thumb reference to the stream object
    let resolved = store.deep_resolve(thumb_obj)?;
    let stream_dict = match resolved.as_stream_dict() {
        Some(d) => d,
        None => return Ok(None),
    };

    let width = get_dict_int(stream_dict, &Name::width(), store).unwrap_or(0) as u32;
    let height = get_dict_int(stream_dict, &Name::height(), store).unwrap_or(0) as u32;
    let bpc = get_dict_int(stream_dict, &Name::bits_per_component(), store).unwrap_or(8) as u32;

    if width == 0 || height == 0 {
        return Ok(None);
    }

    let (n_components, cs_type) = resolve_image_color_space(stream_dict, store);

    // Decode the stream data through the standard filter chain
    let decoded = store.decode_stream(resolved)?;

    let decode_array = read_decode_array(stream_dict, n_components, store);

    let rgba = convert_to_rgba(
        &decoded,
        width,
        height,
        bpc,
        n_components,
        &cs_type,
        &decode_array,
        false,
    );

    let stride = width * 4; // RGBA32 = 4 bytes per pixel
    Ok(Some(Bitmap {
        width,
        height,
        format: BitmapFormat::Rgba32,
        stride,
        data: rgba,
    }))
}

/// Returns the thumbnail stream data, either decoded or raw.
///
/// When `decode` is `true`, the stream is decoded through the filter chain
/// (corresponds to `FPDFPage_GetDecodedThumbnailData`).
/// When `false`, the raw stream bytes are returned as stored
/// (corresponds to `FPDFPage_GetRawThumbnailData`).
pub(crate) fn thumbnail_raw_or_decoded(
    store: &ObjectStore<Arc<[u8]>>,
    page_dict_id: ObjectId,
    decode: bool,
) -> Result<Option<Vec<u8>>> {
    let page_obj = store.resolve(page_dict_id)?;
    let page_dict = page_obj
        .as_dict()
        .ok_or(PdfError::UnknownObject(page_dict_id))?;

    let thumb_obj = match page_dict.get(&Name::thumb()) {
        Some(obj) => obj,
        None => return Ok(None),
    };

    // Resolve through references to find the stream and its object ID
    let (thumb_id, resolved) = match thumb_obj {
        Object::Reference(id) => (*id, store.resolve(*id)?),
        other => {
            let r = store.deep_resolve(other)?;
            // No object ID available for inline streams
            return match r {
                Object::Stream { .. } if decode => {
                    let decoded = store.decode_stream(r)?;
                    Ok(Some(decoded))
                }
                Object::Stream {
                    data: rpdfium_parser::object::StreamData::Decoded { data },
                    ..
                } => Ok(Some(data.clone())),
                _ => Ok(None),
            };
        }
    };

    match resolved {
        Object::Stream { .. } => {
            if decode {
                let decoded = store.decode_stream(resolved)?;
                Ok(Some(decoded))
            } else {
                let raw = store.raw_stream_bytes_for_object(resolved, thumb_id)?;
                Ok(Some(raw))
            }
        }
        _ => Ok(None),
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    /// Build a minimal single-page PDF with a valid cross-reference table.
    fn minimal_pdf() -> Vec<u8> {
        let mut pdf = Vec::new();
        pdf.extend_from_slice(b"%PDF-1.4\n");
        let off1 = pdf.len();
        pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
        let off2 = pdf.len();
        pdf.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n");
        let off3 = pdf.len();
        pdf.extend_from_slice(
            b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>\nendobj\n",
        );
        let xref_offset = pdf.len();
        pdf.extend_from_slice(b"xref\n0 4\n");
        pdf.extend_from_slice(b"0000000000 65535 f \r\n");
        pdf.extend_from_slice(format!("{:010} 00000 n \r\n", off1).as_bytes());
        pdf.extend_from_slice(format!("{:010} 00000 n \r\n", off2).as_bytes());
        pdf.extend_from_slice(format!("{:010} 00000 n \r\n", off3).as_bytes());
        pdf.extend_from_slice(b"trailer\n<< /Size 4 /Root 1 0 R >>\n");
        pdf.extend_from_slice(format!("startxref\n{xref_offset}\n%%EOF").as_bytes());
        pdf
    }

    #[test]
    fn test_has_valid_cross_reference_table_valid_pdf() {
        let lib = Library::new();
        let opts = OpenOptions::default();
        let doc = Document::open(&lib, minimal_pdf(), &opts).unwrap();
        assert!(doc.has_valid_cross_reference_table());
    }

    #[test]
    fn test_trailer_ends_returns_empty_vec() {
        let lib = Library::new();
        let opts = OpenOptions::default();
        let doc = Document::open(&lib, minimal_pdf(), &opts).unwrap();
        // Stub returns empty for now
        let ends = doc.trailer_ends();
        let _ = ends; // just verify it doesn't panic
    }
}