liteparse-pdfium 1.5.0

Safe Rust wrapper around PDFium for liteparse
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
use std::marker::PhantomData;

use crate::bitmap::Bitmap;
use crate::document::{Document, FormEnvironment};
use crate::error::PdfiumError;
use crate::ffi;
use crate::text_page::TextPage;
use crate::types::{Color, RectF};

/// Bounding box of an embedded image object on a page.
/// Coordinates are in PDF points with top-left origin (Y-down).
#[derive(Debug, Clone, Copy)]
pub struct ImageBounds {
    pub x: f32,
    pub y: f32,
    pub width: f32,
    pub height: f32,
}

fn image_object_data(obj: pdfium_sys::FPDF_PAGEOBJECT, decoded: bool) -> Option<Vec<u8>> {
    let size = unsafe {
        if decoded {
            ffi!(FPDFImageObj_GetImageDataDecoded(
                obj,
                std::ptr::null_mut(),
                0
            ))
        } else {
            ffi!(FPDFImageObj_GetImageDataRaw(obj, std::ptr::null_mut(), 0))
        }
    };
    if size == 0 || size > usize::MAX as std::os::raw::c_ulong {
        return None;
    }
    let mut bytes = vec![0u8; size as usize];
    let written = unsafe {
        if decoded {
            ffi!(FPDFImageObj_GetImageDataDecoded(
                obj,
                bytes.as_mut_ptr().cast(),
                size
            ))
        } else {
            ffi!(FPDFImageObj_GetImageDataRaw(
                obj,
                bytes.as_mut_ptr().cast(),
                size
            ))
        }
    };
    if written == 0 || written > size {
        return None;
    }
    bytes.truncate(written as usize);
    Some(bytes)
}

fn image_filters(obj: pdfium_sys::FPDF_PAGEOBJECT) -> Vec<String> {
    let count = unsafe { ffi!(FPDFImageObj_GetImageFilterCount(obj)) };
    if count <= 0 {
        return Vec::new();
    }
    (0..count)
        .filter_map(|index| {
            let size = unsafe {
                ffi!(FPDFImageObj_GetImageFilter(
                    obj,
                    index,
                    std::ptr::null_mut(),
                    0
                ))
            };
            if size == 0 || size > 256 {
                return None;
            }
            let mut bytes = vec![0u8; size as usize];
            let written = unsafe {
                ffi!(FPDFImageObj_GetImageFilter(
                    obj,
                    index,
                    bytes.as_mut_ptr().cast(),
                    size
                ))
            };
            if written == 0 {
                return None;
            }
            let end = bytes
                .iter()
                .position(|byte| *byte == 0)
                .unwrap_or(bytes.len());
            std::str::from_utf8(&bytes[..end]).ok().map(str::to_owned)
        })
        .collect()
}

fn is_jpeg(bytes: &[u8]) -> bool {
    bytes.starts_with(&[0xff, 0xd8, 0xff]) && bytes.ends_with(&[0xff, 0xd9])
}

#[cfg(test)]
mod image_tests {
    use super::is_jpeg;

    #[test]
    fn validates_complete_jpeg_streams() {
        assert!(is_jpeg(&[0xff, 0xd8, 0xff, 0xe0, 1, 2, 0xff, 0xd9]));
        assert!(!is_jpeg(&[0xff, 0xd8, 0xff, 0xe0]));
        assert!(!is_jpeg(&[0x89, b'P', b'N', b'G', 0xff, 0xd9]));
    }
}

/// Metadata for an embedded image page object retained by the extraction
/// filters. `object_index` is its index among all image objects on the page.
#[derive(Debug, Clone)]
pub struct ImageObjectInfo {
    pub object_index: usize,
    pub bounds: ImageBounds,
    pub pixel_width: u32,
    pub pixel_height: u32,
    /// Clockwise page-object rotation in degrees, normalized to `[0, 360)`.
    pub rotation: f32,
    /// Original JPEG stream bytes when PDFium reports a directly decodable
    /// DCT stream and the decoded data has a valid JPEG signature.
    pub jpeg_bytes: Option<Vec<u8>>,
    /// Raw encoded stream bytes, used to identify repeated image resources.
    pub raw_bytes: Option<Vec<u8>>,
    #[doc(hidden)]
    pub bits_per_pixel: u32,
    #[doc(hidden)]
    pub colorspace: i32,
}

#[derive(Debug, Clone)]
pub struct ImageObjects {
    pub images: Vec<ImageObjectInfo>,
    pub error_count: u32,
}

/// One segment of a vector path. Coordinates are in viewport space
/// (top-left origin, 72 DPI) after the object's matrix has been applied.
#[derive(Debug, Clone, Copy)]
pub struct PathSegment {
    pub kind: SegmentKind,
    pub x: f32,
    pub y: f32,
    /// Whether this segment closes the current subpath back to its MoveTo.
    pub close: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SegmentKind {
    MoveTo,
    LineTo,
    BezierTo,
}

/// A vector path object extracted from a page. Used by the markdown emitter
/// for ruled-table, horizontal-rule, and figure-cluster detection.
#[derive(Debug, Clone)]
pub struct PathObject {
    /// Object bbox in viewport space (after matrix; from FPDFPageObj_GetBounds).
    pub bbox: RectF,
    pub stroke_color: Option<Color>,
    pub fill_color: Option<Color>,
    pub stroke_width: f32,
    /// True when the path is stroked per its draw mode.
    pub is_stroked: bool,
    /// True when the path is filled (draw-mode fill ≠ NONE).
    pub is_filled: bool,
    pub segments: Vec<PathSegment>,
}

/// A URI hyperlink annotation on a page. `rect` is in viewport space
/// (top-left origin, 72 DPI), matching `TextItem` coordinates so the URI can
/// be assigned to overlapping text. Only external URI links are represented;
/// internal GoTo/named destinations are excluded.
#[derive(Debug, Clone)]
pub struct PdfLink {
    pub rect: RectF,
    pub uri: String,
}

/// One PDF annotation with geometry normalized to viewport space (top-left
/// origin, 72 DPI). String fields mirror the standard annotation dictionary.
#[derive(Debug, Clone)]
pub struct PdfAnnotation {
    pub object_number: Option<i32>,
    pub subtype: String,
    pub contents: Option<String>,
    pub created: Option<String>,
    pub modified: Option<String>,
    pub title: Option<String>,
    pub rect: Option<RectF>,
    pub quadpoint_rects: Vec<RectF>,
    pub uri: Option<String>,
}

/// One AcroForm widget with its resolved field metadata. A logical radio or
/// checkbox field may appear more than once when it owns several widgets.
#[derive(Debug, Clone)]
pub struct PdfFormField {
    pub id: String,
    pub field_type: String,
    pub page: u32,
    pub annotation_index: i32,
    pub widget_index: i32,
    pub object_number: Option<i32>,
    pub name: Option<String>,
    pub alternate_name: Option<String>,
    pub value: Option<String>,
    pub export_value: Option<String>,
    pub field_flags: i32,
    pub control_count: Option<i32>,
    pub control_index: Option<i32>,
    pub checked: Option<bool>,
    pub rect: Option<RectF>,
    pub options: Vec<String>,
    pub selected_options: Vec<String>,
}

/// A loaded page within a [`Document`].
///
/// The `'doc` lifetime ties the page to its owning document; `'lib` carries
/// the PDFium-lock lifetime through, ensuring no PDFium calls can occur
/// after the lock is released.
pub struct Page<'doc, 'lib: 'doc> {
    pub(crate) handle: pdfium_sys::FPDF_PAGE,
    pub(crate) doc_handle: pdfium_sys::FPDF_DOCUMENT,
    pub(crate) _doc: PhantomData<&'doc Document<'lib>>,
}

impl<'doc, 'lib: 'doc> Page<'doc, 'lib> {
    pub fn width(&self) -> f32 {
        unsafe { ffi!(FPDF_GetPageWidthF(self.handle)) }
    }

    pub fn height(&self) -> f32 {
        unsafe { ffi!(FPDF_GetPageHeightF(self.handle)) }
    }

    pub fn rotation(&self) -> i32 {
        unsafe { ffi!(FPDFPage_GetRotation(self.handle)) }
    }

    /// Get the page bounding box (CropBox, falls back to MediaBox).
    /// Coordinates in PDF page space.
    pub fn view_box(&self) -> Option<RectF> {
        let mut rect = pdfium_sys::FS_RECTF {
            left: 0.0,
            top: 0.0,
            right: 0.0,
            bottom: 0.0,
        };
        let ok = unsafe { ffi!(FPDF_GetPageBoundingBox(self.handle, &mut rect)) };
        if ok != 0 {
            Some(RectF {
                left: rect.left,
                top: rect.top,
                right: rect.right,
                bottom: rect.bottom,
            })
        } else {
            None
        }
    }

    /// Convert a point from PDF page space to viewport space (top-left origin, 72 DPI).
    /// Mirrors the platform's Parse_pageToViewport using FPDF_PageToDevice at 1000x scale.
    pub fn page_to_viewport(&self, view_box: &RectF, page_x: f32, page_y: f32) -> (f32, f32) {
        let mut vw = view_box.right - view_box.left;
        let mut vh = view_box.top - view_box.bottom;

        let rotation = self.rotation();
        if rotation == 1 || rotation == 3 {
            // 90° or 270° — swap viewport dimensions
            std::mem::swap(&mut vw, &mut vh);
        }

        let device_w = (vw * 1000.0).round() as i32;
        let device_h = (vh * 1000.0).round() as i32;
        let mut dx: i32 = 0;
        let mut dy: i32 = 0;

        unsafe {
            ffi!(FPDF_PageToDevice(
                self.handle,
                0,
                0,
                device_w,
                device_h,
                0, // rotation 0 — PDFium applies page rotation internally
                page_x as f64,
                page_y as f64,
                &mut dx,
                &mut dy,
            ));
        }

        (dx as f32 / 1000.0, dy as f32 / 1000.0)
    }

    /// Convert bounds from PDF page space to viewport space (top-left origin).
    /// Returns RectF with left/top/right/bottom in viewport coordinates.
    pub fn bounds_to_viewport(&self, view_box: &RectF, page_bounds: &RectF) -> RectF {
        let (ll_x, ll_y) = self.page_to_viewport(view_box, page_bounds.left, page_bounds.bottom);
        let (ur_x, ur_y) = self.page_to_viewport(view_box, page_bounds.right, page_bounds.top);

        RectF {
            left: ll_x.min(ur_x),
            top: ll_y.min(ur_y),
            right: ll_x.max(ur_x),
            bottom: ll_y.max(ur_y),
        }
    }

    pub fn text(&self) -> Result<TextPage<'_, 'lib>, PdfiumError> {
        let handle = unsafe { ffi!(FPDFText_LoadPage(self.handle)) };
        if handle.is_null() {
            return Err(PdfiumError::OperationFailed);
        }
        Ok(TextPage {
            handle,
            _page: PhantomData,
        })
    }

    /// Render the page to a BGRA bitmap at the given DPI.
    pub fn render(&self, dpi: f32) -> Result<Bitmap<'lib>, PdfiumError> {
        self.render_with_form(dpi, None)
    }

    /// Render the page to a BGRA bitmap, drawing form-field appearances
    /// (filled values, checkbox states) on top via `FPDF_FFLDraw` when a form
    /// environment is supplied. Without it, PDFium only paints widget
    /// annotations' static appearance streams, so filled-in form data can be
    /// missing from the raster. The page open/close form notifications are
    /// wrapped around the render, mirroring the LlamaParse extract binary.
    pub fn render_with_form(
        &self,
        dpi: f32,
        form: Option<&FormEnvironment>,
    ) -> Result<Bitmap<'lib>, PdfiumError> {
        if let Some(form) = form {
            unsafe {
                ffi!(FORM_OnAfterLoadPage(self.handle, form.handle));
                ffi!(FORM_DoPageAAction(
                    self.handle,
                    form.handle,
                    pdfium_sys::FPDFPAGE_AACTION_OPEN as i32,
                ));
            }
        }
        let result = self.render_bitmap(dpi, form);
        if let Some(form) = form {
            unsafe {
                ffi!(FORM_DoPageAAction(
                    self.handle,
                    form.handle,
                    pdfium_sys::FPDFPAGE_AACTION_CLOSE as i32,
                ));
                ffi!(FORM_OnBeforeClosePage(self.handle, form.handle));
            }
        }
        result
    }

    fn render_bitmap(
        &self,
        dpi: f32,
        form: Option<&FormEnvironment>,
    ) -> Result<Bitmap<'lib>, PdfiumError> {
        let scale = dpi / 72.0;
        let width = (self.width() * scale).round() as i32;
        let height = (self.height() * scale).round() as i32;

        // SAFETY: this method is on `Page<'_, 'lib>`, whose existence proves
        // the PDFium lock is held for `'lib`; the returned `Bitmap<'lib>` is
        // tied to that same lock lifetime.
        let bitmap = unsafe { Bitmap::new(width, height) }?;

        // Fill with white (ARGB: 0xFFFFFFFF)
        bitmap.fill_rect(0, 0, width, height, 0xFFFFFFFF);

        let flags = (pdfium_sys::FPDF_ANNOT | pdfium_sys::FPDF_PRINTING) as i32;

        unsafe {
            ffi!(FPDF_RenderPageBitmap(
                bitmap.handle(),
                self.handle,
                0,      // start_x
                0,      // start_y
                width,  // size_x
                height, // size_y
                0,      // rotation
                flags,
            ));
        }

        if let Some(form) = form {
            // NOTE: like the LlamaParse extract binary, popup annotations are
            // not drawn (flags 0 for the form layer draw).
            unsafe {
                ffi!(FPDF_FFLDraw(
                    form.handle,
                    bitmap.handle(),
                    self.handle,
                    0,
                    0,
                    width,
                    height,
                    0,
                    0,
                ));
            }
        }

        Ok(bitmap)
    }

    /// Union of all top-level page object bounds, in PDF page space.
    /// `None` when the page has no content objects. Mirrors the LlamaParse
    /// extract binary's `Parse_getContentBounds`.
    pub fn content_bounds(&self) -> Option<RectF> {
        let count = unsafe { ffi!(FPDFPage_CountObjects(self.handle)) };
        let mut bounds: Option<RectF> = None;
        for i in 0..count {
            let obj = unsafe { ffi!(FPDFPage_GetObject(self.handle, i)) };
            if obj.is_null() {
                continue;
            }
            let mut left: f32 = 0.0;
            let mut bottom: f32 = 0.0;
            let mut right: f32 = 0.0;
            let mut top: f32 = 0.0;
            let ok = unsafe {
                ffi!(FPDFPageObj_GetBounds(
                    obj,
                    &mut left,
                    &mut bottom,
                    &mut right,
                    &mut top
                ))
            };
            if ok == 0 {
                continue;
            }
            bounds = Some(match bounds {
                None => RectF {
                    left,
                    top,
                    right,
                    bottom,
                },
                Some(prev) => RectF {
                    left: prev.left.min(left),
                    top: prev.top.max(top),
                    right: prev.right.max(right),
                    bottom: prev.bottom.min(bottom),
                },
            });
        }
        bounds
    }

    /// Extract bounding boxes of embedded image objects on this page.
    /// Returns coordinates in viewport space (Y-down, top-left origin) in PDF points.
    /// Filters out images smaller than `min_size_pt` and images covering more than
    /// `max_page_coverage` fraction of the page.
    pub fn image_bounds(&self, min_size_pt: f32, max_page_coverage: f32) -> Vec<ImageBounds> {
        self.image_objects(min_size_pt, max_page_coverage, false)
            .images
            .into_iter()
            .map(|image| image.bounds)
            .collect()
    }

    /// Extract metadata for embedded image objects on this page.
    pub fn image_objects(
        &self,
        min_size_pt: f32,
        max_page_coverage: f32,
        include_data: bool,
    ) -> ImageObjects {
        let page_width = self.width();
        let page_height = self.height();
        let view_box = self.view_box().unwrap_or(RectF {
            left: 0.0,
            top: page_height,
            right: page_width,
            bottom: 0.0,
        });
        let obj_count = unsafe { ffi!(FPDFPage_CountObjects(self.handle)) };
        let mut results = Vec::new();
        let mut error_count = 0;
        let mut image_index = 0usize;

        for i in 0..obj_count {
            let obj = unsafe { ffi!(FPDFPage_GetObject(self.handle, i)) };
            if obj.is_null() {
                continue;
            }

            let obj_type = unsafe { ffi!(FPDFPageObj_GetType(obj)) };
            if obj_type != pdfium_sys::FPDF_PAGEOBJ_IMAGE as i32 {
                continue;
            }
            let object_index = image_index;
            image_index += 1;

            let mut left: f32 = 0.0;
            let mut bottom: f32 = 0.0;
            let mut right: f32 = 0.0;
            let mut top: f32 = 0.0;
            let ok = unsafe {
                ffi!(FPDFPageObj_GetBounds(
                    obj,
                    &mut left,
                    &mut bottom,
                    &mut right,
                    &mut top
                ))
            };
            if ok == 0 {
                error_count += 1;
                continue;
            }

            let w = right - left;
            let h = top - bottom;

            if w < min_size_pt || h < min_size_pt {
                continue;
            }
            if w > page_width * max_page_coverage && h > page_height * max_page_coverage {
                continue;
            }

            let viewport = self.bounds_to_viewport(
                &view_box,
                &RectF {
                    left,
                    top,
                    right,
                    bottom,
                },
            );

            let mut metadata = pdfium_sys::FPDF_IMAGEOBJ_METADATA::default();
            let (pixel_width, pixel_height, rotation) = if include_data {
                let metadata_ok = unsafe {
                    ffi!(FPDFImageObj_GetImageMetadata(
                        obj,
                        self.handle,
                        &mut metadata
                    ))
                };
                let mut pixel_width = metadata.width;
                let mut pixel_height = metadata.height;
                let pixel_size_ok = unsafe {
                    ffi!(FPDFImageObj_GetImagePixelSize(
                        obj,
                        &mut pixel_width,
                        &mut pixel_height
                    ))
                };
                if pixel_size_ok == 0 && metadata_ok == 0 {
                    pixel_width = 0;
                    pixel_height = 0;
                    error_count += 1;
                }

                let mut matrix = pdfium_sys::FS_MATRIX {
                    a: 1.0,
                    b: 0.0,
                    c: 0.0,
                    d: 1.0,
                    e: 0.0,
                    f: 0.0,
                };
                let matrix_ok = unsafe { ffi!(FPDFPageObj_GetMatrix(obj, &mut matrix)) };
                let rotation = if matrix_ok != 0 {
                    matrix.b.atan2(matrix.a).to_degrees().rem_euclid(360.0)
                } else {
                    0.0
                };
                (pixel_width, pixel_height, rotation)
            } else {
                (0, 0, 0.0)
            };

            let raw_bytes = include_data
                .then(|| image_object_data(obj, false))
                .flatten();
            let jpeg_bytes = if include_data
                && image_filters(obj)
                    .iter()
                    .any(|filter| filter == "DCTDecode")
            {
                image_object_data(obj, true).filter(|bytes| is_jpeg(bytes))
            } else {
                None
            };

            results.push(ImageObjectInfo {
                object_index,
                bounds: ImageBounds {
                    x: viewport.left,
                    y: viewport.top,
                    width: viewport.right - viewport.left,
                    height: viewport.bottom - viewport.top,
                },
                pixel_width,
                pixel_height,
                rotation,
                jpeg_bytes,
                raw_bytes,
                bits_per_pixel: metadata.bits_per_pixel,
                colorspace: metadata.colorspace,
            });
        }

        ImageObjects {
            images: results,
            error_count,
        }
    }

    /// Extract bounding boxes of filled vector path objects on this page,
    /// recursing into form XObjects (with each form's transform applied).
    /// Returns coordinates in viewport space (Y-down, top-left origin) in PDF
    /// points. Stroke-only paths (rules, borders) are skipped, as are paths
    /// smaller than `min_size_pt` in either dimension and paths covering more
    /// than `max_page_coverage` fraction of the page in both dimensions
    /// (full-page background rects).
    pub fn filled_path_bounds(&self, min_size_pt: f32, max_page_coverage: f32) -> Vec<ImageBounds> {
        let page_width = self.width();
        let page_height = self.height();
        let obj_count = unsafe { ffi!(FPDFPage_CountObjects(self.handle)) };
        let mut results = Vec::new();

        for i in 0..obj_count {
            let obj = unsafe { ffi!(FPDFPage_GetObject(self.handle, i)) };
            if obj.is_null() {
                continue;
            }
            collect_filled_paths(
                obj,
                None,
                page_width,
                page_height,
                min_size_pt,
                max_page_coverage,
                0,
                &mut results,
            );
        }

        results
    }

    /// Get the rendered bitmap of a specific embedded image object by index.
    /// The index corresponds to the order from iterating page objects (image objects only).
    pub fn render_image_object(&self, image_obj_index: usize) -> Result<Bitmap<'lib>, PdfiumError> {
        let obj_count = unsafe { ffi!(FPDFPage_CountObjects(self.handle)) };
        let mut image_idx = 0usize;

        for i in 0..obj_count {
            let obj = unsafe { ffi!(FPDFPage_GetObject(self.handle, i)) };
            if obj.is_null() {
                continue;
            }
            let obj_type = unsafe { ffi!(FPDFPageObj_GetType(obj)) };
            if obj_type != pdfium_sys::FPDF_PAGEOBJ_IMAGE as i32 {
                continue;
            }

            if image_idx == image_obj_index {
                let bmp_handle = unsafe {
                    ffi!(FPDFImageObj_GetRenderedBitmap(
                        self.doc_handle,
                        self.handle,
                        obj
                    ))
                };
                if bmp_handle.is_null() {
                    return Err(PdfiumError::OperationFailed);
                }
                // Wrap in our Bitmap (which will call Destroy on drop)
                return Ok(unsafe { Bitmap::from_handle(bmp_handle) });
            }
            image_idx += 1;
        }

        Err(PdfiumError::OperationFailed)
    }

    /// Enumerate vector path objects on this page. Segment points are
    /// transformed into viewport space (top-left origin, 72 DPI) by composing
    /// the object's matrix with the page→viewport transform. Recurses into
    /// Form XObjects (composing each form's matrix) — table rules and other
    /// vector art are frequently wrapped in a form container, invisible to a
    /// top-level-only walk.
    pub fn path_objects(&self, view_box: &RectF) -> Vec<PathObject> {
        let vp = self.viewport_transform(view_box);
        let obj_count = unsafe { ffi!(FPDFPage_CountObjects(self.handle)) };
        let mut out = Vec::new();
        let identity = pdfium_sys::FS_MATRIX {
            a: 1.0,
            b: 0.0,
            c: 0.0,
            d: 1.0,
            e: 0.0,
            f: 0.0,
        };

        for i in 0..obj_count {
            let obj = unsafe { ffi!(FPDFPage_GetObject(self.handle, i)) };
            if obj.is_null() {
                continue;
            }
            collect_path_objects(obj, &identity, &vp, 0, &mut out);
        }
        out
    }

    /// Enumerate URI hyperlink annotations on this page. Each link's clickable
    /// rectangle is mapped into viewport space (matching `TextItem`); the URI
    /// is read from the link's URI action. Annotations whose action is not a
    /// URI (internal GoTo / named destinations) are skipped.
    pub fn links(&self, view_box: &RectF) -> Vec<PdfLink> {
        let mut out = Vec::new();
        let mut start_pos: std::os::raw::c_int = 0;
        let mut link_annot: pdfium_sys::FPDF_LINK = std::ptr::null_mut();
        loop {
            let ok = unsafe {
                ffi!(FPDFLink_Enumerate(
                    self.handle,
                    &mut start_pos,
                    &mut link_annot
                ))
            };
            if ok == 0 {
                break;
            }
            if link_annot.is_null() {
                continue;
            }
            let action = unsafe { ffi!(FPDFLink_GetAction(link_annot)) };
            if action.is_null() {
                continue;
            }
            let Some(uri) = read_uri_path(self.doc_handle, action) else {
                continue;
            };

            // Prefer per-line quad points: a link that wraps across lines has
            // one quad per line, each tight around the anchor text. The single
            // annotation rect is their *union* — a tall box that would swallow
            // the unlinked words sitting between the lines. Fall back to the
            // annot rect only when no quads are present.
            let quad_count = unsafe { ffi!(FPDFLink_CountQuadPoints(link_annot)) };
            let mut emitted = false;
            for q in 0..quad_count {
                let mut quad = pdfium_sys::FS_QUADPOINTSF::default();
                let ok = unsafe { ffi!(FPDFLink_GetQuadPoints(link_annot, q, &mut quad)) };
                if ok == 0 {
                    continue;
                }
                let page_bounds = RectF {
                    left: quad.x1.min(quad.x2).min(quad.x3).min(quad.x4),
                    bottom: quad.y1.min(quad.y2).min(quad.y3).min(quad.y4),
                    right: quad.x1.max(quad.x2).max(quad.x3).max(quad.x4),
                    top: quad.y1.max(quad.y2).max(quad.y3).max(quad.y4),
                };
                out.push(PdfLink {
                    rect: self.bounds_to_viewport(view_box, &page_bounds),
                    uri: uri.clone(),
                });
                emitted = true;
            }
            if emitted {
                continue;
            }

            let mut rect = pdfium_sys::FS_RECTF {
                left: 0.0,
                top: 0.0,
                right: 0.0,
                bottom: 0.0,
            };
            let got = unsafe { ffi!(FPDFLink_GetAnnotRect(link_annot, &mut rect)) };
            if got == 0 {
                continue;
            }
            let page_bounds = RectF {
                left: rect.left,
                top: rect.top,
                right: rect.right,
                bottom: rect.bottom,
            };
            out.push(PdfLink {
                rect: self.bounds_to_viewport(view_box, &page_bounds),
                uri,
            });
        }
        out
    }

    /// Enumerate all page annotations. Unlike [`Page::links`], this preserves
    /// non-link subtypes and annotation dictionary metadata for public output.
    pub fn annotations(&self, view_box: &RectF) -> Vec<PdfAnnotation> {
        let count = unsafe { ffi!(FPDFPage_GetAnnotCount(self.handle)) };
        let mut out = Vec::with_capacity(count.max(0) as usize);
        for index in 0..count {
            let annot = unsafe { ffi!(FPDFPage_GetAnnot(self.handle, index)) };
            if annot.is_null() {
                continue;
            }

            let subtype = unsafe { ffi!(FPDFAnnot_GetSubtype(annot)) };
            let mut rect = pdfium_sys::FS_RECTF::default();
            let rect = if unsafe { ffi!(FPDFAnnot_GetRect(annot, &mut rect)) } != 0 {
                Some(self.bounds_to_viewport(
                    view_box,
                    &RectF {
                        left: rect.left,
                        top: rect.top,
                        right: rect.right,
                        bottom: rect.bottom,
                    },
                ))
            } else {
                None
            };

            let mut quadpoint_rects = Vec::new();
            if unsafe { ffi!(FPDFAnnot_HasAttachmentPoints(annot)) } != 0 {
                let quad_count = unsafe { ffi!(FPDFAnnot_CountAttachmentPoints(annot)) };
                quadpoint_rects.reserve(quad_count);
                for quad_index in 0..quad_count {
                    let mut quad = pdfium_sys::FS_QUADPOINTSF::default();
                    if unsafe { ffi!(FPDFAnnot_GetAttachmentPoints(annot, quad_index, &mut quad)) }
                        == 0
                    {
                        continue;
                    }
                    let bounds = RectF {
                        left: quad.x1.min(quad.x2).min(quad.x3).min(quad.x4),
                        bottom: quad.y1.min(quad.y2).min(quad.y3).min(quad.y4),
                        right: quad.x1.max(quad.x2).max(quad.x3).max(quad.x4),
                        top: quad.y1.max(quad.y2).max(quad.y3).max(quad.y4),
                    };
                    quadpoint_rects.push(self.bounds_to_viewport(view_box, &bounds));
                }
            }

            let uri = if subtype == pdfium_sys::FPDF_ANNOT_LINK as i32 {
                let link = unsafe { ffi!(FPDFAnnot_GetLink(annot)) };
                if link.is_null() {
                    None
                } else {
                    let action = unsafe { ffi!(FPDFLink_GetAction(link)) };
                    if action.is_null() {
                        None
                    } else {
                        read_uri_path(self.doc_handle, action)
                    }
                }
            } else {
                None
            };

            out.push(PdfAnnotation {
                object_number: match unsafe { ffi!(FPDFAnnot_GetObjNum(annot)) } {
                    number if number > 0 => Some(number),
                    _ => None,
                },
                subtype: annotation_subtype_name(subtype).to_string(),
                contents: read_annotation_string(annot, b"Contents\0"),
                created: read_annotation_string(annot, b"CreationDate\0"),
                modified: read_annotation_string(annot, b"M\0"),
                title: read_annotation_string(annot, b"T\0"),
                rect,
                quadpoint_rects,
                uri,
            });
            unsafe { ffi!(FPDFPage_CloseAnnot(annot)) };
        }
        out
    }

    /// Whether any visible annotation paints text through its `/AP /N`
    /// appearance stream.
    ///
    /// PDFium's text API tokenizes the page content stream only — text drawn
    /// by an annotation appearance is rendered but never extracted. Pages
    /// authored that way (a common anti-copy / production-tool pattern) look
    /// identical to a blank page through [`Page::text_items`], so callers need
    /// this to tell "nothing here" from "content OCR can recover".
    ///
    /// Stops at the first text object found; hidden and popup annotations are
    /// skipped because they are not painted in the render OCR would see.
    pub fn has_annotation_text(&self) -> bool {
        let count = unsafe { ffi!(FPDFPage_GetAnnotCount(self.handle)) };
        for index in 0..count {
            let annot = unsafe { ffi!(FPDFPage_GetAnnot(self.handle, index)) };
            if annot.is_null() {
                continue;
            }
            let subtype = unsafe { ffi!(FPDFAnnot_GetSubtype(annot)) };
            let flags = unsafe { ffi!(FPDFAnnot_GetFlags(annot)) };
            let hidden = flags & pdfium_sys::FPDF_ANNOT_FLAG_HIDDEN as i32 != 0;
            let mut found = false;
            if !hidden && subtype != pdfium_sys::FPDF_ANNOT_POPUP as i32 {
                let object_count = unsafe { ffi!(FPDFAnnot_GetObjectCount(annot)) };
                for object_index in 0..object_count {
                    let object = unsafe { ffi!(FPDFAnnot_GetObject(annot, object_index)) };
                    if object.is_null() {
                        continue;
                    }
                    if unsafe { ffi!(FPDFPageObj_GetType(object)) }
                        == pdfium_sys::FPDF_PAGEOBJ_TEXT as i32
                    {
                        found = true;
                        break;
                    }
                }
            }
            unsafe { ffi!(FPDFPage_CloseAnnot(annot)) };
            if found {
                return true;
            }
        }
        false
    }

    /// Enumerate AcroForm widget annotations and resolve their field values
    /// through PDFium's form-fill environment.
    pub fn form_fields(
        &self,
        form: &FormEnvironment<'_, '_>,
        view_box: &RectF,
        page_number: u32,
    ) -> Vec<PdfFormField> {
        let count = unsafe { ffi!(FPDFPage_GetAnnotCount(self.handle)) };
        let mut out = Vec::new();
        let mut widget_index = 0;
        for annotation_index in 0..count {
            let annot = unsafe { ffi!(FPDFPage_GetAnnot(self.handle, annotation_index)) };
            if annot.is_null() {
                continue;
            }
            if unsafe { ffi!(FPDFAnnot_GetSubtype(annot)) } != pdfium_sys::FPDF_ANNOT_WIDGET as i32
            {
                unsafe { ffi!(FPDFPage_CloseAnnot(annot)) };
                continue;
            }

            let parent =
                unsafe { ffi!(FPDFAnnot_GetLinkedAnnot(annot, b"Parent\0".as_ptr().cast())) };
            let name = first_present([
                read_form_string(
                    form.handle,
                    annot,
                    |handle, annotation, buffer, len| unsafe {
                        ffi!(FPDFAnnot_GetFormFieldName(handle, annotation, buffer, len))
                    },
                ),
                read_annotation_string(annot, b"T\0"),
                (!parent.is_null())
                    .then(|| read_annotation_string(parent, b"T\0"))
                    .flatten(),
            ]);
            let alternate_name = first_present([
                read_form_string(
                    form.handle,
                    annot,
                    |handle, annotation, buffer, len| unsafe {
                        ffi!(FPDFAnnot_GetFormFieldAlternateName(
                            handle, annotation, buffer, len
                        ))
                    },
                ),
                read_annotation_string(annot, b"TU\0"),
                (!parent.is_null())
                    .then(|| read_annotation_string(parent, b"TU\0"))
                    .flatten(),
            ]);
            let value = first_present([
                read_form_string(
                    form.handle,
                    annot,
                    |handle, annotation, buffer, len| unsafe {
                        ffi!(FPDFAnnot_GetFormFieldValue(handle, annotation, buffer, len))
                    },
                ),
                read_annotation_string(annot, b"V\0"),
                (!parent.is_null())
                    .then(|| read_annotation_string(parent, b"V\0"))
                    .flatten(),
            ]);
            let appearance_state = read_annotation_string(annot, b"AS\0");
            let mut export_value = first_present([
                read_form_string(
                    form.handle,
                    annot,
                    |handle, annotation, buffer, len| unsafe {
                        ffi!(FPDFAnnot_GetFormFieldExportValue(
                            handle, annotation, buffer, len
                        ))
                    },
                ),
                read_annotation_string(annot, b"V\0"),
            ]);
            if export_value.is_none() {
                export_value = appearance_state
                    .as_ref()
                    .filter(|state| state.as_str() != "Off")
                    .cloned();
            }

            let raw_type = unsafe { ffi!(FPDFAnnot_GetFormFieldType(form.handle, annot)) };
            let object_number = match unsafe { ffi!(FPDFAnnot_GetObjNum(annot)) } {
                number if number > 0 => Some(number),
                _ => None,
            };
            let id = name
                .clone()
                .or_else(|| object_number.map(|n| format!("pdf-object-{n}")))
                .unwrap_or_else(|| format!("page-{page_number}-widget-{widget_index}"));
            let rect = annotation_rect(self, annot, view_box);
            let option_count = unsafe { ffi!(FPDFAnnot_GetOptionCount(form.handle, annot)) };
            let mut options = Vec::new();
            let mut selected_options = Vec::new();
            for option_index in 0..option_count.max(0) {
                if let Some(label) = read_form_option_label(form.handle, annot, option_index) {
                    if unsafe { ffi!(FPDFAnnot_IsOptionSelected(form.handle, annot, option_index)) }
                        != 0
                    {
                        selected_options.push(label.clone());
                    }
                    options.push(label);
                }
            }
            let is_checkable = raw_type == pdfium_sys::FPDF_FORMFIELD_CHECKBOX as i32
                || raw_type == pdfium_sys::FPDF_FORMFIELD_RADIOBUTTON as i32;
            let checked = is_checkable.then(|| {
                (unsafe { ffi!(FPDFAnnot_IsChecked(form.handle, annot)) }) != 0
                    || appearance_state
                        .as_ref()
                        .is_some_and(|state| state != "Off")
            });
            let control_count = is_checkable
                .then(|| unsafe { ffi!(FPDFAnnot_GetFormControlCount(form.handle, annot)) })
                .filter(|value| *value >= 0);
            let control_index = is_checkable
                .then(|| unsafe { ffi!(FPDFAnnot_GetFormControlIndex(form.handle, annot)) })
                .filter(|value| *value >= 0);

            out.push(PdfFormField {
                id,
                field_type: form_field_type_name(raw_type).to_owned(),
                page: page_number,
                annotation_index,
                widget_index,
                object_number,
                name,
                alternate_name,
                value,
                export_value,
                field_flags: unsafe { ffi!(FPDFAnnot_GetFormFieldFlags(form.handle, annot)) },
                control_count,
                control_index,
                checked,
                rect,
                options,
                selected_options,
            });
            if !parent.is_null() {
                unsafe { ffi!(FPDFPage_CloseAnnot(parent)) };
            }
            unsafe { ffi!(FPDFPage_CloseAnnot(annot)) };
            widget_index += 1;
        }
        out
    }
}

fn form_field_type_name(field_type: i32) -> &'static str {
    match field_type as u32 {
        pdfium_sys::FPDF_FORMFIELD_PUSHBUTTON => "pushbutton",
        pdfium_sys::FPDF_FORMFIELD_CHECKBOX => "checkbox",
        pdfium_sys::FPDF_FORMFIELD_RADIOBUTTON => "radio",
        pdfium_sys::FPDF_FORMFIELD_COMBOBOX => "combobox",
        pdfium_sys::FPDF_FORMFIELD_LISTBOX => "listbox",
        pdfium_sys::FPDF_FORMFIELD_TEXTFIELD => "text",
        pdfium_sys::FPDF_FORMFIELD_SIGNATURE => "signature",
        _ => "unknown",
    }
}

fn first_present<const N: usize>(values: [Option<String>; N]) -> Option<String> {
    values.into_iter().flatten().find(|value| !value.is_empty())
}

fn read_form_string(
    form: pdfium_sys::FPDF_FORMHANDLE,
    annot: pdfium_sys::FPDF_ANNOTATION,
    mut getter: impl FnMut(
        pdfium_sys::FPDF_FORMHANDLE,
        pdfium_sys::FPDF_ANNOTATION,
        *mut u16,
        std::os::raw::c_ulong,
    ) -> std::os::raw::c_ulong,
) -> Option<String> {
    let needed = getter(form, annot, std::ptr::null_mut(), 0) as usize;
    if needed < 2 {
        return None;
    }
    let mut buffer = vec![0u16; needed.div_ceil(2)];
    let written = getter(
        form,
        annot,
        buffer.as_mut_ptr(),
        needed as std::os::raw::c_ulong,
    ) as usize;
    if written < 2 {
        return None;
    }
    let units = (written / 2).min(buffer.len());
    let end = units.saturating_sub(usize::from(buffer.get(units.saturating_sub(1)) == Some(&0)));
    let value = String::from_utf16_lossy(&buffer[..end]);
    (!value.is_empty()).then_some(value)
}

fn read_form_option_label(
    form: pdfium_sys::FPDF_FORMHANDLE,
    annot: pdfium_sys::FPDF_ANNOTATION,
    index: i32,
) -> Option<String> {
    read_form_string(form, annot, |handle, annotation, buffer, len| unsafe {
        ffi!(FPDFAnnot_GetOptionLabel(
            handle, annotation, index, buffer, len
        ))
    })
}

fn annotation_rect(
    page: &Page<'_, '_>,
    annot: pdfium_sys::FPDF_ANNOTATION,
    view_box: &RectF,
) -> Option<RectF> {
    let mut rect = pdfium_sys::FS_RECTF::default();
    (unsafe { ffi!(FPDFAnnot_GetRect(annot, &mut rect)) } != 0).then(|| {
        page.bounds_to_viewport(
            view_box,
            &RectF {
                left: rect.left,
                top: rect.top,
                right: rect.right,
                bottom: rect.bottom,
            },
        )
    })
}

fn annotation_subtype_name(subtype: pdfium_sys::FPDF_ANNOTATION_SUBTYPE) -> &'static str {
    const NAMES: [&str; 29] = [
        "unknown",
        "text",
        "link",
        "freetext",
        "line",
        "square",
        "circle",
        "polygon",
        "polyline",
        "highlight",
        "underline",
        "squiggly",
        "strikeout",
        "stamp",
        "caret",
        "ink",
        "popup",
        "fileattachment",
        "sound",
        "movie",
        "widget",
        "screen",
        "printermark",
        "trapnet",
        "watermark",
        "threed",
        "richmedia",
        "xfawidget",
        "redact",
    ];
    usize::try_from(subtype)
        .ok()
        .and_then(|index| NAMES.get(index))
        .copied()
        .unwrap_or("unknown")
}

fn read_annotation_string(
    annot: pdfium_sys::FPDF_ANNOTATION,
    key: &'static [u8],
) -> Option<String> {
    let key = key.as_ptr().cast();
    let needed = unsafe {
        ffi!(FPDFAnnot_GetStringValue(
            annot,
            key,
            std::ptr::null_mut(),
            0
        ))
    } as usize;
    if needed < 2 {
        return None;
    }
    let mut buf = vec![0u16; needed.div_ceil(2)];
    let written = unsafe {
        ffi!(FPDFAnnot_GetStringValue(
            annot,
            key,
            buf.as_mut_ptr(),
            needed as std::os::raw::c_ulong
        ))
    } as usize;
    if written < 2 {
        return None;
    }
    let units = (written / 2).min(buf.len());
    let end = if buf.get(units.saturating_sub(1)) == Some(&0) {
        units.saturating_sub(1)
    } else {
        units
    };
    let value = String::from_utf16_lossy(&buf[..end]);
    if value.is_empty() { None } else { Some(value) }
}

/// Read a link action's URI path. PDFium returns the URI as a NUL-terminated
/// 7-bit-ASCII byte string; the two-call protocol queries the length first.
/// Returns `None` for non-URI actions (length 0) or empty URIs.
fn read_uri_path(
    doc: pdfium_sys::FPDF_DOCUMENT,
    action: pdfium_sys::FPDF_ACTION,
) -> Option<String> {
    let needed =
        unsafe { ffi!(FPDFAction_GetURIPath(doc, action, std::ptr::null_mut(), 0)) } as usize;
    if needed < 2 {
        return None;
    }
    let mut buf: Vec<u8> = vec![0; needed];
    let written = unsafe {
        ffi!(FPDFAction_GetURIPath(
            doc,
            action,
            buf.as_mut_ptr() as *mut std::os::raw::c_void,
            needed as std::os::raw::c_ulong,
        ))
    } as usize;
    if written < 2 {
        return None;
    }
    // `written` includes the trailing NUL.
    let end = written.saturating_sub(1).min(buf.len());
    let uri = String::from_utf8_lossy(&buf[..end])
        .trim_matches(char::from(0))
        .to_string();
    if uri.is_empty() { None } else { Some(uri) }
}

const FS_IDENTITY: pdfium_sys::FS_MATRIX = pdfium_sys::FS_MATRIX {
    a: 1.0,
    b: 0.0,
    c: 0.0,
    d: 1.0,
    e: 0.0,
    f: 0.0,
};

/// Compose two affine matrices: `result(p) = outer(inner(p))`.
fn compose_matrix(
    outer: &pdfium_sys::FS_MATRIX,
    inner: &pdfium_sys::FS_MATRIX,
) -> pdfium_sys::FS_MATRIX {
    pdfium_sys::FS_MATRIX {
        a: outer.a * inner.a + outer.c * inner.b,
        b: outer.b * inner.a + outer.d * inner.b,
        c: outer.a * inner.c + outer.c * inner.d,
        d: outer.b * inner.c + outer.d * inner.d,
        e: outer.a * inner.e + outer.c * inner.f + outer.e,
        f: outer.b * inner.e + outer.d * inner.f + outer.f,
    }
}

/// Recursively collect path objects, descending into Form XObjects. `parent`
/// is the accumulated form matrix mapping this object's content space into
/// page space (identity at the top level).
fn collect_path_objects(
    obj: pdfium_sys::FPDF_PAGEOBJECT,
    parent: &pdfium_sys::FS_MATRIX,
    vp: &ViewportTransform,
    depth: usize,
    out: &mut Vec<PathObject>,
) {
    const MAX_FORM_DEPTH: usize = 6;
    let obj_type = unsafe { ffi!(FPDFPageObj_GetType(obj)) };

    if obj_type == pdfium_sys::FPDF_PAGEOBJ_FORM as i32 {
        if depth >= MAX_FORM_DEPTH {
            return;
        }
        let mut fm = FS_IDENTITY;
        unsafe { ffi!(FPDFPageObj_GetMatrix(obj, &mut fm)) };
        let combined = compose_matrix(parent, &fm);
        let n = unsafe { ffi!(FPDFFormObj_CountObjects(obj)) };
        for i in 0..n {
            let child = unsafe { ffi!(FPDFFormObj_GetObject(obj, i as std::os::raw::c_ulong)) };
            if child.is_null() {
                continue;
            }
            collect_path_objects(child, &combined, vp, depth + 1, out);
        }
        return;
    }

    if obj_type != pdfium_sys::FPDF_PAGEOBJ_PATH as i32 {
        return;
    }

    // Object → content-space matrix, composed with the accumulated form
    // matrix to reach page space.
    let mut m = FS_IDENTITY;
    unsafe { ffi!(FPDFPageObj_GetMatrix(obj, &mut m)) };
    let m = compose_matrix(parent, &m);

    // GetBounds reports bounds in the object's content-stream space (its own
    // matrix applied, ancestor form matrices not). Lift the corners through
    // the parent matrix, then to viewport.
    let mut left = 0.0f32;
    let mut bottom = 0.0f32;
    let mut right = 0.0f32;
    let mut top = 0.0f32;
    let ok = unsafe {
        ffi!(FPDFPageObj_GetBounds(
            obj,
            &mut left,
            &mut bottom,
            &mut right,
            &mut top
        ))
    };
    if ok == 0 {
        return;
    }
    let corners = [(left, bottom), (left, top), (right, bottom), (right, top)];
    let mut min_x = f32::INFINITY;
    let mut min_y = f32::INFINITY;
    let mut max_x = f32::NEG_INFINITY;
    let mut max_y = f32::NEG_INFINITY;
    for (x, y) in corners {
        let px = parent.a * x + parent.c * y + parent.e;
        let py = parent.b * x + parent.d * y + parent.f;
        min_x = min_x.min(px);
        max_x = max_x.max(px);
        min_y = min_y.min(py);
        max_y = max_y.max(py);
    }
    let bbox = vp.transform_bounds(&RectF {
        left: min_x,
        top: max_y,
        right: max_x,
        bottom: min_y,
    });

    // Draw mode → is_filled / is_stroked.
    let mut fill_mode = 0i32;
    let mut stroke_bool = 0i32;
    let dm_ok = unsafe { ffi!(FPDFPath_GetDrawMode(obj, &mut fill_mode, &mut stroke_bool)) };
    let (is_filled, is_stroked) = if dm_ok != 0 {
        (
            fill_mode != pdfium_sys::FPDF_FILLMODE_NONE as i32,
            stroke_bool != 0,
        )
    } else {
        (false, false)
    };

    // Colors are reported as RGBA channels in 0..=255 cuint.
    let stroke_color =
        read_color(|r, g, b, a| unsafe { ffi!(FPDFPageObj_GetStrokeColor(obj, r, g, b, a)) });
    let fill_color =
        read_color(|r, g, b, a| unsafe { ffi!(FPDFPageObj_GetFillColor(obj, r, g, b, a)) });

    let mut stroke_width = 0.0f32;
    unsafe { ffi!(FPDFPageObj_GetStrokeWidth(obj, &mut stroke_width)) };

    // Walk segments. Points are in the object's local coords; apply the
    // composed matrix → page, then viewport transform.
    let n_segs = unsafe { ffi!(FPDFPath_CountSegments(obj)) };
    let mut segments = Vec::with_capacity(n_segs.max(0) as usize);
    for si in 0..n_segs {
        let seg = unsafe { ffi!(FPDFPath_GetPathSegment(obj, si)) };
        if seg.is_null() {
            continue;
        }
        let mut sx = 0.0f32;
        let mut sy = 0.0f32;
        let pt_ok = unsafe { ffi!(FPDFPathSegment_GetPoint(seg, &mut sx, &mut sy)) };
        if pt_ok == 0 {
            continue;
        }
        let ty = unsafe { ffi!(FPDFPathSegment_GetType(seg)) };
        let close = unsafe { ffi!(FPDFPathSegment_GetClose(seg)) } != 0;
        let kind = match ty as u32 {
            pdfium_sys::FPDF_SEGMENT_MOVETO => SegmentKind::MoveTo,
            pdfium_sys::FPDF_SEGMENT_LINETO => SegmentKind::LineTo,
            pdfium_sys::FPDF_SEGMENT_BEZIERTO => SegmentKind::BezierTo,
            _ => continue,
        };

        // Apply the composed matrix (FS_MATRIX is column-major a/b/c/d/e/f
        // matching the PDF text-matrix convention used elsewhere).
        let page_x = m.a * sx + m.c * sy + m.e;
        let page_y = m.b * sx + m.d * sy + m.f;
        let (x, y) = vp.transform_point(page_x, page_y);
        segments.push(PathSegment { kind, x, y, close });
    }

    out.push(PathObject {
        bbox,
        stroke_color,
        fill_color,
        stroke_width,
        is_stroked,
        is_filled,
        segments,
    });
}

/// Helper: call a PDFium getter for RGBA color channels and pack into our `Color`.
/// Returns None when the FFI call reports failure.
fn read_color<F>(getter: F) -> Option<Color>
where
    F: FnOnce(*mut u32, *mut u32, *mut u32, *mut u32) -> i32,
{
    let mut r = 0u32;
    let mut g = 0u32;
    let mut b = 0u32;
    let mut a = 0u32;
    let ok = getter(&mut r, &mut g, &mut b, &mut a);
    if ok == 0 {
        return None;
    }
    Some(Color {
        r: r as u8,
        g: g as u8,
        b: b as u8,
        a: a as u8,
    })
}

/// Recursion limit for nested form XObjects in `filled_path_bounds`.
const MAX_FORM_DEPTH: u32 = 4;

/// Compose two FS_MATRIX transforms: the result applies `inner` first,
/// then `outer` (i.e. `outer ∘ inner`).
fn compose_matrices(
    outer: &pdfium_sys::FS_MATRIX,
    inner: &pdfium_sys::FS_MATRIX,
) -> pdfium_sys::FS_MATRIX {
    pdfium_sys::FS_MATRIX {
        a: outer.a * inner.a + outer.c * inner.b,
        b: outer.b * inner.a + outer.d * inner.b,
        c: outer.a * inner.c + outer.c * inner.d,
        d: outer.b * inner.c + outer.d * inner.d,
        e: outer.a * inner.e + outer.c * inner.f + outer.e,
        f: outer.b * inner.e + outer.d * inner.f + outer.f,
    }
}

#[allow(clippy::too_many_arguments)]
fn collect_filled_paths(
    obj: pdfium_sys::FPDF_PAGEOBJECT,
    transform: Option<&pdfium_sys::FS_MATRIX>,
    page_width: f32,
    page_height: f32,
    min_size_pt: f32,
    max_page_coverage: f32,
    depth: u32,
    out: &mut Vec<ImageBounds>,
) {
    let obj_type = unsafe { ffi!(FPDFPageObj_GetType(obj)) };

    if obj_type == pdfium_sys::FPDF_PAGEOBJ_FORM as i32 {
        if depth >= MAX_FORM_DEPTH {
            return;
        }
        // Child bounds are reported in the form's coordinate space, so the
        // form matrix (composed with any outer form transforms) must be
        // applied to map them into page space.
        let mut m = pdfium_sys::FS_MATRIX {
            a: 1.0,
            b: 0.0,
            c: 0.0,
            d: 1.0,
            e: 0.0,
            f: 0.0,
        };
        let has_m = unsafe { ffi!(FPDFPageObj_GetMatrix(obj, &mut m)) } != 0;
        let combined = match (transform, has_m) {
            (Some(outer), true) => Some(compose_matrices(outer, &m)),
            (Some(outer), false) => Some(*outer),
            (None, true) => Some(m),
            (None, false) => None,
        };

        let child_count = unsafe { ffi!(FPDFFormObj_CountObjects(obj)) };
        for i in 0..child_count {
            let child = unsafe { ffi!(FPDFFormObj_GetObject(obj, i as std::os::raw::c_ulong)) };
            if child.is_null() {
                continue;
            }
            collect_filled_paths(
                child,
                combined.as_ref(),
                page_width,
                page_height,
                min_size_pt,
                max_page_coverage,
                depth + 1,
                out,
            );
        }
        return;
    }

    if obj_type != pdfium_sys::FPDF_PAGEOBJ_PATH as i32 {
        return;
    }

    // Only filled paths can be glyph outlines; skip stroke-only paths
    // (table borders, rules, underlines).
    let mut fill_mode: std::os::raw::c_int = 0;
    let mut stroke: pdfium_sys::FPDF_BOOL = 0;
    let ok = unsafe { ffi!(FPDFPath_GetDrawMode(obj, &mut fill_mode, &mut stroke)) };
    if ok == 0 || fill_mode == pdfium_sys::FPDF_FILLMODE_NONE as i32 {
        return;
    }

    // Skip light or transparent fills: glyph outlines are drawn in ink-like
    // (dark, opaque) colors, while table zebra striping and section shading
    // use light pastels. Light-on-dark text still gets caught because the
    // dark background rect itself is a dark filled path. Paths whose fill
    // color can't be read (pattern/shading fills) are kept conservatively.
    let mut r: std::os::raw::c_uint = 0;
    let mut g: std::os::raw::c_uint = 0;
    let mut b: std::os::raw::c_uint = 0;
    let mut a: std::os::raw::c_uint = 0;
    let ok = unsafe {
        ffi!(FPDFPageObj_GetFillColor(
            obj, &mut r, &mut g, &mut b, &mut a
        ))
    };
    if ok != 0 {
        if a < 128 {
            return;
        }
        let luminance = 0.299 * r as f32 + 0.587 * g as f32 + 0.114 * b as f32;
        if luminance > 140.0 {
            return;
        }
    }

    let mut left: f32 = 0.0;
    let mut bottom: f32 = 0.0;
    let mut right: f32 = 0.0;
    let mut top: f32 = 0.0;
    let ok = unsafe {
        ffi!(FPDFPageObj_GetBounds(
            obj,
            &mut left,
            &mut bottom,
            &mut right,
            &mut top
        ))
    };
    if ok == 0 {
        return;
    }

    if let Some(m) = transform {
        let corners = [(left, bottom), (right, bottom), (left, top), (right, top)];
        let mut min_x = f32::INFINITY;
        let mut max_x = f32::NEG_INFINITY;
        let mut min_y = f32::INFINITY;
        let mut max_y = f32::NEG_INFINITY;
        for (x, y) in corners {
            let tx = m.a * x + m.c * y + m.e;
            let ty = m.b * x + m.d * y + m.f;
            min_x = min_x.min(tx);
            max_x = max_x.max(tx);
            min_y = min_y.min(ty);
            max_y = max_y.max(ty);
        }
        left = min_x;
        right = max_x;
        bottom = min_y;
        top = max_y;
    }

    let w = right - left;
    let h = top - bottom;

    if w < min_size_pt || h < min_size_pt {
        return;
    }
    if w > page_width * max_page_coverage && h > page_height * max_page_coverage {
        return;
    }

    out.push(ImageBounds {
        x: left,
        y: page_height - top,
        width: w,
        height: h,
    });
}

/// Pre-computed affine transform from PDF page space to viewport space.
/// Avoids repeated FFI calls to `FPDF_PageToDevice` by probing 3 points
/// once and deriving the 6 affine coefficients.
#[derive(Debug, Clone, Copy)]
pub struct ViewportTransform {
    a: f32,
    b: f32,
    c: f32,
    d: f32,
    e: f32,
    f: f32,
}

impl ViewportTransform {
    /// Transform a single point from page space to viewport space.
    #[inline]
    pub fn transform_point(&self, page_x: f32, page_y: f32) -> (f32, f32) {
        (
            self.a * page_x + self.b * page_y + self.e,
            self.c * page_x + self.d * page_y + self.f,
        )
    }

    /// Transform a bounding rect from page space to viewport space.
    #[inline]
    pub fn transform_bounds(&self, page_bounds: &RectF) -> RectF {
        let (ll_x, ll_y) = self.transform_point(page_bounds.left, page_bounds.bottom);
        let (ur_x, ur_y) = self.transform_point(page_bounds.right, page_bounds.top);
        RectF {
            left: ll_x.min(ur_x),
            top: ll_y.min(ur_y),
            right: ll_x.max(ur_x),
            bottom: ll_y.max(ur_y),
        }
    }
}

impl<'doc, 'lib: 'doc> Page<'doc, 'lib> {
    /// Build a `ViewportTransform` by probing 3 points through PDFium.
    /// This makes 3 FFI calls total, after which all transforms are pure math.
    pub fn viewport_transform(&self, view_box: &RectF) -> ViewportTransform {
        let (e, f) = self.page_to_viewport(view_box, 0.0, 0.0);
        let (ax_e, cx_f) = self.page_to_viewport(view_box, 1.0, 0.0);
        let (by_e, dy_f) = self.page_to_viewport(view_box, 0.0, 1.0);

        ViewportTransform {
            a: ax_e - e,
            b: by_e - e,
            c: cx_f - f,
            d: dy_f - f,
            e,
            f,
        }
    }
}

impl Drop for Page<'_, '_> {
    fn drop(&mut self) {
        unsafe { ffi!(FPDF_ClosePage(self.handle)) };
    }
}

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

    #[test]
    fn nested_form_matrix_composition_transforms_path_points_in_order() {
        // Outer form translates by (100, 20), inner form scales by (2, 3),
        // and the path object translates by (4, 5). The collector composes
        // these in outer(inner(path(point))) order.
        let outer = pdfium_sys::FS_MATRIX {
            a: 1.0,
            b: 0.0,
            c: 0.0,
            d: 1.0,
            e: 100.0,
            f: 20.0,
        };
        let inner = pdfium_sys::FS_MATRIX {
            a: 2.0,
            b: 0.0,
            c: 0.0,
            d: 3.0,
            e: 0.0,
            f: 0.0,
        };
        let object = pdfium_sys::FS_MATRIX {
            a: 1.0,
            b: 0.0,
            c: 0.0,
            d: 1.0,
            e: 4.0,
            f: 5.0,
        };
        let nested = compose_matrix(&compose_matrix(&outer, &inner), &object);
        let x = nested.a * 1.0 + nested.c * 2.0 + nested.e;
        let y = nested.b * 1.0 + nested.d * 2.0 + nested.f;
        assert_eq!((x, y), (110.0, 41.0));

        let viewport = ViewportTransform {
            a: 1.0,
            b: 0.0,
            c: 0.0,
            d: -1.0,
            e: 0.0,
            f: 200.0,
        };
        assert_eq!(viewport.transform_point(x, y), (110.0, 159.0));
    }

    fn annotation_pdf() -> Vec<u8> {
        let objects = [
            "<< /Type /Catalog /Pages 2 0 R >>",
            "<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
            "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Annots [4 0 R 5 0 R] >>",
            "<< /Type /Annot /Subtype /Highlight /Rect [10 20 100 40] /QuadPoints [10 40 100 40 10 20 100 20] /Contents (review this) /T (Reviewer) /CreationDate (D:20260102030405Z) /M (D:20260103040506Z) >>",
            "<< /Type /Annot /Subtype /Link /Rect [10 50 100 70] /Border [0 0 0] /A << /S /URI /URI (https://example.com) >> >>",
        ];
        let mut pdf = b"%PDF-1.7\n".to_vec();
        let mut offsets = Vec::with_capacity(objects.len());
        for (index, object) in objects.iter().enumerate() {
            offsets.push(pdf.len());
            pdf.extend_from_slice(format!("{} 0 obj\n{}\nendobj\n", index + 1, object).as_bytes());
        }
        let xref = pdf.len();
        pdf.extend_from_slice(format!("xref\n0 {}\n", objects.len() + 1).as_bytes());
        pdf.extend_from_slice(b"0000000000 65535 f \n");
        for offset in offsets {
            pdf.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
        }
        pdf.extend_from_slice(
            format!(
                "trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n",
                objects.len() + 1
            )
            .as_bytes(),
        );
        pdf
    }

    #[test]
    fn extracts_annotation_metadata_geometry_and_link_uri() {
        let bytes = annotation_pdf();
        let library = Library::init();
        let document = library.load_document_from_bytes(&bytes, None).unwrap();
        let page = document.page(0).unwrap();
        let view_box = page.view_box().unwrap();
        let annotations = page.annotations(&view_box);

        assert_eq!(annotations.len(), 2);
        let highlight = &annotations[0];
        assert_eq!(highlight.subtype, "highlight");
        assert_eq!(highlight.contents.as_deref(), Some("review this"));
        assert_eq!(highlight.title.as_deref(), Some("Reviewer"));
        assert_eq!(highlight.created.as_deref(), Some("D:20260102030405Z"));
        assert_eq!(highlight.modified.as_deref(), Some("D:20260103040506Z"));
        let rect = highlight.rect.as_ref().unwrap();
        assert_eq!(
            (rect.left, rect.top, rect.right, rect.bottom),
            (10.0, 160.0, 100.0, 180.0)
        );
        assert_eq!(highlight.quadpoint_rects.len(), 1);

        let link = &annotations[1];
        assert_eq!(link.subtype, "link");
        assert_eq!(link.uri.as_deref(), Some("https://example.com"));
        assert_eq!(link.rect.as_ref().unwrap().top, 130.0);
    }
}