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
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
//! Form XObject and image XObject extraction.
use super::fonts::{font_style, FontStyle};
use super::text_paint::{PaintResources, TextPaint};
use crate::text_utils::{effective_font_size, expand_ligatures};
use crate::tounicode::FontCMaps;
use crate::types::{attach_run_coverage, BoldSource, ItemCoverage, ItemType, TextItem};
use lopdf::{Document, Encoding, Object, ObjectId};
use std::collections::HashMap;
use super::content_stream::{estimated_string_advance_ts, PendingSpace};
use super::fonts::{
build_font_encodings, build_font_widths, build_type3_scales, build_type3_y_flips,
compute_string_width_ts, extract_text_from_operand, get_font_file2_obj_num, get_operand_bytes,
CMapDecisionCache, FontStyleCache,
};
use super::geometry::{
advanced_tm, baseline_rotation, estimated_advance_ts, reading_direction, rise_adjusted,
scaled_run_geometry,
};
use super::word_gaps::{
is_dependent_sign, offset_takes_spacing_back, tj_gap_thresholds, tj_tracking,
word_gap_candidate, word_gap_threshold, PenHighWater, PendingWordGaps, WordGapCandidate,
};
use super::{get_number, image_bbox_from_ctm, multiply_matrices};
const MAX_FORM_XOBJECT_DEPTH: u8 = 5;
/// Upper bound on Form XObject invocations during a single page extraction.
/// Depth alone is not enough: an acyclic DAG where each form invokes the next
/// N times expands to N^depth work before the depth cap is reached.
const MAX_FORM_XOBJECT_INVOCATIONS: usize = 10_000;
/// Upper bound on content-stream operations walked across all Form XObject
/// expansions for a page. Nested forms are decoded independently of the
/// page-level operation cap, so this keeps total form work in the same
/// ballpark as that page cap.
const MAX_FORM_XOBJECT_OPERATIONS: usize = 1_000_000;
/// Shared budget for Form XObject expansion on a page. Bounds both nested DAG
/// expansion and repeated sibling `/Do` invocations of the same form.
pub(crate) struct FormWalkBudget {
invocations: usize,
operations: usize,
max_invocations: usize,
max_operations: usize,
truncated: bool,
}
impl FormWalkBudget {
pub(crate) fn new() -> Self {
Self::with_limits(MAX_FORM_XOBJECT_INVOCATIONS, MAX_FORM_XOBJECT_OPERATIONS)
}
fn with_limits(max_invocations: usize, max_operations: usize) -> Self {
Self {
invocations: 0,
operations: 0,
max_invocations,
max_operations,
truncated: false,
}
}
fn exhausted(&mut self) -> bool {
if self.invocations >= self.max_invocations || self.operations >= self.max_operations {
self.truncated = true;
true
} else {
false
}
}
fn charge_invocation(&mut self) -> bool {
if self.exhausted() {
return false;
}
self.invocations += 1;
true
}
/// Charge one walked content-stream operator. Independent of the
/// invocation cap so a form that was already admitted can finish its
/// stream (up to the operation cap).
fn charge_operation(&mut self) -> bool {
if self.operations >= self.max_operations {
self.truncated = true;
return false;
}
self.operations += 1;
true
}
pub(crate) fn was_truncated(&self) -> bool {
self.truncated
}
}
pub(crate) enum XObjectType {
Image,
Form(ObjectId),
}
/// Get XObjects from page resources, categorized by type
pub(crate) fn get_page_xobjects(
doc: &Document,
page_id: ObjectId,
) -> std::collections::HashMap<String, XObjectType> {
let mut xobject_types = std::collections::HashMap::new();
// Try to get the page dictionary
if let Ok(page_dict) = doc.get_dictionary(page_id) {
// Get Resources dictionary
let resources = if let Ok(res_ref) = page_dict.get(b"Resources") {
if let Ok(obj_ref) = res_ref.as_reference() {
doc.get_dictionary(obj_ref).ok()
} else {
res_ref.as_dict().ok()
}
} else {
None
};
if let Some(resources) = resources {
collect_xobjects_from_dict(doc, resources, &mut xobject_types);
}
}
xobject_types
}
/// Get XObjects from a Form XObject's Resources
fn get_form_xobjects(
doc: &Document,
form_dict: &lopdf::Dictionary,
) -> HashMap<String, XObjectType> {
let mut xobject_types = HashMap::new();
let resources = if let Ok(res_ref) = form_dict.get(b"Resources") {
if let Ok(obj_ref) = res_ref.as_reference() {
doc.get_dictionary(obj_ref).ok()
} else {
res_ref.as_dict().ok()
}
} else {
return xobject_types;
};
if let Some(resources) = resources {
collect_xobjects_from_dict(doc, resources, &mut xobject_types);
}
xobject_types
}
/// Collect XObject entries from a Resources dictionary
fn collect_xobjects_from_dict(
doc: &Document,
resources: &lopdf::Dictionary,
xobject_types: &mut HashMap<String, XObjectType>,
) {
if let Ok(xobjects_ref) = resources.get(b"XObject") {
let xobjects = if let Ok(obj_ref) = xobjects_ref.as_reference() {
doc.get_dictionary(obj_ref).ok()
} else {
xobjects_ref.as_dict().ok()
};
if let Some(xobjects) = xobjects {
for (name, value) in xobjects.iter() {
let name_str = String::from_utf8_lossy(name).to_string();
if let Ok(obj_ref) = value.as_reference() {
if let Ok(Object::Stream(stream)) = doc.get_object(obj_ref) {
if let Ok(subtype) = stream.dict.get(b"Subtype") {
if let Ok(subtype_name) = subtype.as_name() {
if subtype_name == b"Image" {
xobject_types.insert(name_str, XObjectType::Image);
} else if subtype_name == b"Form" {
xobject_types.insert(name_str, XObjectType::Form(obj_ref));
}
}
}
}
}
}
}
}
}
/// Text items extracted from a content stream together with the visual-order
/// RTL evidence gathered while parsing them, for the page-level
/// `fix_visual_order_rtl` pass: indexes of candidate items (see
/// `is_visual_rtl_candidate`) and of the items shown by logical-order ops.
pub(crate) struct ExtractedText {
pub(crate) items: Vec<TextItem>,
/// The CMap coverage of each item, parallel to `items`.
pub(crate) item_coverage: ItemCoverage,
pub(crate) rtl_visual_candidates: Vec<usize>,
pub(crate) rtl_logical_runs: Vec<usize>,
/// Indexes of the items shown by visible ops of several RTL letters
/// painted forwards (see `is_visual_rtl_run`): visual-storage votes.
pub(crate) rtl_visual_runs: Vec<usize>,
/// Baseline angle of every text-producing show operator, in stream
/// order: this form's share of the page-rotation vote. Per operator,
/// not per item — one TJ array can split into several items.
pub(crate) run_rotations: Vec<f32>,
/// Invisible (Tr 3) text was present but suppressed — the same signal
/// the page parser reports, so a hidden OCR layer drawn through a form
/// still earns the `include_invisible` retry.
pub(crate) skipped_invisible: bool,
}
impl ExtractedText {
fn new() -> Self {
Self {
items: Vec::new(),
item_coverage: Vec::new(),
rtl_visual_candidates: Vec::new(),
rtl_logical_runs: Vec::new(),
rtl_visual_runs: Vec::new(),
run_rotations: Vec::new(),
skipped_invisible: false,
}
}
/// Append this extraction into a caller's accumulators, rebasing the
/// candidate indexes onto the caller's item vector. Keeping the rebase
/// here is what stops item and RTL-evidence bookkeeping from drifting
/// apart across the page/form extraction paths.
#[allow(clippy::too_many_arguments)]
pub(crate) fn append_into(
self,
items: &mut Vec<TextItem>,
item_coverage: &mut ItemCoverage,
rtl_visual_candidates: &mut Vec<usize>,
rtl_logical_runs: &mut Vec<usize>,
rtl_visual_runs: &mut Vec<usize>,
run_rotations: &mut Vec<f32>,
skipped_invisible: &mut bool,
) {
let base = items.len();
rtl_visual_candidates.extend(self.rtl_visual_candidates.into_iter().map(|c| c + base));
rtl_logical_runs.extend(self.rtl_logical_runs.into_iter().map(|c| c + base));
rtl_visual_runs.extend(self.rtl_visual_runs.into_iter().map(|c| c + base));
run_rotations.extend(self.run_rotations);
*skipped_invisible |= self.skipped_invisible;
debug_assert_eq!(self.items.len(), self.item_coverage.len());
items.extend(self.items);
item_coverage.extend(self.item_coverage);
}
}
/// Extract text items from a Form XObject.
#[allow(clippy::too_many_arguments)]
pub(crate) fn extract_form_xobject_text(
doc: &Document,
form_id: ObjectId,
page_num: u32,
font_cmaps: &FontCMaps,
parent_ctm: &[f32; 6],
include_invisible: bool,
inherited_render_mode: i32,
inherited_text_rise: f32,
inherited_horizontal_scale: f32,
inherited_text_paint: TextPaint,
inherited_fill_is_white: bool,
cmap_decisions: &mut CMapDecisionCache,
style_cache: &mut FontStyleCache,
budget: &mut FormWalkBudget,
) -> ExtractedText {
extract_form_xobject_text_inner(
doc,
form_id,
page_num,
font_cmaps,
parent_ctm,
include_invisible,
inherited_render_mode,
inherited_text_rise,
inherited_horizontal_scale,
inherited_text_paint,
inherited_fill_is_white,
cmap_decisions,
style_cache,
0,
budget,
)
}
#[allow(clippy::too_many_arguments)]
fn extract_form_xobject_text_inner(
doc: &Document,
form_id: ObjectId,
page_num: u32,
font_cmaps: &FontCMaps,
parent_ctm: &[f32; 6],
include_invisible: bool,
inherited_render_mode: i32,
inherited_text_rise: f32,
inherited_horizontal_scale: f32,
inherited_text_paint: TextPaint,
inherited_fill_is_white: bool,
cmap_decisions: &mut CMapDecisionCache,
style_cache: &mut FontStyleCache,
depth: u8,
budget: &mut FormWalkBudget,
) -> ExtractedText {
let mut extracted = ExtractedText::new();
if !budget.charge_invocation() {
return extracted;
}
// Get the Form XObject stream
let Ok(Object::Stream(stream)) = doc.get_object(form_id) else {
return extracted;
};
// Decompress the content stream within the page-content bound: a form
// inflating past it is skipped, as a page over it is, before anything
// is allocated for it. A stream that fails to decode for another
// reason is read raw, if that fits the bound too.
let content_data = match stream
.decompressed_content_with_limit(super::content_decode::MAX_PAGE_CONTENT_BYTES)
{
Ok(data) => data,
Err(lopdf::Error::Decompress(lopdf::DecompressError::MemoryLimitExceeded { .. })) => {
log::warn!(
"form xobject {:?}: skipping — content stream exceeds {} decompressed bytes",
form_id,
super::content_decode::MAX_PAGE_CONTENT_BYTES
);
return extracted;
}
Err(_) if stream.content.len() > super::content_decode::MAX_PAGE_CONTENT_BYTES => {
log::warn!(
"form xobject {:?}: skipping — raw content stream exceeds {} bytes",
form_id,
super::content_decode::MAX_PAGE_CONTENT_BYTES
);
return extracted;
}
Err(_) => stream.content.clone(),
};
// Decode the content stream. Cap before lopdf materializes the operator
// vector — the walk budget cannot help if decode itself allocates first.
let Ok(Some(content)) = super::content_decode::decode_content_bounded(
&content_data,
super::content_decode::MAX_PAGE_OPERATIONS,
) else {
return extracted;
};
let items = &mut extracted.items;
let item_coverage = &mut extracted.item_coverage;
let rtl_visual_candidates = &mut extracted.rtl_visual_candidates;
let rtl_logical_runs = &mut extracted.rtl_logical_runs;
let rtl_visual_runs = &mut extracted.rtl_visual_runs;
let run_rotations = &mut extracted.run_rotations;
let skipped_invisible = &mut extracted.skipped_invisible;
// Get fonts from the Form's Resources
let form_fonts = get_form_fonts(doc, &stream.dict);
let paint_resources = PaintResources::form(doc, &stream.dict);
// Unknown font resources may be Type3; infer stroke weight only for
// positively resolved ordinary text fonts.
let paintable_fonts: std::collections::HashSet<String> = form_fonts
.iter()
.filter(|(_, font)| {
font.get(b"Subtype")
.ok()
.and_then(|o| o.as_name().ok())
.is_some_and(|subtype| {
matches!(subtype, b"Type0" | b"Type1" | b"MMType1" | b"TrueType")
})
})
.map(|(name, _)| String::from_utf8_lossy(name).into_owned())
.collect();
let (font_encodings, _has_gid_fonts) =
build_font_encodings(doc, &form_fonts, font_cmaps, style_cache);
// Build font width info for the form
let font_widths = build_font_widths(doc, &form_fonts, style_cache);
let type3_scales = build_type3_scales(doc, &form_fonts);
let type3_y_flips = build_type3_y_flips(doc, &form_fonts);
// Build font base names and ToUnicode refs for the form
let mut font_base_names: HashMap<String, String> = HashMap::new();
let mut font_tounicode_refs: HashMap<String, u32> = HashMap::new();
let mut inline_cmaps: HashMap<String, crate::tounicode::CMapEntry> = HashMap::new();
let mut font_styles: HashMap<String, FontStyle> = HashMap::new();
for (font_name, font_dict) in &form_fonts {
let resource_name = String::from_utf8_lossy(font_name).to_string();
if let Ok(base_font) = font_dict.get(b"BaseFont") {
if let Ok(name) = base_font.as_name() {
let base_name = String::from_utf8_lossy(name).to_string();
font_base_names.insert(resource_name.clone(), base_name);
}
}
// The name (the resource tag for a font without one) and the width
// table are read once here rather than for every run.
let style = font_style(doc, font_dict, style_cache)
.with_name(
font_base_names
.get(&resource_name)
.map_or(resource_name.as_str(), String::as_str),
)
.with_measured_pitch(font_widths.get(&resource_name));
if style != FontStyle::default() {
font_styles.insert(resource_name.clone(), style);
}
match font_dict.get(b"ToUnicode") {
Ok(tounicode) => {
if let Ok(obj_ref) = tounicode.as_reference() {
font_tounicode_refs.insert(resource_name, obj_ref.0);
} else if let Object::Stream(s) = tounicode {
let data = s
.decompressed_content()
.unwrap_or_else(|_| s.content.clone());
if let Some(entry) =
crate::tounicode::build_cmap_entry_from_stream(&data, font_dict, doc, 0)
{
inline_cmaps.insert(resource_name, entry);
}
}
}
Err(_) => {
if let Some(ff2_obj_num) = get_font_file2_obj_num(doc, font_dict) {
font_tounicode_refs.insert(resource_name, ff2_obj_num);
}
}
}
}
// Cache font encodings for form fonts
let mut encoding_cache: HashMap<String, Encoding<'_>> = HashMap::new();
for (font_name, font_dict) in &form_fonts {
let name = String::from_utf8_lossy(font_name).to_string();
if let Ok(enc) = font_dict.get_font_encoding(doc) {
encoding_cache.insert(name, enc);
}
}
// Build XObject map from the Form's own Resources for nested Do
let form_xobjects = get_form_xobjects(doc, &stream.dict);
// Apply the Form XObject's own Matrix (if any) to the parent CTM
let form_matrix = if let Ok(matrix_obj) = stream.dict.get(b"Matrix") {
if let Ok(arr) = matrix_obj.as_array() {
if arr.len() >= 6 {
let mut m = [1.0f32, 0.0, 0.0, 1.0, 0.0, 0.0];
for (i, v) in arr.iter().take(6).enumerate() {
m[i] = get_number(v).unwrap_or(if i == 0 || i == 3 { 1.0 } else { 0.0 });
}
m
} else {
[1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
}
} else {
[1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
}
} else {
[1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
};
let base_ctm = multiply_matrices(&form_matrix, parent_ctm);
// Process the content stream
let mut current_font = String::new();
let mut current_font_size: f32 = 12.0;
let mut text_matrix = [1.0f32, 0.0, 0.0, 1.0, 0.0, 0.0];
// Text line matrix (TLM) — Td/TD/T* move relative to the start of the
// current line, not to the position left by the last show operator.
let mut line_matrix = [1.0f32, 0.0, 0.0, 1.0, 0.0, 0.0];
let mut text_leading: f32 = 0.0; // TL parameter (text-space units)
let mut char_spacing: f32 = 0.0; // Tc parameter
let mut word_spacing: f32 = 0.0; // Tw parameter
// Ts parameter (baseline shift, unscaled). Text state is graphics state,
// so a form starts with the rise in force where it was invoked.
let mut horizontal_scale: f32 = inherited_horizontal_scale;
let mut pending_space: Option<PendingSpace> = None;
let mut pending_word_gaps: Option<PendingWordGaps> = None;
let mut text_rise: f32 = inherited_text_rise;
// Tr is graphics state, so a form starts in the mode the invoking stream
// left it in: `3 Tr` set on the page or in an outer form hides the text
// drawn here too.
let mut text_rendering_mode: i32 = inherited_render_mode;
let mut text_paint = inherited_text_paint;
let mut in_text_block = false;
// The fill colour is graphics state too: a form invoked under a white
// fill paints white until it sets its own colour.
let mut fill_is_white = inherited_fill_is_white;
let mut ctm = base_ctm;
// Text state (Tc/Tw/TL/Tf) and the fill colour are part of the graphics
// state and must be saved/restored by q/Q alongside the CTM.
#[derive(Clone)]
struct GraphicsState {
ctm: [f32; 6],
char_spacing: f32,
word_spacing: f32,
horizontal_scale: f32,
text_rise: f32,
text_rendering_mode: i32,
text_paint: TextPaint,
text_leading: f32,
current_font: String,
current_font_size: f32,
fill_is_white: bool,
}
let mut ctm_stack: Vec<GraphicsState> = Vec::new();
for op in &content.operations {
// The coverage of the preceding operator's decodes goes to the first
// item it appended (see `attach_run_coverage`).
attach_run_coverage(item_coverage, items.len(), || {
cmap_decisions.take_run_coverage()
});
if !budget.charge_operation() {
break;
}
text_paint.observe(&op.operator, &op.operands, &paint_resources);
match op.operator.as_str() {
"q" => {
ctm_stack.push(GraphicsState {
ctm,
char_spacing,
word_spacing,
horizontal_scale,
text_rise,
text_rendering_mode,
text_paint,
text_leading,
current_font: current_font.clone(),
current_font_size,
fill_is_white,
});
}
"Q" => {
if let Some(saved) = ctm_stack.pop() {
ctm = saved.ctm;
char_spacing = saved.char_spacing;
word_spacing = saved.word_spacing;
horizontal_scale = saved.horizontal_scale;
text_rise = saved.text_rise;
text_rendering_mode = saved.text_rendering_mode;
text_paint = saved.text_paint;
text_leading = saved.text_leading;
current_font = saved.current_font;
current_font_size = saved.current_font_size;
fill_is_white = saved.fill_is_white;
}
}
"cm" => {
if op.operands.len() >= 6 {
let mut m = [0.0f32; 6];
for (i, operand) in op.operands.iter().take(6).enumerate() {
m[i] = get_number(operand).unwrap_or(0.0);
}
ctm = multiply_matrices(&m, &ctm);
}
}
"Do" => {
// A nested form's runs belong to its own stream and never
// continue a wide-spaced boundary string of this one.
pending_word_gaps = None;
if !op.operands.is_empty() {
if let Ok(name) = op.operands[0].as_name() {
let xobj_name = String::from_utf8_lossy(name).to_string();
match form_xobjects.get(&xobj_name) {
Some(XObjectType::Form(nested_id)) => {
if depth < MAX_FORM_XOBJECT_DEPTH && !budget.exhausted() {
extract_form_xobject_text_inner(
doc,
*nested_id,
page_num,
font_cmaps,
&ctm,
include_invisible,
text_rendering_mode,
text_rise,
horizontal_scale,
text_paint,
fill_is_white,
cmap_decisions,
style_cache,
depth + 1,
budget,
)
.append_into(
items,
item_coverage,
rtl_visual_candidates,
rtl_logical_runs,
rtl_visual_runs,
run_rotations,
skipped_invisible,
);
}
}
Some(XObjectType::Image) => {
// Mirror the top-level Image-XObject emission
// in content_stream.rs so figures embedded
// inside Form XObjects (common in print-to-PDF
// workflows) aren't silently dropped.
let (x, y, width, height) = image_bbox_from_ctm(&ctm);
items.push(TextItem {
text: format!("[Image: {}]", xobj_name),
x,
y,
width,
height,
font: String::new(),
font_tag: String::new(),
legacy_symbol_rewrite: false,
font_size: 0.0,
page: page_num,
is_bold: false,
is_italic: false,
font_weight: None,
bold_source: None,
fixed_pitch: None,
is_underline: false,
is_strikeout: false,
rotation: 0.0,
advance_known: true,
item_type: ItemType::Image,
mcid: None,
baseline_shift: 0.0,
});
}
None => {}
}
}
}
}
"BT" => {
in_text_block = true;
text_matrix = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0];
line_matrix = text_matrix;
}
"ET" => {
in_text_block = false;
// A wide-spaced boundary string is continued within its text
// object; a later object's geometry is unrelated to it.
pending_word_gaps = None;
}
"Tf" => {
if op.operands.len() >= 2 {
if let Ok(name) = op.operands[0].as_name() {
current_font = String::from_utf8_lossy(name).to_string();
}
current_font_size = get_number(&op.operands[1]).unwrap_or(12.0);
}
}
"TL" => {
// Set text leading (used by T*, ', and ")
if let Some(tl) = op.operands.first().and_then(get_number) {
text_leading = tl;
}
}
"Tc" => {
if let Some(tc) = op.operands.first().and_then(get_number) {
char_spacing = tc;
}
}
"Tw" => {
if let Some(tw) = op.operands.first().and_then(get_number) {
word_spacing = tw;
}
}
"Tr" => {
// Text rendering mode (3 = invisible / OCR overlay). Hidden
// text is skipped exactly like the page parser skips it —
// it neither emits items nor votes on page rotation — unless
// the caller asked for the hidden layer.
if let Some(mode) = op.operands.first().and_then(get_number) {
text_rendering_mode = mode as i32;
}
}
"Tz" => {
if let Some(scale) = op.operands.first().and_then(get_number) {
if scale.is_finite() {
horizontal_scale = scale / 100.0;
}
}
}
"Ts" => {
// Text rise: baseline shift for superscripts/subscripts. It
// moves the glyph origin, never the advance (see
// `rise_adjusted`).
if let Some(ts) = op.operands.first().and_then(get_number) {
text_rise = ts;
}
}
"Td" | "TD" => {
// Move text position: TLM = T(tx,ty) x TLM; Tm = TLM
if op.operands.len() >= 2 {
let tx = get_number(&op.operands[0]).unwrap_or(0.0);
let ty = get_number(&op.operands[1]).unwrap_or(0.0);
line_matrix[4] += tx * line_matrix[0] + ty * line_matrix[2];
line_matrix[5] += tx * line_matrix[1] + ty * line_matrix[3];
text_matrix = line_matrix;
if op.operator == "TD" {
text_leading = -ty;
}
}
}
"Tm" => {
if op.operands.len() >= 6 {
for (i, operand) in op.operands.iter().take(6).enumerate() {
text_matrix[i] =
get_number(operand).unwrap_or(if i == 0 || i == 3 { 1.0 } else { 0.0 });
}
line_matrix = text_matrix;
}
}
"T*" => {
// Move to start of next line: equivalent to `0 -TL Td`
let tl = if text_leading != 0.0 {
text_leading
} else {
current_font_size * 1.2
};
line_matrix[4] += (-tl) * line_matrix[2];
line_matrix[5] += (-tl) * line_matrix[3];
text_matrix = line_matrix;
}
"g" => {
if let Some(gray) = op.operands.first().and_then(get_number) {
fill_is_white = gray > 0.95;
}
}
"rg" => {
if op.operands.len() >= 3 {
let r = get_number(&op.operands[0]).unwrap_or(0.0);
let g = get_number(&op.operands[1]).unwrap_or(0.0);
let b = get_number(&op.operands[2]).unwrap_or(0.0);
fill_is_white = r > 0.95 && g > 0.95 && b > 0.95;
}
}
"k" => {
if op.operands.len() >= 4 {
let c = get_number(&op.operands[0]).unwrap_or(1.0);
let m = get_number(&op.operands[1]).unwrap_or(1.0);
let y = get_number(&op.operands[2]).unwrap_or(1.0);
let k = get_number(&op.operands[3]).unwrap_or(1.0);
fill_is_white = c < 0.05 && m < 0.05 && y < 0.05 && k < 0.05;
}
}
"sc" | "scn" => {
let nums: Vec<f32> = op.operands.iter().filter_map(get_number).collect();
match nums.len() {
3 => {
fill_is_white = nums[0] > 0.95 && nums[1] > 0.95 && nums[2] > 0.95;
}
4 => {
fill_is_white =
nums[0] < 0.05 && nums[1] < 0.05 && nums[2] < 0.05 && nums[3] < 0.05;
}
_ => fill_is_white = false,
}
}
"Tj" | "'" | "\"" => {
// `'` = move to next line then show; `"` = set word/char spacing,
// move to next line, then show (string is the last operand).
if op.operator != "Tj" {
if op.operator == "\"" && op.operands.len() >= 3 {
word_spacing = get_number(&op.operands[0]).unwrap_or(word_spacing);
char_spacing = get_number(&op.operands[1]).unwrap_or(char_spacing);
}
let tl = if text_leading != 0.0 {
text_leading
} else {
current_font_size * 1.2
};
line_matrix[4] += (-tl) * line_matrix[2];
line_matrix[5] += (-tl) * line_matrix[3];
text_matrix = line_matrix;
}
if let (true, Some(show_operand)) = (in_text_block, op.operands.last()) {
// Where this run starts says whether the run before it, a
// wide-spaced boundary string, had its spacing taken back.
// An empty show paints nothing and decides nothing.
if get_operand_bytes(show_operand).is_some_and(|raw| !raw.is_empty()) {
if let Some(pending) = pending_word_gaps.take() {
pending.resolve(items, &text_matrix, &ctm);
}
}
let invisible = text_rendering_mode == 3 && !include_invisible;
if invisible
&& get_operand_bytes(show_operand).is_some_and(|raw| !raw.is_empty())
{
*skipped_invisible = true;
}
if crate::text_utils::white_fill_hides(text_rendering_mode, fill_is_white)
|| invisible
{
if let Some(font_info) = font_widths.get(¤t_font) {
if let Some(raw_bytes) = get_operand_bytes(show_operand) {
let w_ts = compute_string_width_ts(
raw_bytes,
font_info,
current_font_size,
char_spacing,
word_spacing,
);
text_matrix[4] += w_ts * horizontal_scale * text_matrix[0];
text_matrix[5] += w_ts * horizontal_scale * text_matrix[1];
}
} else {
// No width metrics: move by the estimate the run
// would have carried, as the page parser does.
let estimate_ts = estimated_string_advance_ts(
get_operand_bytes(show_operand),
None,
current_font_size
* type3_scales.get(¤t_font).copied().unwrap_or(1.0),
char_spacing,
word_spacing,
);
text_matrix[4] += estimate_ts * horizontal_scale * text_matrix[0];
text_matrix[5] += estimate_ts * horizontal_scale * text_matrix[1];
}
continue;
}
if let Some((text, legacy_symbol_rewrite)) = extract_text_from_operand(
show_operand,
¤t_font,
font_base_names.get(¤t_font).map(|s| s.as_str()),
font_cmaps,
&font_tounicode_refs,
&inline_cmaps,
&font_encodings,
&encoding_cache,
cmap_decisions,
&font_widths,
) {
let combined =
multiply_matrices(&rise_adjusted(&text_matrix, text_rise), &ctm);
let rendered_size = effective_font_size(current_font_size, &combined)
* type3_scales.get(¤t_font).copied().unwrap_or(1.0);
let advance_ts = font_widths.get(¤t_font).and_then(|font_info| {
get_operand_bytes(show_operand).map(|raw_bytes| {
compute_string_width_ts(
raw_bytes,
font_info,
current_font_size,
char_spacing,
word_spacing,
)
})
});
let em_ts = current_font_size
* type3_scales.get(¤t_font).copied().unwrap_or(1.0);
let raw = get_operand_bytes(show_operand);
let fallback_ts = if raw.is_some_and(|bytes| !bytes.is_empty()) {
estimated_string_advance_ts(
raw,
font_widths.get(¤t_font),
em_ts,
char_spacing,
word_spacing,
)
} else {
estimated_advance_ts(&text, em_ts)
};
let geometry = scaled_run_geometry(
&combined,
advance_ts,
fallback_ts,
rendered_size.copysign(current_font_size),
type3_y_flips.contains(¤t_font),
horizontal_scale,
);
// Without width metrics the cursor moves by the same
// estimate the run's box carries.
let cursor_ts = advance_ts.unwrap_or(fallback_ts);
text_matrix[4] += cursor_ts * horizontal_scale * text_matrix[0];
text_matrix[5] += cursor_ts * horizontal_scale * text_matrix[1];
// Only create text item for non-whitespace; whitespace
// still advances the text matrix above so gap detection
// works, and a space run hands its word space to the
// item it follows.
if text.trim().is_empty() {
pending_space = PendingSpace::note(
pending_space.take(),
items,
&geometry,
page_num,
);
} else {
if let Some(pending) = pending_space.take() {
pending.resolve(items, &geometry, &text, rendered_size);
}
let (dir_x, dir_y) =
reading_direction(&combined, current_font_size * horizontal_scale);
run_rotations.push(baseline_rotation(dir_x, dir_y));
let base_font = font_base_names
.get(¤t_font)
.map(|s| s.as_str())
.unwrap_or(¤t_font);
let style = font_styles.get(¤t_font).copied().unwrap_or_default();
// Forward paint order (positive device-space
// advance) may be visual storage; a mirrored
// matrix already paints right-to-left. Rotated
// matrices carry no horizontal evidence and stay
// neutral.
if crate::text_utils::is_visual_rtl_candidate(&text)
&& combined[0].abs() > combined[1].abs()
{
if combined[0] * horizontal_scale > 0.0 {
rtl_visual_candidates.push(items.len());
if !crate::text_utils::white_fill_hides(
text_rendering_mode,
fill_is_white,
) && crate::text_utils::render_mode_paints(
text_rendering_mode,
) && crate::text_utils::is_visual_rtl_run(&text)
{
rtl_visual_runs.push(items.len());
}
} else {
rtl_logical_runs.push(items.len());
}
}
let painted_bold = paintable_fonts.contains(¤t_font)
&& text_paint.adds_bold(&text, rendered_size, base_font, &ctm);
items.push(TextItem {
text: expand_ligatures(&text),
x: geometry.x,
y: geometry.y,
width: geometry.width,
height: geometry.height,
font: crate::extractor::fonts::item_font_name(
¤t_font,
base_font,
)
.to_string(),
font_tag: current_font.clone(),
legacy_symbol_rewrite,
font_size: rendered_size,
page: page_num,
is_bold: style.bold || painted_bold,
is_italic: style.italic,
font_weight: style.weight,
bold_source: style
.bold_source
.or(painted_bold.then_some(BoldSource::Painted)),
fixed_pitch: style.fixed_pitch,
is_underline: false,
is_strikeout: false,
rotation: geometry.rotation,
advance_known: geometry.advance_known,
item_type: ItemType::Text,
mcid: None,
baseline_shift: 0.0,
});
// A short string with word-gap character spacing
// shows its spaces once the next run proves the
// spacing after it was taken back (see `word_gaps`).
pending_word_gaps = get_operand_bytes(show_operand).and_then(|raw| {
PendingWordGaps::for_shown_string(
items.len() - 1,
raw,
&text,
font_widths.get(¤t_font),
current_font_size,
char_spacing,
word_spacing,
&text_matrix,
&ctm,
horizontal_scale,
|code| {
cmap_decisions.without_coverage(|decisions| {
extract_text_from_operand(
code,
¤t_font,
font_base_names
.get(¤t_font)
.map(|s| s.as_str()),
font_cmaps,
&font_tounicode_refs,
&inline_cmaps,
&font_encodings,
&encoding_cache,
decisions,
&font_widths,
)
})
},
)
});
}
}
}
}
"TJ" => {
// Show text with positioning — split at column-sized gaps
if in_text_block && !op.operands.is_empty() {
if let Ok(array) = op.operands[0].as_array() {
// Invisible (Tr 3) text is hidden like white-on-white
// text: it advances the pen but shows nothing and
// must not vote on page rotation. Numeric-only arrays
// (pure kerning) show no text and must not trigger
// the invisible retry.
let invisible = text_rendering_mode == 3 && !include_invisible;
if invisible
&& array
.iter()
.any(|el| get_operand_bytes(el).is_some_and(|raw| !raw.is_empty()))
{
*skipped_invisible = true;
}
let hidden =
crate::text_utils::white_fill_hides(text_rendering_mode, fill_is_white)
|| invisible;
let font_info = font_widths.get(¤t_font);
// Word-space threshold for `TJ` offsets and character
// spacing alike, from the font metrics when available.
let space_threshold = word_gap_threshold(font_info);
// A tracked display run is judged over its own
// tracking, as on the page (see `tj_tracking` and
// `tj_gap_thresholds`); a hidden run is not read
// for it, and the reader decodes the glyphs of a run
// in the tracking band on a copy of the CMap
// decisions.
let tracking = if hidden {
None
} else {
let mut probe_decisions: Option<CMapDecisionCache> = None;
tj_tracking(array, font_info, space_threshold, |element| {
extract_text_from_operand(
element,
¤t_font,
font_base_names.get(¤t_font).map(|s| s.as_str()),
font_cmaps,
&font_tounicode_refs,
&inline_cmaps,
&font_encodings,
&encoding_cache,
probe_decisions.get_or_insert_with(|| cmap_decisions.clone()),
&font_widths,
)
})
};
let baseline_horizontal = {
let combined = multiply_matrices(&text_matrix, &ctm);
combined[0].abs() >= combined[1].abs()
};
let (word_gap, split_gap) =
tj_gap_thresholds(space_threshold, tracking, baseline_horizontal);
let mut sub_items: Vec<(String, f32, f32, f32, bool)> = Vec::new();
let mut current_text = String::new();
let mut current_symbol_rewrite = false;
let mut current_estimate_ts: f32 = 0.0; // metric-less estimate of `current_text`
let mut sub_start_width_ts: f32 = 0.0;
let mut total_width_ts: f32 = 0.0;
// A sub-run's box starts at its first painted glyph.
// Positioning ahead of that glyph — `[-2973 (oduction)]
// TJ` rejoining a word whose head was painted first
// from another `Tm` — carries the pen from the `Tm`
// origin, not the box.
let mut sub_run_painted = false;
// Positive TJ offsets beyond a space width move the pen
// backward past painted glyphs — logical-order RTL
// producers position runs right-to-left this way.
let mut backward_jump = false;
// The farthest the pen has been, for a return from a
// zero-advance sign placed behind it: no gap opens on
// the page until the pen is past the mark again (see
// `PenHighWater`).
let mut pen_high_water = PenHighWater::new();
// The array's last string, when it is a wide-spaced
// boundary string, and the sub-run text before it.
let mut deferred_word_gaps: Option<(String, WordGapCandidate)> = None;
// Only positioning may follow the array's last string;
// the next run decides for a candidate there.
let last_string_index = array.iter().rposition(|el| {
get_operand_bytes(el).is_some_and(|raw| !raw.is_empty())
});
for (index, element) in array.iter().enumerate() {
match element {
Object::Integer(n) => {
let n_val = *n as f32;
let displacement = -n_val / 1000.0 * current_font_size;
// The offset as the thresholds judge it:
// itself, or on a return from a sign placed
// behind the high-water mark only the
// travel beyond the mark.
let judged = pen_high_water.judge_offset(
n_val,
total_width_ts,
total_width_ts + displacement,
current_font_size,
);
// A true backtrack puts the pen behind the
// current segment's start — plain positive
// kerning never does.
if n_val > space_threshold
&& !current_text.is_empty()
&& total_width_ts + displacement < sub_start_width_ts
{
backward_jump = true;
}
if !hidden && judged < -split_gap && !current_text.is_empty() {
sub_items.push((
std::mem::take(&mut current_text),
sub_start_width_ts,
total_width_ts,
std::mem::take(&mut current_estimate_ts),
std::mem::take(&mut current_symbol_rewrite),
));
total_width_ts += displacement;
sub_start_width_ts = total_width_ts;
sub_run_painted = false;
} else {
total_width_ts += displacement;
if !hidden
&& judged < -word_gap
&& !current_text.is_empty()
&& !current_text.ends_with(' ')
{
current_text.push(' ');
}
}
continue;
}
Object::Real(n) => {
let n_val = *n;
let displacement = -n_val / 1000.0 * current_font_size;
// The offset as the thresholds judge it:
// itself, or on a return from a sign placed
// behind the high-water mark only the
// travel beyond the mark.
let judged = pen_high_water.judge_offset(
n_val,
total_width_ts,
total_width_ts + displacement,
current_font_size,
);
// A true backtrack puts the pen behind the
// current segment's start — plain positive
// kerning never does.
if n_val > space_threshold
&& !current_text.is_empty()
&& total_width_ts + displacement < sub_start_width_ts
{
backward_jump = true;
}
if !hidden && judged < -split_gap && !current_text.is_empty() {
sub_items.push((
std::mem::take(&mut current_text),
sub_start_width_ts,
total_width_ts,
std::mem::take(&mut current_estimate_ts),
std::mem::take(&mut current_symbol_rewrite),
));
total_width_ts += displacement;
sub_start_width_ts = total_width_ts;
sub_run_painted = false;
} else {
total_width_ts += displacement;
if !hidden
&& judged < -word_gap
&& !current_text.is_empty()
&& !current_text.ends_with(' ')
{
current_text.push(' ');
}
}
continue;
}
_ => {}
}
if !sub_run_painted
&& get_operand_bytes(element).is_some_and(|raw| !raw.is_empty())
{
sub_start_width_ts = total_width_ts;
sub_run_painted = true;
if let Some(pending) = pending_word_gaps.take() {
pending.resolve(
items,
&advanced_tm(
&text_matrix,
total_width_ts,
horizontal_scale,
),
&ctm,
);
}
}
if let Some(fi) = font_info {
if let Some(raw_bytes) = get_operand_bytes(element) {
total_width_ts += compute_string_width_ts(
raw_bytes,
fi,
current_font_size,
char_spacing,
word_spacing,
);
}
} else {
// No width metrics: the cursor moves by the
// estimate the sub-run's box will carry.
let element_estimate_ts = estimated_string_advance_ts(
get_operand_bytes(element),
None,
current_font_size
* type3_scales.get(¤t_font).copied().unwrap_or(1.0),
char_spacing,
word_spacing,
);
total_width_ts += element_estimate_ts;
current_estimate_ts += element_estimate_ts;
}
if let Some(raw) =
get_operand_bytes(element).filter(|raw| !raw.is_empty())
{
pen_high_water
.painted(total_width_ts, is_dependent_sign(raw, font_info));
}
if !hidden {
if let Some((text, legacy_symbol_rewrite)) =
extract_text_from_operand(
element,
¤t_font,
font_base_names.get(¤t_font).map(|s| s.as_str()),
font_cmaps,
&font_tounicode_refs,
&inline_cmaps,
&font_encodings,
&encoding_cache,
cmap_decisions,
&font_widths,
)
{
// A short string with word-gap character
// spacing shows its spaces once the spacing
// after it is taken back: by the positive
// offset that follows it here, or — for the
// array's last string — by where the next
// run starts (see `word_gaps`).
let candidate = get_operand_bytes(element).and_then(|raw| {
word_gap_candidate(
raw,
&text,
font_info,
current_font_size,
char_spacing,
word_spacing,
space_threshold,
|code| {
cmap_decisions.without_coverage(|decisions| {
extract_text_from_operand(
code,
¤t_font,
font_base_names
.get(¤t_font)
.map(|s| s.as_str()),
font_cmaps,
&font_tounicode_refs,
&inline_cmaps,
&font_encodings,
&encoding_cache,
decisions,
&font_widths,
)
})
},
)
});
let strings_follow =
last_string_index.is_some_and(|last| index < last);
let text = match (candidate, array.get(index + 1)) {
(Some(candidate), Some(next))
if offset_takes_spacing_back(
next,
candidate.trailing_spacing_ts,
current_font_size,
) =>
{
candidate.spaced_text
}
(Some(candidate), _) if !strings_follow => {
deferred_word_gaps =
Some((current_text.clone(), candidate));
text
}
_ => text,
};
current_text.push_str(&text);
current_symbol_rewrite |= legacy_symbol_rewrite;
}
}
}
if !hidden && !current_text.trim().is_empty() {
sub_items.push((
current_text,
sub_start_width_ts,
total_width_ts,
current_estimate_ts,
current_symbol_rewrite,
));
} else if !hidden && sub_items.is_empty() && !current_text.is_empty() {
// A whitespace-only array is a space run like a
// whitespace-only `Tj`: it may be the word space
// of the item before it.
let offset_tm =
advanced_tm(&text_matrix, sub_start_width_ts, horizontal_scale);
let combined =
multiply_matrices(&rise_adjusted(&offset_tm, text_rise), &ctm);
let rendered_size = effective_font_size(current_font_size, &combined)
* type3_scales.get(¤t_font).copied().unwrap_or(1.0);
let geometry = scaled_run_geometry(
&combined,
font_info.map(|_| total_width_ts - sub_start_width_ts),
current_estimate_ts,
rendered_size.copysign(current_font_size),
type3_y_flips.contains(¤t_font),
horizontal_scale,
);
pending_space = PendingSpace::note(
pending_space.take(),
items,
&geometry,
page_num,
);
}
if !sub_items.is_empty() {
let combined = multiply_matrices(&text_matrix, &ctm);
let (dir_x, dir_y) =
reading_direction(&combined, current_font_size * horizontal_scale);
run_rotations.push(baseline_rotation(dir_x, dir_y));
let rendered_size = effective_font_size(current_font_size, &combined)
* type3_scales.get(¤t_font).copied().unwrap_or(1.0);
let base_font = font_base_names
.get(¤t_font)
.map(|s| s.as_str())
.unwrap_or(¤t_font);
let style = font_styles.get(¤t_font).copied().unwrap_or_default();
let scale_x = (text_matrix[0] * ctm[0] + text_matrix[1] * ctm[2])
* horizontal_scale;
// Rotated matrices carry no horizontal evidence:
// stay neutral unless the advance is x-dominant.
let scale_y = (text_matrix[0] * ctm[1] + text_matrix[1] * ctm[3])
* horizontal_scale;
let horizontal_advance = scale_x.abs() > scale_y.abs();
// The op-wide backtrack marker votes once per op —
// per-sub-run geometry (mirrored matrices) still
// votes per sub-run, symmetric with candidates.
let mut op_backtrack_voted = false;
for (text, start_w, end_w, estimate_ts, legacy_symbol_rewrite) in
&sub_items
{
let offset_tm =
advanced_tm(&text_matrix, *start_w, horizontal_scale);
let combined_mat =
multiply_matrices(&rise_adjusted(&offset_tm, text_rise), &ctm);
let geometry = scaled_run_geometry(
&combined_mat,
font_info.map(|_| end_w - start_w),
// A measured sub-run's advance is the `Some`
// above and this fallback goes unused. Without
// metrics the accumulated width IS the sub-run's
// estimate, kerning included — signed, since a
// negative `Tf` size reads backwards; if kerning
// walked it past zero the painted codes' own
// estimate stands.
if font_info.is_some()
|| (end_w - start_w != 0.0
&& ((end_w - start_w > 0.0) == (*estimate_ts > 0.0)))
{
end_w - start_w
} else if *estimate_ts != 0.0 {
*estimate_ts
} else {
estimated_advance_ts(
text,
current_font_size
* type3_scales
.get(¤t_font)
.copied()
.unwrap_or(1.0),
)
},
rendered_size.copysign(current_font_size),
type3_y_flips.contains(¤t_font),
horizontal_scale,
);
if horizontal_advance
&& crate::text_utils::is_visual_rtl_candidate(text)
{
if scale_x < 0.0 {
rtl_logical_runs.push(items.len());
} else if backward_jump {
if !op_backtrack_voted {
rtl_logical_runs.push(items.len());
op_backtrack_voted = true;
}
} else {
rtl_visual_candidates.push(items.len());
if !hidden
&& crate::text_utils::render_mode_paints(
text_rendering_mode,
)
&& crate::text_utils::is_visual_rtl_run(text)
{
rtl_visual_runs.push(items.len());
}
}
}
if let Some(pending) = pending_space.take() {
pending.resolve(items, &geometry, text, rendered_size);
}
let painted_bold = paintable_fonts.contains(¤t_font)
&& text_paint.adds_bold(text, rendered_size, base_font, &ctm);
items.push(TextItem {
text: expand_ligatures(text),
x: geometry.x,
y: geometry.y,
width: geometry.width,
height: geometry.height,
font: crate::extractor::fonts::item_font_name(
¤t_font,
base_font,
)
.to_string(),
font_tag: current_font.clone(),
legacy_symbol_rewrite: *legacy_symbol_rewrite,
font_size: rendered_size,
page: page_num,
is_bold: style.bold || painted_bold,
is_italic: style.italic,
font_weight: style.weight,
bold_source: style
.bold_source
.or(painted_bold.then_some(BoldSource::Painted)),
fixed_pitch: style.fixed_pitch,
is_underline: false,
is_strikeout: false,
rotation: geometry.rotation,
advance_known: geometry.advance_known,
item_type: ItemType::Text,
mcid: None,
baseline_shift: 0.0,
});
}
}
// Always advance the text matrix by the total width —
// measured, or estimated for a font without metrics.
text_matrix[4] += total_width_ts * horizontal_scale * text_matrix[0];
text_matrix[5] += total_width_ts * horizontal_scale * text_matrix[1];
// The array's last string was a candidate: the next
// run decides, against the pen it left.
if let Some((prefix, candidate)) = deferred_word_gaps {
if !sub_items.is_empty() {
pending_word_gaps = Some(PendingWordGaps::new(
items.len() - 1,
expand_ligatures(&format!("{prefix}{}", candidate.spaced_text)),
&text_matrix,
&ctm,
horizontal_scale,
candidate.trailing_spacing_ts,
current_font_size,
));
}
}
}
}
}
_ => {}
}
}
// Coverage no item of the form followed stays waiting for the page's
// next item, or for the page's end (see `attach_run_coverage`).
attach_run_coverage(item_coverage, items.len(), || {
cmap_decisions.take_run_coverage()
});
extracted
}
/// Get fonts from a Form XObject's Resources
pub(crate) fn get_form_fonts<'a>(
doc: &'a Document,
form_dict: &'a lopdf::Dictionary,
) -> std::collections::BTreeMap<Vec<u8>, &'a lopdf::Dictionary> {
let mut fonts = std::collections::BTreeMap::new();
// Get Resources from Form dictionary
let resources = if let Ok(res_ref) = form_dict.get(b"Resources") {
if let Ok(obj_ref) = res_ref.as_reference() {
doc.get_dictionary(obj_ref).ok()
} else {
res_ref.as_dict().ok()
}
} else {
return fonts;
};
let Some(resources) = resources else {
return fonts;
};
// Get Font dictionary
let font_dict = if let Ok(font_ref) = resources.get(b"Font") {
if let Ok(obj_ref) = font_ref.as_reference() {
doc.get_dictionary(obj_ref).ok()
} else {
font_ref.as_dict().ok()
}
} else {
return fonts;
};
let Some(font_dict) = font_dict else {
return fonts;
};
// Collect fonts
for (name, value) in font_dict.iter() {
let dict = match value {
Object::Reference(id) => doc.get_dictionary(*id).ok(),
Object::Dictionary(dict) => Some(dict),
_ => None,
};
if let Some(dict) = dict {
fonts.insert(name.clone(), dict);
}
}
fonts
}
#[cfg(test)]
mod tests {
use super::*;
use crate::extractor::content_stream::extract_page_text_items;
use lopdf::{dictionary, Dictionary, Stream};
/// Build an acyclic Form XObject DAG: `levels` form objects, each non-leaf
/// invoking the next form `branches` times. The leaf draws a single `(X)`.
/// Returns `(doc, root_form_id)`.
fn form_dag(branches: usize, levels: usize) -> (Document, ObjectId) {
assert!(levels >= 2);
let mut doc = Document::new();
let font_id = doc.add_object(dictionary! {
"Type" => "Font",
"Subtype" => "Type1",
"BaseFont" => "Helvetica",
});
let ids: Vec<ObjectId> = (0..levels).map(|_| doc.new_object_id()).collect();
for level in 0..levels {
let stream = if level + 1 == levels {
Stream::new(
dictionary! {
"Type" => "XObject",
"Subtype" => "Form",
"BBox" => vec![0.into(), 0.into(), 100.into(), 100.into()],
"Resources" => dictionary! {
"Font" => dictionary! {
"F1" => Object::Reference(font_id),
},
},
},
b"BT /F1 10 Tf 10 10 Td (X) Tj ET\n".to_vec(),
)
} else {
let next_name = format!("Fm{}", level + 1);
let content = format!("/{next_name} Do\n").repeat(branches);
let mut xobjects = Dictionary::new();
xobjects.set(next_name, Object::Reference(ids[level + 1]));
let mut resources = Dictionary::new();
resources.set("XObject", Object::Dictionary(xobjects));
let mut dict = dictionary! {
"Type" => "XObject",
"Subtype" => "Form",
"BBox" => vec![0.into(), 0.into(), 100.into(), 100.into()],
};
dict.set("Resources", Object::Dictionary(resources));
Stream::new(dict, content.into_bytes())
};
doc.set_object(ids[level], Object::Stream(stream));
}
(doc, ids[0])
}
fn page_invoking_form(mut doc: Document, form_id: ObjectId) -> (Document, ObjectId) {
let content_id = doc.add_object(Object::Stream(Stream::new(
dictionary! {},
b"/Fm0 Do\n".to_vec(),
)));
let page_id = doc.add_object(dictionary! {
"Type" => "Page",
"Contents" => Object::Reference(content_id),
"Resources" => dictionary! {
"XObject" => dictionary! {
"Fm0" => Object::Reference(form_id),
},
},
"MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()],
});
let pages_id = doc.add_object(dictionary! {
"Type" => "Pages",
"Count" => Object::Integer(1),
"Kids" => vec![Object::Reference(page_id)],
});
let catalog_id = doc.add_object(dictionary! {
"Type" => "Catalog",
"Pages" => Object::Reference(pages_id),
});
doc.trailer.set("Root", Object::Reference(catalog_id));
(doc, page_id)
}
fn extract_form(
doc: &Document,
form_id: ObjectId,
budget: &mut FormWalkBudget,
) -> Vec<TextItem> {
extract_form_xobject_text(
doc,
form_id,
1,
&FontCMaps::from_doc(doc),
&[1.0, 0.0, 0.0, 1.0, 0.0, 0.0],
false,
0,
0.0,
1.0,
TextPaint::default(),
false,
&mut CMapDecisionCache::new(),
&mut FontStyleCache::new(),
budget,
)
.items
}
#[test]
fn nested_form_still_extracts_leaf_text() {
let (doc, root) = form_dag(1, 3);
let items = extract_form(&doc, root, &mut FormWalkBudget::new());
assert_eq!(items.len(), 1);
assert_eq!(items[0].text, "X");
}
#[test]
fn form_items_carry_family_name_and_resource_tag() {
// Parity with content_stream.rs: `font` is the /BaseFont family
// name, `font_tag` the raw resource tag, in both parsers.
let (doc, root) = form_dag(1, 2);
let items = extract_form(&doc, root, &mut FormWalkBudget::new());
assert_eq!(items.len(), 1);
assert_eq!(items[0].font, "Helvetica");
assert_eq!(items[0].font_tag, "F1");
}
#[test]
fn acyclic_form_dag_within_budget_keeps_all_leaves() {
// 4 sibling invocations across 4 nested levels → 4^4 leaf drawings.
// Default budgets are far above 256, so legitimate nesting is intact.
let (doc, root) = form_dag(4, 5);
let items = extract_form(&doc, root, &mut FormWalkBudget::new());
assert_eq!(items.len(), 4usize.pow(4));
assert!(items.iter().all(|item| item.text == "X"));
}
#[test]
fn acyclic_form_dag_stops_at_invocation_budget() {
// Same DAG as above would draw 256 leaves; a tiny invocation cap must
// stop expansion rather than walking the full tree.
let (doc, root) = form_dag(4, 5);
let mut budget = FormWalkBudget::with_limits(20, MAX_FORM_XOBJECT_OPERATIONS);
let items = extract_form(&doc, root, &mut budget);
assert!(
items.len() < 4usize.pow(4),
"invocation budget must truncate DAG expansion; got {} items",
items.len()
);
assert!(budget.was_truncated());
}
#[test]
fn form_operations_stop_at_budget() {
let mut doc = Document::new();
let font_id = doc.add_object(dictionary! {
"Type" => "Font",
"Subtype" => "Type1",
"BaseFont" => "Helvetica",
});
let mut content = b"q Q\n".repeat(50);
content.extend_from_slice(b"BT /F1 10 Tf 10 10 Td (X) Tj ET\n");
let form_id = doc.add_object(Object::Stream(Stream::new(
dictionary! {
"Type" => "XObject",
"Subtype" => "Form",
"BBox" => vec![0.into(), 0.into(), 100.into(), 100.into()],
"Resources" => dictionary! {
"Font" => dictionary! {
"F1" => Object::Reference(font_id),
},
},
},
content,
)));
let mut budget = FormWalkBudget::with_limits(MAX_FORM_XOBJECT_INVOCATIONS, 10);
let items = extract_form(&doc, form_id, &mut budget);
assert!(
items.is_empty(),
"operation budget must stop before the trailing text show"
);
assert!(budget.was_truncated());
}
#[test]
fn page_level_form_dag_stays_within_production_budget() {
// A page-level `/Do` of an 8-wide, 6-level Form DAG would expand to
// 8^5 = 32_768 leaf drawings without a budget. The production
// invocation cap must keep extraction bounded.
let (doc, root) = form_dag(8, 6);
let (doc, page_id) = page_invoking_form(doc, root);
let font_cmaps = FontCMaps::from_doc(&doc);
let ((items, _, _), _, _, _) = extract_page_text_items(
&doc,
page_id,
1,
&font_cmaps,
false,
&mut FontStyleCache::new(),
&mut FormWalkBudget::new(),
)
.unwrap();
assert!(
items.len() <= MAX_FORM_XOBJECT_INVOCATIONS,
"page-level Form expansion must stay within the invocation cap; got {}",
items.len()
);
assert!(
!items.is_empty(),
"budget must still allow some nested form text through"
);
}
#[test]
fn shared_form_budget_spans_two_extraction_passes() {
// The invisible-layer retry calls extract_page_text_items twice for
// the same page; both passes must share one budget.
let (doc, root) = form_dag(1, 2);
let (doc, page_id) = page_invoking_form(doc, root);
let font_cmaps = FontCMaps::from_doc(&doc);
// Root + leaf = 2 invocations on the first pass.
let mut budget = FormWalkBudget::with_limits(2, MAX_FORM_XOBJECT_OPERATIONS);
let ((first, _, _), _, _, _) = extract_page_text_items(
&doc,
page_id,
1,
&font_cmaps,
false,
&mut FontStyleCache::new(),
&mut budget,
)
.unwrap();
assert_eq!(first.iter().filter(|item| item.text == "X").count(), 1);
assert!(!budget.was_truncated());
let ((second, _, _), _, _, _) = extract_page_text_items(
&doc,
page_id,
1,
&font_cmaps,
true,
&mut FontStyleCache::new(),
&mut budget,
)
.unwrap();
assert!(
second.iter().all(|item| item.text != "X"),
"second pass must not get a fresh invocation budget"
);
assert!(budget.was_truncated());
}
/// Build a document whose page draws *all* of its content through a single
/// Form XObject — the shape emitted by print-to-PDF producers like PDFlib,
/// where the page stream itself is only `q /X1 Do Q`.
fn doc_with_form_content(form_content: &[u8]) -> (Document, ObjectId) {
doc_with_page_and_forms(b"q /X1 Do Q", &[form_content])
}
/// A page drawing `page_content` with forms `X1`, `X2`, … available to
/// the page and to each other (so a form can invoke a nested form).
fn doc_with_page_and_forms(page_content: &[u8], forms: &[&[u8]]) -> (Document, ObjectId) {
let mut doc = Document::new();
let widths: Vec<Object> = (0..=255).map(|_| 600.into()).collect();
let font_id = doc.add_object(dictionary! {
"Type" => "Font",
"Subtype" => "Type1",
"BaseFont" => "Helvetica",
"FirstChar" => 0,
"LastChar" => 255,
"Widths" => Object::Array(widths),
});
let form_ids: Vec<ObjectId> = forms.iter().map(|_| doc.new_object_id()).collect();
let xobjects = || {
let mut dict = lopdf::Dictionary::new();
for (index, id) in form_ids.iter().enumerate() {
dict.set(format!("X{}", index + 1), Object::Reference(*id));
}
dict
};
for (id, content) in form_ids.iter().zip(forms) {
doc.set_object(
*id,
Object::Stream(Stream::new(
dictionary! {
"Type" => "XObject",
"Subtype" => "Form",
"BBox" => vec![0.into(), 0.into(), 612.into(), 792.into()],
"Resources" => dictionary! {
"Font" => dictionary! { "F1" => Object::Reference(font_id) },
"XObject" => xobjects(),
},
},
content.to_vec(),
)),
);
}
let content_id = doc.add_object(Object::Stream(Stream::new(
dictionary! {},
page_content.to_vec(),
)));
let page_id = doc.add_object(dictionary! {
"Type" => "Page",
"Contents" => Object::Reference(content_id),
"Resources" => dictionary! {
"Font" => dictionary! { "F1" => Object::Reference(font_id) },
"XObject" => xobjects(),
},
"MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()],
});
let pages_id = doc.add_object(dictionary! {
"Type" => "Pages",
"Count" => Object::Integer(1),
"Kids" => vec![Object::Reference(page_id)],
});
let catalog_id = doc.add_object(dictionary! {
"Type" => "Catalog",
"Pages" => Object::Reference(pages_id),
});
doc.trailer.set("Root", Object::Reference(catalog_id));
(doc, page_id)
}
fn form_items(form_content: &[u8]) -> Vec<TextItem> {
let (doc, page_id) = doc_with_form_content(form_content);
let font_cmaps = FontCMaps::from_doc(&doc);
let ((items, _, _), _, _, _) = extract_page_text_items(
&doc,
page_id,
1,
&font_cmaps,
false,
&mut FontStyleCache::new(),
&mut FormWalkBudget::new(),
)
.unwrap();
items
}
fn find<'a>(items: &'a [TextItem], text: &str) -> &'a TextItem {
items
.iter()
.find(|item| item.text == text)
.unwrap_or_else(|| {
let found: Vec<&String> = items.iter().map(|i| &i.text).collect();
panic!("no item {text:?} in {found:?}")
})
}
/// A form whose content is over the page-content bound is skipped, as
/// a page over it is; the forms invoked beside it are still read.
#[test]
fn form_content_over_the_byte_bound_is_skipped() {
let mut oversized = b"BT /F1 12 Tf 72 700 Td (lost) Tj ET".to_vec();
oversized.resize(
crate::extractor::content_decode::MAX_PAGE_CONTENT_BYTES + 1,
b' ',
);
let (doc, page_id) = doc_with_page_and_forms(
b"q /X1 Do Q q /X2 Do Q",
&[&oversized, b"BT /F1 12 Tf 72 600 Td (kept) Tj ET"],
);
let font_cmaps = FontCMaps::from_doc(&doc);
let ((items, _, _), _, _, _) = extract_page_text_items(
&doc,
page_id,
1,
&font_cmaps,
false,
&mut FontStyleCache::new(),
&mut FormWalkBudget::new(),
)
.unwrap();
let texts: Vec<&str> = items.iter().map(|item| item.text.as_str()).collect();
assert_eq!(texts, ["kept"]);
}
#[test]
fn t_star_inside_form_moves_to_next_line() {
// T* was previously unhandled inside Form XObjects, so every line after
// the first piled onto the preceding baseline and drifted right.
let items =
form_items(b"BT /F1 12 Tf 12 TL 1 0 0 1 100 700 Tm (first) Tj T* (second) Tj ET");
let first = find(&items, "first");
let second = find(&items, "second");
assert!((first.y - 700.0).abs() < 0.1, "first y = {}", first.y);
assert!((second.y - 688.0).abs() < 0.1, "second y = {}", second.y);
assert!((second.x - 100.0).abs() < 0.1, "second x = {}", second.x);
}
#[test]
fn td_inside_form_is_relative_to_line_start_not_shown_text() {
// Td moves relative to the text *line* matrix. Applying it to the
// matrix already advanced by Tj marched each line off the right edge.
let items = form_items(b"BT /F1 12 Tf 1 0 0 1 100 700 Tm (AAAAA) Tj 0 -12 Td (B) Tj ET");
let b = find(&items, "B");
assert!((b.x - 100.0).abs() < 0.1, "B x = {} (expected 100)", b.x);
assert!((b.y - 688.0).abs() < 0.1, "B y = {}", b.y);
}
#[test]
fn td_inside_form_sets_leading_for_later_t_star() {
// `TD` sets the leading to -ty as a side effect; a following T* must
// reuse it.
let items = form_items(
b"BT /F1 12 Tf 1 0 0 1 100 700 Tm (one) Tj 0 -15 TD (two) Tj T* (three) Tj ET",
);
assert!((find(&items, "two").y - 685.0).abs() < 0.1);
let three = find(&items, "three");
assert!((three.y - 670.0).abs() < 0.1, "three y = {}", three.y);
assert!((three.x - 100.0).abs() < 0.1, "three x = {}", three.x);
}
#[test]
fn quote_operator_inside_form_moves_to_next_line() {
let items = form_items(b"BT /F1 12 Tf 12 TL 1 0 0 1 100 700 Tm (first) Tj (second) ' ET");
let second = find(&items, "second");
assert!((second.y - 688.0).abs() < 0.1, "second y = {}", second.y);
assert!((second.x - 100.0).abs() < 0.1, "second x = {}", second.x);
}
#[test]
fn double_quote_operator_inside_form_sets_spacing_and_moves() {
// `aw ac (string) "` — set word spacing and char spacing, then T* and show.
let items =
form_items(b"BT /F1 12 Tf 12 TL 1 0 0 1 100 700 Tm (first) Tj 0 0 (second) \" ET");
let second = find(&items, "second");
assert!((second.y - 688.0).abs() < 0.1, "second y = {}", second.y);
assert!((second.x - 100.0).abs() < 0.1, "second x = {}", second.x);
}
#[test]
fn char_spacing_inside_form_widens_advance() {
// Tc was hardcoded to 0 in the form parser, so advance widths drifted.
// 2 glyphs x 600/1000 x 12pt = 14.4, plus 2 x Tc(2.0) = 18.4.
let items = form_items(b"BT /F1 12 Tf 1 0 0 1 100 700 Tm 2 Tc (AB) Tj ET");
let ab = find(&items, "AB");
assert!((ab.width - 18.4).abs() < 0.1, "AB width = {}", ab.width);
}
#[test]
fn q_restores_fill_colour_inside_form() {
// A white fill set inside q/Q must not leak past the Q — otherwise the
// following black text is treated as invisible and dropped entirely.
let items = form_items(
b"BT /F1 12 Tf 12 TL 1 0 0 1 100 700 Tm q 1 g (hidden) Tj Q T* (visible) Tj ET",
);
assert!(
items.iter().any(|item| item.text == "visible"),
"text after Q was dropped: {:?}",
items.iter().map(|i| &i.text).collect::<Vec<_>>()
);
assert!(
!items.iter().any(|item| item.text == "hidden"),
"white-filled text should still be suppressed"
);
}
#[test]
fn q_restores_text_state_inside_form() {
// Tc/TL live in the graphics state; `Q` must roll them back.
let items =
form_items(b"BT /F1 12 Tf 12 TL 1 0 0 1 100 700 Tm q 30 TL (a) Tj Q T* (b) Tj ET");
let b = find(&items, "b");
assert!(
(b.y - 688.0).abs() < 0.1,
"b y = {} (leading should restore to 12)",
b.y
);
}
#[test]
fn form_only_rotated_page_is_turned_like_page_stream_text() {
// The whole page is one Form XObject whose runs are all 90°: the
// form runs must vote, so the page is re-based exactly as if the
// runs had been shown by the page stream itself.
let (doc, page_id) = doc_with_form_content(
b"BT /F1 12 Tf 0 1 -1 0 200 100 Tm (HELLO) Tj ET
BT /F1 12 Tf 0 1 -1 0 240 100 Tm (WORLD) Tj ET",
);
let font_cmaps = FontCMaps::from_doc(&doc);
let ((items, _, _), _, page_rotation, _) = extract_page_text_items(
&doc,
page_id,
1,
&font_cmaps,
false,
&mut FontStyleCache::new(),
&mut FormWalkBudget::new(),
)
.unwrap();
assert_eq!(page_rotation, crate::extractor::geometry::PageRotation::Ccw);
let hello = find(&items, "HELLO");
assert_eq!(hello.rotation, 0.0);
assert!((hello.x - 100.0).abs() < 0.01, "x = {}", hello.x);
assert!((hello.y + 200.0).abs() < 0.01, "y = {}", hello.y);
assert!((hello.width - 36.0).abs() < 0.01, "width = {}", hello.width);
}
#[test]
fn form_only_page_with_a_lone_split_tj_stays_upright() {
// One rotated TJ that splits at a 6em gap yields two items but is a
// single show operator: a lone stamp, not a rotated page.
let (doc, page_id) =
doc_with_form_content(b"BT /F1 10 Tf 0 1 -1 0 40 100 Tm [(AB) -6000 (CD)] TJ ET");
let font_cmaps = FontCMaps::from_doc(&doc);
let ((items, _, _), _, page_rotation, _) = extract_page_text_items(
&doc,
page_id,
1,
&font_cmaps,
false,
&mut FontStyleCache::new(),
&mut FormWalkBudget::new(),
)
.unwrap();
assert_eq!(items.len(), 2, "{items:?}");
assert_eq!(
page_rotation,
crate::extractor::geometry::PageRotation::Upright
);
assert!(items.iter().all(|i| (i.rotation - 90.0).abs() < 1e-3));
}
#[test]
fn invisible_form_text_is_skipped_and_does_not_vote() {
// An OCR layer drawn inside a form with `3 Tr`: two rotated hidden
// runs next to one visible upright caption. The hidden runs must
// neither appear nor turn the page, and the page must report that
// it skipped them so the `include_invisible` retry recovers them,
// exactly as for page-stream text.
let content = b"BT /F1 12 Tf 72 700 Td (Caption) Tj ET
BT 3 Tr /F1 12 Tf 0 1 -1 0 200 100 Tm (HIDDEN) Tj ET
BT 3 Tr /F1 12 Tf 0 1 -1 0 240 100 Tm [(ALSO) -3000 (HIDDEN)] TJ ET";
let (doc, page_id) = doc_with_form_content(content);
let font_cmaps = FontCMaps::from_doc(&doc);
let extract = |include_invisible: bool| {
extract_page_text_items(
&doc,
page_id,
1,
&font_cmaps,
include_invisible,
&mut FontStyleCache::new(),
&mut FormWalkBudget::new(),
)
.unwrap()
};
let ((items, _, _), _, page_rotation, skipped_invisible) = extract(false);
assert_eq!(
page_rotation,
crate::extractor::geometry::PageRotation::Upright
);
assert!(skipped_invisible);
let texts: Vec<&str> = items.iter().map(|i| i.text.as_str()).collect();
assert_eq!(texts, ["Caption"]);
let ((items, _, _), _, page_rotation, _) = extract(true);
assert!(items.iter().any(|i| i.text == "HIDDEN"), "{items:?}");
assert!(
items.iter().any(|i| i.text.starts_with("ALSO")),
"{items:?}"
);
// Two rotated operators against one upright: the recovered layer
// now turns the page like any other rotated text.
assert_eq!(page_rotation, crate::extractor::geometry::PageRotation::Ccw);
}
fn extract_page(
doc: &Document,
page_id: ObjectId,
include_invisible: bool,
) -> (Vec<TextItem>, bool) {
let font_cmaps = FontCMaps::from_doc(doc);
let ((items, _, _), _, _, skipped_invisible) = extract_page_text_items(
doc,
page_id,
1,
&font_cmaps,
include_invisible,
&mut FontStyleCache::new(),
&mut FormWalkBudget::new(),
)
.unwrap();
(items, skipped_invisible)
}
#[test]
fn form_inherits_the_pages_text_rendering_mode() {
// `3 Tr` set by the page stream before `Do`: the form's text is an
// OCR-style hidden layer and must stay hidden on the visible pass.
let (doc, page_id) = doc_with_page_and_forms(
b"BT 3 Tr ET q /X1 Do Q",
&[b"BT /F1 12 Tf 72 700 Td (Hidden) Tj ET"],
);
let (items, skipped_invisible) = extract_page(&doc, page_id, false);
assert!(items.is_empty(), "{items:?}");
assert!(skipped_invisible);
let (items, _) = extract_page(&doc, page_id, true);
assert_eq!(items.len(), 1);
assert_eq!(items[0].text, "Hidden");
}
#[test]
fn form_inherits_fill_stroke_weight_and_restores_it() {
let (doc, page_id) = doc_with_page_and_forms(
b"0.3 w 2 Tr BT ET /X1 Do 0 Tr /X2 Do",
&[
b"BT /F1 12 Tf 72 700 Td (Lead) Tj ET q 0 Tr BT /F1 12 Tf 72 680 Td (Plain) Tj ET Q BT /F1 12 Tf 72 660 Td (Restored) Tj ET",
b"BT /F1 12 Tf 72 640 Td (Body) Tj ET",
],
);
let (items, _) = extract_page(&doc, page_id, false);
let styles: Vec<_> = items.iter().map(|i| (i.text.as_str(), i.is_bold)).collect();
assert_eq!(
styles,
[
("Lead", true),
("Plain", false),
("Restored", true),
("Body", false)
]
);
}
#[test]
fn form_graphics_states_are_scoped_and_restored() {
let (mut doc, page_id) = doc_with_page_and_forms(
b"/State gs 0.3 w 2 Tr /X1 Do /X2 Do",
&[
b"/State gs BT /F1 12 Tf 72 700 Td (Plain) Tj ET",
b"/State gs BT /F1 12 Tf 72 680 Td (Lead) Tj ET
q /Missing gs BT /F1 12 Tf 72 660 Td (Unknown) Tj ET Q
BT /F1 12 Tf 72 640 Td (Restored) Tj ET",
],
);
doc.get_dictionary_mut(page_id)
.unwrap()
.get_mut(b"Resources")
.unwrap()
.as_dict_mut()
.unwrap()
.set(
"ExtGState",
dictionary! { "State" => dictionary! { "SM" => 0.02 } },
);
for (id, state) in [
((2, 0), dictionary! { "ca" => 0.5 }),
((3, 0), dictionary! { "OPM" => 1 }),
] {
doc.get_object_mut(id)
.unwrap()
.as_stream_mut()
.unwrap()
.dict
.get_mut(b"Resources")
.unwrap()
.as_dict_mut()
.unwrap()
.set("ExtGState", dictionary! { "State" => state });
}
let (items, _) = extract_page(&doc, page_id, false);
let styles: Vec<_> = items.iter().map(|i| (i.text.as_str(), i.is_bold)).collect();
assert_eq!(
styles,
[
("Plain", false),
("Lead", true),
("Unknown", false),
("Restored", true)
]
);
}
#[test]
fn nested_form_resolves_indirect_paint_resources_without_leaking_state() {
let (mut doc, page_id) = doc_with_page_and_forms(
b"0.3 w 2 Tr /X1 Do",
&[
b"/Tone cs 0.2 0.3 0.4 sc /Tone CS 0.2 0.3 0.4 SC /State gs
BT /F1 12 Tf 72 700 Td (Outer) Tj ET /X2 Do
0.2 0.3 0.4 rg BT /F1 12 Tf 72 660 Td (Restored) Tj ET",
b"/Tone cs 0 sc /Tone CS 0 SC /State gs
BT /F1 12 Tf 72 680 Td (Inner) Tj ET",
],
);
for (id, color_space, state) in [
((2, 0), "DeviceRGB", dictionary! { "SM" => 0.02 }),
((3, 0), "DeviceGray", dictionary! { "OPM" => 1 }),
] {
let mut resources = doc
.get_object(id)
.unwrap()
.as_stream()
.unwrap()
.dict
.get(b"Resources")
.unwrap()
.as_dict()
.unwrap()
.clone();
let space_id = doc.add_object(Object::Name(color_space.as_bytes().to_vec()));
let state_id = doc.add_object(state);
let spaces_id = doc.add_object(dictionary! { "Tone" => Object::Reference(space_id) });
let states_id = doc.add_object(dictionary! { "State" => Object::Reference(state_id) });
resources.set("ColorSpace", Object::Reference(spaces_id));
resources.set("ExtGState", Object::Reference(states_id));
let resources_id = doc.add_object(resources);
doc.get_object_mut(id)
.unwrap()
.as_stream_mut()
.unwrap()
.dict
.set("Resources", Object::Reference(resources_id));
}
let (items, _) = extract_page(&doc, page_id, false);
assert_eq!(
items.iter().map(|i| i.text.as_str()).collect::<Vec<_>>(),
["Outer", "Inner", "Restored"]
);
assert!(items.iter().all(|i| i.is_bold));
}
#[test]
fn form_fill_stroke_covers_all_show_operators() {
for show in [
"(Styled) Tj",
"[(Sty) (led)] TJ",
"(Styled) '",
"0 0 (Styled) \"",
] {
let content = format!("BT /F1 12 Tf 72 700 Td {show} ET");
let (doc, page_id) =
doc_with_page_and_forms(b"0.3 w 2 Tr /X1 Do", &[content.as_bytes()]);
let (items, _) = extract_page(&doc, page_id, false);
assert_eq!(items.len(), 1, "{show}: {items:?}");
assert_eq!(items[0].text, "Styled");
assert!(items[0].is_bold, "{show}: {items:?}");
}
}
#[test]
fn unresolved_form_font_does_not_gain_painted_bold() {
let items = form_items(b"0.3 w 2 Tr BT /Missing 12 Tf 72 700 Td (Alpha) Tj ET");
assert_eq!(items.len(), 1);
assert_eq!(items[0].text, "Alpha");
assert!(!items[0].is_bold);
}
#[test]
fn inline_form_fonts_match_referenced_style_and_geometry() {
for (subtype, name, mode, text, bold, italic) in [
("Type1", "Helvetica", 2, "Alpha", true, false),
("Type1", "Helvetica-BoldOblique", 0, "Alpha", true, true),
("Type1", "Wingdings", 2, "A", false, false),
("Type3", "Shape", 2, "A", false, false),
] {
let content = format!("0.3 w {mode} Tr BT /F1 12 Tf 72 700 Td ({text}) Tj ET");
let (mut referenced_doc, page_id) =
doc_with_page_and_forms(b"/X1 Do", &[content.as_bytes()]);
let glyph = referenced_doc.add_object(Stream::new(
dictionary! {},
b"600 0 0 0 600 700 d1 0 0 600 700 re f".to_vec(),
));
let font = referenced_doc.get_dictionary_mut((1, 0)).unwrap();
font.set("Subtype", Object::Name(subtype.as_bytes().to_vec()));
font.set("BaseFont", Object::Name(name.as_bytes().to_vec()));
if subtype == "Type3" {
font.set(
"FontMatrix",
vec![
0.001.into(),
0.into(),
0.into(),
0.001.into(),
0.into(),
0.into(),
],
);
font.set("FontBBox", vec![0.into(), 0.into(), 600.into(), 700.into()]);
font.set("CharProcs", dictionary! { "A" => Object::Reference(glyph) });
font.set(
"Encoding",
dictionary! { "Differences" => vec![65.into(), Object::Name(b"A".to_vec())] },
);
}
let direct_font = font.clone();
let mut inline_doc = referenced_doc.clone();
inline_doc
.get_object_mut((2, 0))
.unwrap()
.as_stream_mut()
.unwrap()
.dict
.get_mut(b"Resources")
.unwrap()
.as_dict_mut()
.unwrap()
.get_mut(b"Font")
.unwrap()
.as_dict_mut()
.unwrap()
.set("F1", direct_font);
let (referenced_items, _) = extract_page(&referenced_doc, page_id, false);
let (inline_items, _) = extract_page(&inline_doc, page_id, false);
assert_eq!(referenced_items.len(), 1, "{name}");
assert_eq!(inline_items.len(), 1, "{name}");
let expected = &referenced_items[0];
let actual = &inline_items[0];
assert_eq!(actual.text, text, "{name}");
assert_eq!((actual.is_bold, actual.is_italic), (bold, italic), "{name}");
assert_eq!(
(
&actual.font,
actual.font_size,
actual.width,
actual.height,
actual.x,
actual.y,
actual.is_bold,
actual.is_italic,
actual.advance_known
),
(
&expected.font,
expected.font_size,
expected.width,
expected.height,
expected.x,
expected.y,
expected.is_bold,
expected.is_italic,
expected.advance_known
),
"{name}"
);
}
}
#[test]
fn nested_form_inherits_the_outer_forms_text_rendering_mode() {
// The outer form sets `3 Tr` and invokes the inner form, whose text
// must stay hidden; an outer run at the default mode stays visible.
let (doc, page_id) = doc_with_page_and_forms(
b"q /X1 Do Q",
&[
b"BT /F1 12 Tf 72 700 Td (Visible) Tj ET BT 3 Tr ET q /X2 Do Q",
b"BT /F1 12 Tf 72 650 Td (Hidden) Tj ET",
],
);
let (items, skipped_invisible) = extract_page(&doc, page_id, false);
let texts: Vec<&str> = items.iter().map(|i| i.text.as_str()).collect();
assert_eq!(texts, ["Visible"]);
assert!(skipped_invisible);
let (items, _) = extract_page(&doc, page_id, true);
assert!(items.iter().any(|i| i.text == "Hidden"), "{items:?}");
}
#[test]
fn form_inherits_the_pages_text_rise() {
// `5 Ts` set by the page stream before `Do`: text state is graphics
// state, so the form's first run is raised until the form itself
// resets the rise.
let (doc, page_id) = doc_with_page_and_forms(
b"BT 5 Ts ET q /X1 Do Q",
&[b"BT /F1 12 Tf 1 0 0 1 100 500 Tm (raised) Tj 0 Ts (base) Tj ET"],
);
let (items, _) = extract_page(&doc, page_id, false);
let raised = find(&items, "raised");
let base = find(&items, "base");
assert!((raised.y - 505.0).abs() < 0.1, "raised y = {}", raised.y);
assert!((base.y - 500.0).abs() < 0.1, "base y = {}", base.y);
}
#[test]
fn nested_form_inherits_the_outer_forms_text_rise() {
// The outer form raises the baseline and invokes the inner form; the
// inner run is raised, the outer's own run at rise 0 is not.
let (doc, page_id) = doc_with_page_and_forms(
b"q /X1 Do Q",
&[
b"BT /F1 12 Tf 1 0 0 1 100 500 Tm (outer) Tj ET BT 5 Ts ET q /X2 Do Q",
b"BT /F1 12 Tf 1 0 0 1 100 400 Tm (inner) Tj ET",
],
);
let (items, _) = extract_page(&doc, page_id, false);
let outer = find(&items, "outer");
let inner = find(&items, "inner");
assert!((outer.y - 500.0).abs() < 0.1, "outer y = {}", outer.y);
assert!((inner.y - 405.0).abs() < 0.1, "inner y = {}", inner.y);
}
#[test]
fn form_tj_at_a_negative_size_votes_with_its_own_items() {
// A form's vertical TJ runs at `-12 Tf` read top-to-bottom: their
// page-rotation votes must say so, like the items they produce, or
// the page would be turned against them.
let (doc, page_id) = doc_with_page_and_forms(
b"q /X1 Do Q",
&[b"BT /F1 -12 Tf 0 1 -1 0 100 100 Tm [(UP)] TJ ET BT /F1 -12 Tf 0 1 -1 0 130 100 Tm [(UP)] TJ ET"],
);
let font_cmaps = FontCMaps::from_doc(&doc);
let ((items, _, _), _, page_rotation, _) = extract_page_text_items(
&doc,
page_id,
1,
&font_cmaps,
false,
&mut FontStyleCache::new(),
&mut FormWalkBudget::new(),
)
.unwrap();
assert_eq!(page_rotation, crate::extractor::geometry::PageRotation::Cw);
assert_eq!(items.len(), 2, "{items:?}");
assert!(items.iter().all(|i| i.rotation == 0.0), "{items:?}");
}
#[test]
fn text_rise_inside_form_shifts_the_baseline() {
// Ts displaces the glyph origin without touching the advance, in a
// form exactly as in the page stream; the next run at rise 0 returns
// to the original baseline and follows the raised run horizontally.
let items = form_items(
b"BT /F1 12 Tf 1 0 0 1 100 500 Tm (base) Tj 5 Ts (super) Tj 0 Ts (after) Tj ET",
);
let base = find(&items, "base");
let raised = find(&items, "super");
let after = find(&items, "after");
assert!((base.y - 500.0).abs() < 0.1, "base y = {}", base.y);
assert!((raised.y - 505.0).abs() < 0.1, "raised y = {}", raised.y);
assert!((after.y - 500.0).abs() < 0.1, "after y = {}", after.y);
assert!(after.x > raised.x);
}
#[test]
fn rotated_run_inside_form_gets_tall_thin_box() {
// Same contract as the page-level parser: a 20pt stamp reading
// bottom-to-top gets its em as width and its advance as height, for
// both Tj and TJ.
let items = form_items(
b"BT /F1 12 Tf 72 700 Td (Body line one) Tj ET
BT /F1 12 Tf 72 686 Td (Body line two) Tj ET
BT /F1 12 Tf 72 672 Td (Body line three) Tj ET
BT /F1 20 Tf 0 1 -1 0 32 200 Tm (arXiv:2301.00001) Tj ET
BT /F1 10 Tf 0 1 -1 0 60 200 Tm [(ABCD)] TJ ET",
);
let stamp = find(&items, "arXiv:2301.00001");
assert!(
(stamp.rotation - 90.0).abs() < 1e-3,
"rotation = {}",
stamp.rotation
);
assert!((stamp.x - 12.0).abs() < 0.01, "x = {}", stamp.x);
assert!((stamp.y - 200.0).abs() < 0.01, "y = {}", stamp.y);
assert!((stamp.width - 20.0).abs() < 0.01, "width = {}", stamp.width);
assert!(
(stamp.height - 192.0).abs() < 0.01,
"height = {}",
stamp.height
);
let tj = find(&items, "ABCD");
assert!(
(tj.rotation - 90.0).abs() < 1e-3,
"rotation = {}",
tj.rotation
);
assert!((tj.x - 50.0).abs() < 0.01, "x = {}", tj.x);
assert!((tj.width - 10.0).abs() < 0.01, "width = {}", tj.width);
assert!((tj.y - 200.0).abs() < 0.01, "y = {}", tj.y);
assert!((tj.height - 24.0).abs() < 0.01, "height = {}", tj.height);
let body = find(&items, "Body line one");
assert_eq!(body.rotation, 0.0);
assert!(
(body.width - 13.0 * 7.2).abs() < 0.01,
"width = {}",
body.width
);
assert_eq!(body.height, 12.0);
}
/// The form parser positions `TJ` sub-runs like the page parser: pen
/// travel ahead of the first glyph moves the box, not just the pen.
#[test]
fn tj_positioning_ahead_of_the_first_glyph_inside_form_moves_the_box() {
// -5400 at 10pt carries the pen 54pt from x=100 to 154, flush against
// "Intr" (130..154), so the merge pass rejoins the word.
let items = form_items(
b"BT /F1 10 Tf 1 0 0 1 130 700 Tm (Intr) Tj 1 0 0 1 100 700 Tm [-5400 (oduction)] TJ ET",
);
let word = find(&items, "Introduction");
assert!((word.x - 130.0).abs() < 0.05, "{items:?}");
assert!((word.width - 72.0).abs() < 0.05, "{items:?}");
// A squeezed space run positioned the same way is still the word
// space of the item before it.
let items = form_items(
b"BT /F1 12 Tf 72 700 Td (for) Tj -6 Tc 1 0 0 1 60 700 Tm [-2800 ( )] TJ 0 Tc 1 0 0 1 94.8 700 Tm (the) Tj ET",
);
find(&items, "for the");
}
/// Word gaps carried by character spacing inside a form read as word
/// spaces once the spacing is taken back, for every show operator —
/// `"` sets the spacing itself; spacing that stays is tracking.
#[test]
fn character_spacing_word_gaps_inside_form_read_as_word_spaces() {
for (content, expected) in [
(
"BT /F1 10 Tf 72 700 Td (sen) Tj 3 Tc 18 0 Td [(dt) 300 (oM)] TJ 0 Tc 30 0 Td (ars) Tj ET",
"send to Mars",
),
(
"BT /F1 10 Tf 72 700 Td (sen) Tj 3 Tc 18 0 Td (dt) Tj 0 Tc 15 0 Td (o) Tj ET",
"send to",
),
("BT /F1 10 Tf 12 TL 72 712 Td 3 Tc (dt) ' 0 Tc 15 0 Td (o) Tj ET", "d to"),
("BT /F1 10 Tf 12 TL 72 712 Td 0 3 (dt) \" 0 Tc 15 0 Td (o) Tj ET", "d to"),
("BT /F1 10 Tf 72 700 Td 3 Tc [(dt) 20] TJ 0 Tc 14.8 0 Td (o) Tj ET", "d to"),
("BT /F1 10 Tf 72 700 Td 3 Tc (dt) Tj 18 0 Td (o) Tj ET", "dto"),
("BT /F1 10 Tf 72 700 Td 3 Tc (HEADING) Tj ET", "HEADING"),
] {
let items = form_items(content.as_bytes());
let texts: Vec<_> = items.iter().map(|i| i.text.as_str()).collect();
assert_eq!(texts, [expected], "{content}: {items:?}");
}
}
/// An XObject painted between a candidate and the run that would have
/// taken its spacing back belongs to another stream: the candidate is
/// dropped, on the page and inside a form alike.
#[test]
fn an_xobject_in_between_drops_the_word_gap_candidate() {
let (doc, page_id) = doc_with_page_and_forms(
b"BT /F1 10 Tf 72 700 Td 3 Tc (dt) Tj q /X1 Do Q 0 Tc 15 0 Td (o) Tj ET q /X2 Do Q",
&[
b"",
b"BT /F1 10 Tf 72 600 Td 3 Tc (dt) Tj q /X1 Do Q 0 Tc 15 0 Td (o) Tj ET",
],
);
let font_cmaps = FontCMaps::from_doc(&doc);
let ((items, _, _), _, _, _) = extract_page_text_items(
&doc,
page_id,
1,
&font_cmaps,
false,
&mut FontStyleCache::new(),
&mut FormWalkBudget::new(),
)
.unwrap();
let texts: Vec<_> = items.iter().map(|i| i.text.as_str()).collect();
assert_eq!(texts, ["dto", "dto"], "{items:?}");
}
/// Tracked display text set as a glyph-per-string `TJ` array inside a
/// form is judged over its own tracking, as on the page; positioning
/// between whole words reads as before. The form font's space is 0.6
/// em, so its word-gap threshold is 240 thousandths.
#[test]
fn tracked_tj_title_inside_form_stays_one_word() {
for (content, expected) in [
(
"BT /F1 24 Tf 72 700 Td [(V) -216 (A) -333 (L) -166 (L) -250 (E) -290 (Y)] TJ ET",
"VALLEY",
),
(
"BT /F1 24 Tf 72 700 Td [(V) -250 (A) -250 (L) -250 (L) -250 (E) -250 (Y) -560 (R) -250 (O) -250 (A) -250 (D)] TJ ET",
"VALLEY ROAD",
),
(
"BT /F1 12 Tf 72 700 Td [(The) -258 (quick) -300 (brown)] TJ ET",
"The quick brown",
),
] {
let items = form_items(content.as_bytes());
let texts: Vec<_> = items.iter().map(|i| i.text.as_str()).collect();
assert_eq!(texts.join(" "), expected, "{content}: {items:?}");
}
}
/// Items of a page whose only content is `q /X1 Do Q`, the form showing
/// `form_content` through `F1`, the zero-advance-sign font of
/// `content_stream::add_zero_advance_sign_font`.
fn form_items_with_zero_advance_signs(form_content: &[u8]) -> Vec<TextItem> {
let mut doc = Document::new();
let font_id = crate::extractor::content_stream::add_zero_advance_sign_font(&mut doc);
let form_id = doc.add_object(Object::Stream(Stream::new(
dictionary! {
"Type" => "XObject",
"Subtype" => "Form",
"BBox" => vec![0.into(), 0.into(), 612.into(), 792.into()],
"Resources" => dictionary! {
"Font" => dictionary! { "F1" => Object::Reference(font_id) },
},
},
form_content.to_vec(),
)));
let content_id = doc.add_object(Object::Stream(Stream::new(
dictionary! {},
b"q /X1 Do Q".to_vec(),
)));
let page_id = doc.add_object(dictionary! {
"Type" => "Page",
"Contents" => Object::Reference(content_id),
"Resources" => dictionary! {
"XObject" => dictionary! { "X1" => Object::Reference(form_id) },
},
"MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()],
});
let pages_id = doc.add_object(dictionary! {
"Type" => "Pages",
"Count" => Object::Integer(1),
"Kids" => vec![Object::Reference(page_id)],
});
let catalog_id = doc.add_object(dictionary! {
"Type" => "Catalog",
"Pages" => Object::Reference(pages_id),
});
doc.trailer.set("Root", Object::Reference(catalog_id));
let font_cmaps = FontCMaps::from_doc(&doc);
let ((items, _, _), _, _, _) = extract_page_text_items(
&doc,
page_id,
1,
&font_cmaps,
false,
&mut FontStyleCache::new(),
&mut FormWalkBudget::new(),
)
.unwrap();
items
}
#[test]
fn form_tj_returns_from_signs_placed_behind_the_pen_open_no_word_gap() {
// As on the page: a zero-advance sign placed 0.223 em back over
// the glyph before it, the pen returned 0.221 em, is no word gap;
// a forward offset from the pen's farthest point still is.
use crate::extractor::content_stream::SIGNED_WORD;
let items = form_items_with_zero_advance_signs(
b"BT /F1 14 Tf 20 700 Td [<0001> 223 <0002> -221 <0003> <0004> 246 <0005> -221 <0006>] TJ ET",
);
let texts: Vec<&str> = items.iter().map(|item| item.text.as_str()).collect();
assert_eq!(texts, [SIGNED_WORD]);
assert!(
(items[0].x - 20.0).abs() < 0.01 && (items[0].width - 29.4).abs() < 0.01,
"{:?}",
items[0]
);
let items = form_items_with_zero_advance_signs(
b"BT /F1 14 Tf 20 700 Td [<0001> 223 <0002> -621 <0003>] TJ ET",
);
let texts: Vec<&str> = items.iter().map(|item| item.text.as_str()).collect();
assert_eq!(texts, ["\u{1789}\u{17D2}\u{1789} \u{179C}"]);
// Under `0.5 Tc` the sign is a sign by its glyph, though the
// spacing moves the pen for it.
let items = form_items_with_zero_advance_signs(
b"BT /F1 14 Tf 0.5 Tc 20 700 Td [<0001> 223 <0002> -221 <0003> <0004> 246 <0005> -221 <0006>] TJ ET",
);
let texts: Vec<&str> = items.iter().map(|item| item.text.as_str()).collect();
assert_eq!(texts, [SIGNED_WORD]);
// Twenty zero-advance glyphs behind the pen are hidden text, not a
// sign: the return after them is the word gap it reads as.
let hidden = "0002".repeat(20);
let items = form_items_with_zero_advance_signs(
format!("BT /F1 14 Tf 20 700 Td [<0003> 300 <{hidden}> -300 <0004>] TJ ET").as_bytes(),
);
let texts: Vec<&str> = items.iter().map(|item| item.text.as_str()).collect();
let expected = format!("\u{179C}{} \u{178F}\u{17D2}", "\u{1789}".repeat(20));
assert_eq!(texts, [expected.as_str()]);
}
}