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
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
//! # PDF Serializer
//!
//! Takes the laid-out pages from the layout engine and writes a valid PDF file.
//!
//! This is a from-scratch PDF 1.7 writer. We write the raw bytes ourselves
//! because it gives us full control over the output and makes the engine
//! self-contained. The PDF spec is verbose but the subset we need for
//! document rendering is manageable.
//!
//! ## PDF Structure (simplified)
//!
//! ```text
//! %PDF-1.7 <- header
//! 1 0 obj ... endobj <- objects (fonts, pages, content streams, etc.)
//! 2 0 obj ... endobj
//! ...
//! xref <- cross-reference table (byte offsets of each object)
//! trailer <- points to the root object
//! %%EOF
//! ```
//!
//! ## Font Embedding
//!
//! Standard PDF fonts (Helvetica, Times, Courier) use simple Type1 references.
//! Custom TrueType fonts are embedded as CIDFontType2 with Identity-H encoding,
//! producing 5 PDF objects per font: FontFile2, FontDescriptor, CIDFont,
//! ToUnicode CMap, and the root Type0 dictionary.
pub(crate) mod tagged;
pub(crate) mod xmp;
use std::collections::{HashMap, HashSet};
use std::fmt::Write as FmtWrite; // for write! on String
use std::io::Write as IoWrite; // for write! on Vec<u8>
use crate::error::FormeError;
use crate::font::subset::subset_ttf;
use crate::font::{FontContext, FontData, FontKey};
use crate::layout::*;
use crate::model::*;
use crate::style::{Color, FontStyle, Overflow, TextDecoration};
use crate::svg::SvgCommand;
use miniz_oxide::deflate::compress_to_vec_zlib;
/// A link annotation to be added to a page.
struct LinkAnnotation {
x: f64,
y: f64,
width: f64,
height: f64,
href: String,
}
/// A bookmark entry for the PDF outline tree.
struct PdfBookmark {
title: String,
page_obj_id: usize,
y_pdf: f64,
}
pub struct PdfWriter;
/// Embedding data for a custom TrueType font.
#[allow(dead_code)]
struct CustomFontEmbedData {
ttf_data: Vec<u8>,
/// Maps original glyph IDs (from shaping) to remapped GIDs in the subset font.
gid_remap: HashMap<u16, u16>,
/// Maps original glyph IDs to their Unicode character(s) for ToUnicode CMap.
glyph_to_char: HashMap<u16, char>,
/// Legacy fallback: maps chars to subset GIDs (for page number placeholders).
char_to_gid: HashMap<char, u16>,
units_per_em: u16,
ascender: i16,
descender: i16,
}
/// Font usage data collected from layout elements.
struct FontUsage {
/// Characters used per font (for standard font subsetting fallback).
chars: HashSet<char>,
/// Glyph IDs used per font (from shaped PositionedGlyphs).
glyph_ids: HashSet<u16>,
/// Maps glyph ID → first char it represents (for ToUnicode CMap).
glyph_to_char: HashMap<u16, char>,
}
/// Tracks allocated PDF objects during writing.
struct PdfBuilder {
objects: Vec<PdfObject>,
/// Maps (family, weight, italic) -> (object_id, index)
font_objects: Vec<(FontKey, usize)>,
/// Embedding data for custom fonts, keyed by FontKey.
custom_font_data: HashMap<FontKey, CustomFontEmbedData>,
/// XObject obj IDs for images, indexed as /Im0, /Im1, ...
/// Each entry is (main_xobject_id, optional_smask_xobject_id).
image_objects: Vec<usize>,
/// Maps (page_index, element_position_in_page) to image index in image_objects.
/// Used during content stream writing to find the right /ImN reference.
image_index_map: HashMap<(usize, usize), usize>,
/// ExtGState objects for opacity. Maps opacity value (as ordered bits) to
/// (object_id, gs_name) e.g. (42, "GS0").
ext_gstate_map: HashMap<u64, (usize, String)>,
}
pub(crate) struct PdfObject {
#[allow(dead_code)]
pub(crate) id: usize,
pub(crate) data: Vec<u8>,
}
impl Default for PdfWriter {
fn default() -> Self {
Self::new()
}
}
impl PdfWriter {
pub fn new() -> Self {
Self
}
/// Write laid-out pages to a PDF byte vector.
pub fn write(
&self,
pages: &[LayoutPage],
metadata: &Metadata,
font_context: &FontContext,
tagged: bool,
pdfa: Option<&PdfAConformance>,
embedded_data: Option<&str>,
) -> Result<Vec<u8>, FormeError> {
let mut builder = PdfBuilder {
objects: Vec::new(),
font_objects: Vec::new(),
custom_font_data: HashMap::new(),
image_objects: Vec::new(),
image_index_map: HashMap::new(),
ext_gstate_map: HashMap::new(),
};
// Reserve object IDs:
// 0 = placeholder (PDF objects are 1-indexed)
// 1 = Catalog
// 2 = Pages (page tree root)
// 3+ = fonts, then page objects, then content streams
builder.objects.push(PdfObject {
id: 0,
data: vec![],
});
builder.objects.push(PdfObject {
id: 1,
data: vec![],
});
builder.objects.push(PdfObject {
id: 2,
data: vec![],
});
// Register the fonts actually used across all pages
self.register_fonts(&mut builder, pages, font_context)?;
// PDF/A: validate that all fonts are embedded (no standard fonts)
if pdfa.is_some() {
for (key, _) in &builder.font_objects {
if !builder.custom_font_data.contains_key(key) {
return Err(FormeError::RenderError(format!(
"PDF/A requires all fonts to be embedded. Register a custom font for \
family '{}' using Font.register().",
key.family
)));
}
}
}
// Register images as XObject PDF objects
self.register_images(&mut builder, pages);
// Register ExtGState objects for opacity
self.register_ext_gstates(&mut builder, pages);
// Create tag builder for accessibility if requested
let mut tag_builder = if tagged {
Some(tagged::TagBuilder::new(pages.len()))
} else {
None
};
// Two-pass page processing:
// Pass 1: Build content streams, page objects, collect bookmarks + annotations
// Pass 2: Create annotation objects (needs full bookmark list for internal links)
let mut page_obj_ids: Vec<usize> = Vec::new();
let mut all_bookmarks: Vec<PdfBookmark> = Vec::new();
let mut per_page_content_obj_ids: Vec<usize> = Vec::new();
let mut per_page_annotations: Vec<Vec<LinkAnnotation>> = Vec::new();
let mut per_page_resources: Vec<String> = Vec::new();
// Pass 1: content streams, page objects (without /Annots), bookmarks
for (page_idx, page) in pages.iter().enumerate() {
let content = self.build_content_stream_for_page(
page,
page_idx,
&builder,
page_idx + 1,
pages.len(),
tag_builder.as_mut(),
);
let compressed = compress_to_vec_zlib(content.as_bytes(), 6);
let content_obj_id = builder.objects.len();
let mut content_data: Vec<u8> = Vec::new();
let _ = write!(
content_data,
"<< /Length {} /Filter /FlateDecode >>\nstream\n",
compressed.len()
);
content_data.extend_from_slice(&compressed);
content_data.extend_from_slice(b"\nendstream");
builder.objects.push(PdfObject {
id: content_obj_id,
data: content_data,
});
per_page_content_obj_ids.push(content_obj_id);
// Collect link annotations (deferred creation until pass 2)
let mut annotations: Vec<LinkAnnotation> = Vec::new();
Self::collect_link_annotations(&page.elements, page.height, &mut annotations);
per_page_annotations.push(annotations);
// Reserve page object (placeholder — filled in pass 2)
let page_obj_id = builder.objects.len();
builder.objects.push(PdfObject {
id: page_obj_id,
data: vec![],
});
// Build resource dict for this page
let font_resources = self.build_font_resource_dict(&builder.font_objects);
let xobject_resources = self.build_xobject_resource_dict(page_idx, &builder);
let ext_gstate_resources = self.build_ext_gstate_resource_dict(&builder);
let mut resources = format!("/Font << {} >>", font_resources);
if !xobject_resources.is_empty() {
let _ = write!(resources, " /XObject << {} >>", xobject_resources);
}
if !ext_gstate_resources.is_empty() {
let _ = write!(resources, " /ExtGState << {} >>", ext_gstate_resources);
}
per_page_resources.push(resources);
// Collect bookmarks (needs page_obj_id)
Self::collect_bookmarks(&page.elements, page.height, page_obj_id, &mut all_bookmarks);
page_obj_ids.push(page_obj_id);
}
// Pass 2: create annotation objects and fill in page dicts
for (page_idx, annotations) in per_page_annotations.iter().enumerate() {
let mut annot_obj_ids: Vec<usize> = Vec::new();
for annot in annotations {
let rect = format!(
"[{:.2} {:.2} {:.2} {:.2}]",
annot.x,
annot.y,
annot.x + annot.width,
annot.y + annot.height
);
if let Some(anchor) = annot.href.strip_prefix('#') {
// Internal link: find matching bookmark by title
if let Some(bm) = all_bookmarks.iter().find(|b| b.title == anchor) {
let annot_obj_id = builder.objects.len();
let annot_dict = format!(
"<< /Type /Annot /Subtype /Link /Rect {} /Border [0 0 0] \
/A << /S /GoTo /D [{} 0 R /XYZ 0 {:.2} null] >> >>",
rect, bm.page_obj_id, bm.y_pdf
);
builder.objects.push(PdfObject {
id: annot_obj_id,
data: annot_dict.into_bytes(),
});
annot_obj_ids.push(annot_obj_id);
}
// No matching bookmark: skip silently
} else {
// External link
let annot_obj_id = builder.objects.len();
let annot_dict = format!(
"<< /Type /Annot /Subtype /Link /Rect {} /Border [0 0 0] \
/A << /Type /Action /S /URI /URI ({}) >> >>",
rect,
Self::escape_pdf_string(&annot.href)
);
builder.objects.push(PdfObject {
id: annot_obj_id,
data: annot_dict.into_bytes(),
});
annot_obj_ids.push(annot_obj_id);
}
}
let annots_str = if annot_obj_ids.is_empty() {
String::new()
} else {
let refs: String = annot_obj_ids
.iter()
.map(|id| format!("{} 0 R", id))
.collect::<Vec<_>>()
.join(" ");
format!(" /Annots [{}]", refs)
};
let page_obj_id = page_obj_ids[page_idx];
let content_obj_id = per_page_content_obj_ids[page_idx];
let struct_parents_str = if tagged {
format!(" /StructParents {}", page_idx)
} else {
String::new()
};
let page_dict = format!(
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {:.2} {:.2}] \
/Contents {} 0 R /Resources << {} >>{}{} >>",
pages[page_idx].width,
pages[page_idx].height,
content_obj_id,
per_page_resources[page_idx],
annots_str,
struct_parents_str
);
builder.objects[page_obj_id].data = page_dict.into_bytes();
}
// Build outline tree if bookmarks exist
let outlines_obj_id = if !all_bookmarks.is_empty() {
Some(self.write_outline_tree(&mut builder, &all_bookmarks))
} else {
None
};
// Build structure tree for tagged PDF
let struct_tree_root_id = if let Some(ref tb) = tag_builder {
let (root_id, _parent_tree_id) = tb.write_objects(&mut builder.objects, &page_obj_ids);
Some(root_id)
} else {
None
};
// PDF/A: write XMP metadata stream and ICC output intent
let xmp_metadata_id = if let Some(conf) = pdfa {
let xmp_xml = xmp::generate_xmp(metadata, conf);
let xmp_bytes = xmp_xml.as_bytes();
let xmp_obj_id = builder.objects.len();
// XMP metadata stream must NOT be compressed (PDF/A requirement)
let xmp_data = format!(
"<< /Type /Metadata /Subtype /XML /Length {} >>\nstream\n",
xmp_bytes.len()
);
let mut xmp_obj_data: Vec<u8> = xmp_data.into_bytes();
xmp_obj_data.extend_from_slice(xmp_bytes);
xmp_obj_data.extend_from_slice(b"\nendstream");
builder.objects.push(PdfObject {
id: xmp_obj_id,
data: xmp_obj_data,
});
Some(xmp_obj_id)
} else {
None
};
let output_intent_id = if pdfa.is_some() {
// Embed sRGB ICC profile
static SRGB_ICC: &[u8] = include_bytes!("srgb2014.icc");
let compressed_icc = compress_to_vec_zlib(SRGB_ICC, 6);
let icc_obj_id = builder.objects.len();
let mut icc_data: Vec<u8> = Vec::new();
let _ = write!(
icc_data,
"<< /N 3 /Length {} /Filter /FlateDecode >>\nstream\n",
compressed_icc.len()
);
icc_data.extend_from_slice(&compressed_icc);
icc_data.extend_from_slice(b"\nendstream");
builder.objects.push(PdfObject {
id: icc_obj_id,
data: icc_data,
});
// OutputIntent dictionary
let oi_obj_id = builder.objects.len();
let oi_data = format!(
"<< /Type /OutputIntent /S /GTS_PDFA1 \
/OutputConditionIdentifier (sRGB IEC61966-2.1) \
/RegistryName (http://www.color.org) \
/DestOutputProfile {} 0 R >>",
icc_obj_id
);
builder.objects.push(PdfObject {
id: oi_obj_id,
data: oi_data.into_bytes(),
});
Some(oi_obj_id)
} else {
None
};
// Embedded data attachment (PDF 1.7 EmbeddedFile)
let embedded_names_id = if let Some(data) = embedded_data {
let compressed = compress_to_vec_zlib(data.as_bytes(), 6);
// EmbeddedFile stream
let ef_obj_id = builder.objects.len();
let ef_data = format!(
"<< /Type /EmbeddedFile /Subtype /application#2Fjson /Length {} /Filter /FlateDecode >>\nstream\n",
compressed.len()
);
let mut ef_bytes = ef_data.into_bytes();
ef_bytes.extend_from_slice(&compressed);
ef_bytes.extend_from_slice(b"\nendstream");
builder.objects.push(PdfObject {
id: ef_obj_id,
data: ef_bytes,
});
// FileSpec dictionary
let fs_obj_id = builder.objects.len();
let fs_data = format!(
"<< /Type /Filespec /F (forme-data.json) /UF (forme-data.json) /EF << /F {} 0 R >> /AFRelationship /Data >>",
ef_obj_id
);
builder.objects.push(PdfObject {
id: fs_obj_id,
data: fs_data.into_bytes(),
});
// Names tree for EmbeddedFiles
let names_obj_id = builder.objects.len();
let names_data = format!("<< /Names [(forme-data.json) {} 0 R] >>", fs_obj_id);
builder.objects.push(PdfObject {
id: names_obj_id,
data: names_data.into_bytes(),
});
Some(names_obj_id)
} else {
None
};
// Write Catalog (object 1)
let mut catalog = String::from("<< /Type /Catalog /Pages 2 0 R");
if let Some(outlines_id) = outlines_obj_id {
write!(
catalog,
" /Outlines {} 0 R /PageMode /UseOutlines",
outlines_id
)
.unwrap();
}
if let Some(ref lang) = metadata.lang {
write!(catalog, " /Lang ({})", Self::escape_pdf_string(lang)).unwrap();
}
if let Some(struct_root_id) = struct_tree_root_id {
write!(
catalog,
" /MarkInfo << /Marked true >> /StructTreeRoot {} 0 R",
struct_root_id
)
.unwrap();
}
if let Some(xmp_id) = xmp_metadata_id {
write!(catalog, " /Metadata {} 0 R", xmp_id).unwrap();
}
if let Some(oi_id) = output_intent_id {
write!(catalog, " /OutputIntents [{} 0 R]", oi_id).unwrap();
}
if let Some(names_id) = embedded_names_id {
write!(catalog, " /Names << /EmbeddedFiles {} 0 R >>", names_id).unwrap();
}
catalog.push_str(" >>");
builder.objects[1].data = catalog.into_bytes();
// Write Pages tree (object 2)
let kids: String = page_obj_ids
.iter()
.map(|id| format!("{} 0 R", id))
.collect::<Vec<_>>()
.join(" ");
builder.objects[2].data = format!(
"<< /Type /Pages /Kids [{}] /Count {} >>",
kids,
page_obj_ids.len()
)
.into_bytes();
// Info dictionary (metadata)
let info_obj_id = if metadata.title.is_some() || metadata.author.is_some() {
let id = builder.objects.len();
let mut info = String::from("<< ");
if let Some(ref title) = metadata.title {
let _ = write!(info, "/Title ({}) ", Self::escape_pdf_string(title));
}
if let Some(ref author) = metadata.author {
let _ = write!(info, "/Author ({}) ", Self::escape_pdf_string(author));
}
if let Some(ref subject) = metadata.subject {
let _ = write!(info, "/Subject ({}) ", Self::escape_pdf_string(subject));
}
let _ = write!(info, "/Producer (Forme 0.6) /Creator (Forme) >>");
builder.objects.push(PdfObject {
id,
data: info.into_bytes(),
});
Some(id)
} else {
None
};
Ok(self.serialize(&builder, info_obj_id))
}
/// Build the PDF content stream for a single page.
fn build_content_stream_for_page(
&self,
page: &LayoutPage,
page_idx: usize,
builder: &PdfBuilder,
page_number: usize,
total_pages: usize,
mut tag_builder: Option<&mut tagged::TagBuilder>,
) -> String {
let mut stream = String::new();
let page_height = page.height;
let mut element_counter = 0usize;
for element in &page.elements {
self.write_element(
&mut stream,
element,
page_height,
builder,
page_idx,
&mut element_counter,
page_number,
total_pages,
tag_builder.as_deref_mut(),
);
}
stream
}
/// Write a single layout element as PDF operators.
#[allow(clippy::too_many_arguments)]
fn write_element(
&self,
stream: &mut String,
element: &LayoutElement,
page_height: f64,
builder: &PdfBuilder,
page_idx: usize,
element_counter: &mut usize,
page_number: usize,
total_pages: usize,
mut tag_builder: Option<&mut tagged::TagBuilder>,
) {
// Tagged PDF: emit BDC (begin marked content) for elements with a node_type
let tagged_mcid = if let Some(ref mut tb) = tag_builder {
if let Some(ref nt) = element.node_type {
let is_header = element.is_header_row;
// For TableCell, inherit is_header_row from its parent row
let mcid = tb.begin_element(nt, is_header, element.alt.as_deref(), page_idx);
let role = tb.map_role_public(nt, is_header);
let _ = writeln!(stream, "/{} <</MCID {}>> BDC", role, mcid);
Some(mcid)
} else {
None
}
} else {
None
};
match &element.draw {
DrawCommand::None => {}
DrawCommand::Rect {
background,
border_width,
border_color,
border_radius,
opacity,
} => {
let x = element.x;
let y = page_height - element.y - element.height;
let w = element.width;
let h = element.height;
// Apply opacity via ExtGState
let needs_opacity = *opacity < 1.0;
if needs_opacity {
if let Some((_, gs_name)) = builder.ext_gstate_map.get(&opacity.to_bits()) {
let _ = writeln!(stream, "q\n/{} gs", gs_name);
}
}
if let Some(bg) = background {
if bg.a > 0.0 {
let _ = writeln!(stream, "q\n{:.3} {:.3} {:.3} rg", bg.r, bg.g, bg.b);
if border_radius.top_left > 0.0 {
self.write_rounded_rect(stream, x, y, w, h, border_radius);
} else {
let _ = writeln!(stream, "{:.2} {:.2} {:.2} {:.2} re", x, y, w, h);
}
let _ = writeln!(stream, "f\nQ");
}
}
let bw = border_width;
if bw.top > 0.0 || bw.right > 0.0 || bw.bottom > 0.0 || bw.left > 0.0 {
if (bw.top - bw.right).abs() < 0.001
&& (bw.right - bw.bottom).abs() < 0.001
&& (bw.bottom - bw.left).abs() < 0.001
{
let bc = &border_color.top;
let _ = writeln!(
stream,
"q\n{:.3} {:.3} {:.3} RG\n{:.2} w",
bc.r, bc.g, bc.b, bw.top
);
if border_radius.top_left > 0.0 {
self.write_rounded_rect(stream, x, y, w, h, border_radius);
} else {
let _ = writeln!(stream, "{:.2} {:.2} {:.2} {:.2} re", x, y, w, h);
}
let _ = writeln!(stream, "S\nQ");
} else {
self.write_border_sides(stream, x, y, w, h, bw, border_color);
}
}
if needs_opacity {
let _ = writeln!(stream, "Q");
}
}
DrawCommand::Text {
lines,
color,
text_decoration,
opacity,
} => {
// Apply opacity via ExtGState
let needs_opacity = *opacity < 1.0;
if needs_opacity {
if let Some((_, gs_name)) = builder.ext_gstate_map.get(&opacity.to_bits()) {
let _ = writeln!(stream, "q\n/{} gs", gs_name);
}
}
for line in lines {
if line.glyphs.is_empty() {
continue;
}
// Group consecutive glyphs by (font_family, font_weight, font_style, font_size, color)
// to support multi-font text runs
let groups = Self::group_glyphs_by_style(&line.glyphs);
let pdf_y = page_height - line.y;
let _ = writeln!(stream, "BT");
// Set word spacing for justification (PDF Tw operator)
if line.word_spacing.abs() > 0.001 {
let _ = writeln!(stream, "{:.4} Tw", line.word_spacing);
}
// Track current text matrix position for relative Td moves
let mut tm_x = 0.0_f64;
let mut tm_y = 0.0_f64;
let mut x_cursor = line.x;
// Track group spans for per-group text decoration
let mut group_spans: Vec<(f64, f64, TextDecoration, Color)> = Vec::new();
for group in &groups {
let first = &group[0];
let glyph_color = first.color.unwrap_or(*color);
let idx = self.font_index(
&first.font_family,
first.font_weight,
first.font_style,
&builder.font_objects,
);
let italic =
matches!(first.font_style, FontStyle::Italic | FontStyle::Oblique);
let font_key = FontKey {
family: first.font_family.clone(),
weight: if first.font_weight >= 600 { 700 } else { 400 },
italic,
};
let font_name = format!("F{}", idx);
// Td is relative to current text matrix position
let dx = x_cursor - tm_x;
let dy = pdf_y - tm_y;
let _ = writeln!(
stream,
"{:.3} {:.3} {:.3} rg\n/{} {:.1} Tf\n{:.2} Tc\n{:.2} {:.2} Td",
glyph_color.r,
glyph_color.g,
glyph_color.b,
font_name,
first.font_size,
first.letter_spacing,
dx,
dy
);
tm_x = x_cursor;
tm_y = pdf_y;
// Check for page number placeholders
let raw_text: String = group.iter().map(|g| g.char_value).collect();
let has_placeholder = raw_text.contains("{{pageNumber}}")
|| raw_text.contains("{{totalPages}}");
let is_custom = builder.custom_font_data.contains_key(&font_key);
if is_custom {
if let Some(embed_data) = builder.custom_font_data.get(&font_key) {
let mut hex = String::new();
if has_placeholder {
// Placeholder text: replace and use char→gid fallback
let text_after = raw_text
.replace("{{pageNumber}}", &page_number.to_string())
.replace("{{totalPages}}", &total_pages.to_string());
for ch in text_after.chars() {
let gid =
embed_data.char_to_gid.get(&ch).copied().unwrap_or(0);
let _ = write!(hex, "{:04X}", gid);
}
} else {
// Shaped text: use glyph IDs directly (remapped through subset)
for g in group.iter() {
let new_gid = embed_data
.gid_remap
.get(&g.glyph_id)
.copied()
.unwrap_or_else(|| {
// Fallback: try char→gid
embed_data
.char_to_gid
.get(&g.char_value)
.copied()
.unwrap_or(0)
});
let _ = write!(hex, "{:04X}", new_gid);
}
}
let _ = writeln!(stream, "<{}> Tj", hex);
} else {
let _ = writeln!(stream, "<> Tj");
}
} else {
let text_after = raw_text
.replace("{{pageNumber}}", &page_number.to_string())
.replace("{{totalPages}}", &total_pages.to_string());
let mut text_str = String::new();
for ch in text_after.chars() {
let b = Self::unicode_to_winansi(ch).unwrap_or(b'?');
match b {
b'\\' => text_str.push_str("\\\\"),
b'(' => text_str.push_str("\\("),
b')' => text_str.push_str("\\)"),
0x20..=0x7E => text_str.push(b as char),
_ => {
let _ = write!(text_str, "\\{:03o}", b);
}
}
}
let _ = writeln!(stream, "({}) Tj", text_str);
}
// Record span for per-group text decoration
let group_start_x = x_cursor;
// Advance x_cursor past this group using shaped advances
// Account for word_spacing on spaces (Tw adds to each space char)
if let Some(last) = group.last() {
let space_count_in_group =
group.iter().filter(|g| g.char_value == ' ').count();
x_cursor = line.x
+ last.x_offset
+ last.x_advance
+ space_count_in_group as f64 * line.word_spacing;
}
// Check if this group has text decoration
let group_dec = first.text_decoration;
if !matches!(group_dec, TextDecoration::None) {
group_spans.push((group_start_x, x_cursor, group_dec, glyph_color));
}
}
let _ = writeln!(stream, "ET");
// Draw per-group text decorations
for (span_x, span_end_x, dec, dec_color) in &group_spans {
match dec {
TextDecoration::Underline => {
let underline_y = pdf_y - 1.5;
let _ = write!(
stream,
"q\n{:.3} {:.3} {:.3} RG\n0.5 w\n{:.2} {:.2} m\n{:.2} {:.2} l\nS\nQ\n",
dec_color.r, dec_color.g, dec_color.b,
span_x, underline_y,
span_end_x, underline_y
);
}
TextDecoration::LineThrough => {
let first_size =
line.glyphs.first().map(|g| g.font_size).unwrap_or(12.0);
let strikethrough_y = pdf_y + first_size * 0.3;
let _ = write!(
stream,
"q\n{:.3} {:.3} {:.3} RG\n0.5 w\n{:.2} {:.2} m\n{:.2} {:.2} l\nS\nQ\n",
dec_color.r, dec_color.g, dec_color.b,
span_x, strikethrough_y,
span_end_x, strikethrough_y
);
}
TextDecoration::None => {}
}
}
// Also handle whole-line decoration from parent style
if group_spans.is_empty() {
if matches!(text_decoration, TextDecoration::Underline) {
let underline_y = pdf_y - 1.5;
let _ = write!(
stream,
"q\n{:.3} {:.3} {:.3} RG\n0.5 w\n{:.2} {:.2} m\n{:.2} {:.2} l\nS\nQ\n",
color.r, color.g, color.b,
line.x, underline_y,
line.x + line.width, underline_y
);
}
if matches!(text_decoration, TextDecoration::LineThrough) {
let first_size =
line.glyphs.first().map(|g| g.font_size).unwrap_or(12.0);
let strikethrough_y = pdf_y + first_size * 0.3;
let _ = write!(
stream,
"q\n{:.3} {:.3} {:.3} RG\n0.5 w\n{:.2} {:.2} m\n{:.2} {:.2} l\nS\nQ\n",
color.r, color.g, color.b,
line.x, strikethrough_y,
line.x + line.width, strikethrough_y
);
}
}
}
if needs_opacity {
let _ = writeln!(stream, "Q");
}
}
DrawCommand::Image { .. } => {
let elem_idx = *element_counter;
*element_counter += 1;
if let Some(&img_idx) = builder.image_index_map.get(&(page_idx, elem_idx)) {
let x = element.x;
let y = page_height - element.y - element.height;
let _ = write!(
stream,
"q\n{:.4} 0 0 {:.4} {:.2} {:.2} cm\n/Im{} Do\nQ\n",
element.width, element.height, x, y, img_idx
);
} else {
// Fallback: grey placeholder if image index not found
let x = element.x;
let y = page_height - element.y - element.height;
let _ = write!(
stream,
"q\n0.9 0.9 0.9 rg\n{:.2} {:.2} {:.2} {:.2} re\nf\nQ\n",
x, y, element.width, element.height
);
}
if tagged_mcid.is_some() {
let _ = writeln!(stream, "EMC");
if let Some(ref mut tb) = tag_builder {
tb.end_element();
}
}
return; // Don't increment counter again for children
}
DrawCommand::ImagePlaceholder => {
*element_counter += 1;
let x = element.x;
let y = page_height - element.y - element.height;
let _ = write!(
stream,
"q\n0.9 0.9 0.9 rg\n{:.2} {:.2} {:.2} {:.2} re\nf\nQ\n",
x, y, element.width, element.height
);
if tagged_mcid.is_some() {
let _ = writeln!(stream, "EMC");
if let Some(ref mut tb) = tag_builder {
tb.end_element();
}
}
return;
}
DrawCommand::Svg {
commands,
width: svg_w,
height: svg_h,
clip,
} => {
let x = element.x;
let y = page_height - element.y - element.height;
// Save state, translate to position, flip Y for SVG coordinate system
let _ = writeln!(stream, "q");
let _ = writeln!(stream, "1 0 0 1 {:.2} {:.2} cm", x, y);
// Scale from viewBox to target size (if viewBox differs from target)
if *svg_w > 0.0 && *svg_h > 0.0 {
let sx = element.width / svg_w;
let sy = element.height / svg_h;
let _ = writeln!(stream, "{:.4} 0 0 {:.4} 0 0 cm", sx, sy);
}
// Flip Y: SVG has Y increasing down, we need PDF Y increasing up
let _ = writeln!(stream, "1 0 0 -1 0 {:.2} cm", svg_h);
// Clip to canvas bounds (Canvas always clips, SVG does not)
if *clip {
let _ = writeln!(stream, "0 0 {:.2} {:.2} re W n", svg_w, svg_h);
}
Self::write_svg_commands(stream, commands);
let _ = writeln!(stream, "Q");
if tagged_mcid.is_some() {
let _ = writeln!(stream, "EMC");
if let Some(ref mut tb) = tag_builder {
tb.end_element();
}
}
return;
}
DrawCommand::Barcode {
bars,
bar_width,
height,
color,
} => {
*element_counter += 1;
let _ = writeln!(stream, "q");
let _ = writeln!(stream, "{:.3} {:.3} {:.3} rg", color.r, color.g, color.b);
for (i, &bar) in bars.iter().enumerate() {
if bar == 1 {
let bx = element.x + i as f64 * bar_width;
let by = page_height - element.y - height;
let _ = writeln!(
stream,
"{:.2} {:.2} {:.2} {:.2} re",
bx, by, bar_width, height
);
}
}
let _ = writeln!(stream, "f\nQ");
if tagged_mcid.is_some() {
let _ = writeln!(stream, "EMC");
if let Some(ref mut tb) = tag_builder {
tb.end_element();
}
}
return;
}
DrawCommand::QrCode {
modules,
module_size,
color,
} => {
*element_counter += 1;
let _ = writeln!(stream, "q");
let _ = writeln!(stream, "{:.3} {:.3} {:.3} rg", color.r, color.g, color.b);
for (row_idx, row) in modules.iter().enumerate() {
for (col_idx, &dark) in row.iter().enumerate() {
if dark {
let mx = element.x + col_idx as f64 * module_size;
let my = page_height - element.y - (row_idx as f64 + 1.0) * module_size;
let _ = writeln!(
stream,
"{:.2} {:.2} {:.2} {:.2} re",
mx, my, module_size, module_size
);
}
}
}
let _ = writeln!(stream, "f\nQ");
if tagged_mcid.is_some() {
let _ = writeln!(stream, "EMC");
if let Some(ref mut tb) = tag_builder {
tb.end_element();
}
}
return;
}
DrawCommand::Chart { primitives } => {
*element_counter += 1;
let _ = writeln!(stream, "q");
// Set up coordinate transform: Y-flip so chart primitives use top-left origin
let _ = writeln!(
stream,
"1 0 0 -1 {:.4} {:.4} cm",
element.x,
page_height - element.y
);
for prim in primitives {
write_chart_primitive(stream, prim, element.height, builder);
}
let _ = writeln!(stream, "Q");
if tagged_mcid.is_some() {
let _ = writeln!(stream, "EMC");
if let Some(ref mut tb) = tag_builder {
tb.end_element();
}
}
return;
}
DrawCommand::Watermark {
lines,
color,
opacity,
angle_rad,
font_family: _,
} => {
let _ = writeln!(stream, "q");
// Set opacity via ExtGState if not fully opaque
if *opacity < 1.0 {
if let Some((_, gs_name)) = builder.ext_gstate_map.get(&opacity.to_bits()) {
let _ = writeln!(stream, "/{} gs", gs_name);
}
}
// Translate to center position (element.x, element.y = page center)
let pdf_cx = element.x;
let pdf_cy = page_height - element.y;
let _ = writeln!(stream, "1 0 0 1 {:.2} {:.2} cm", pdf_cx, pdf_cy);
// Rotate by angle
let cos_a = angle_rad.cos();
let sin_a = angle_rad.sin();
let _ = writeln!(
stream,
"{:.6} {:.6} {:.6} {:.6} 0 0 cm",
cos_a, sin_a, -sin_a, cos_a
);
// Render text centered on origin
let _ = writeln!(stream, "BT");
let _ = writeln!(stream, "{:.3} {:.3} {:.3} rg", color.r, color.g, color.b);
if let Some(line) = lines.first() {
let groups = Self::group_glyphs_by_style(&line.glyphs);
let text_width = line.width;
let cap_height = line.height * 0.7;
let _ = writeln!(
stream,
"{:.2} {:.2} Td",
-text_width / 2.0,
-cap_height / 2.0
);
for group in &groups {
let first = &group[0];
let italic =
matches!(first.font_style, FontStyle::Italic | FontStyle::Oblique);
let fk = FontKey {
family: first.font_family.clone(),
weight: if first.font_weight >= 600 { 700 } else { 400 },
italic,
};
let idx = self.font_index(
&first.font_family,
first.font_weight,
first.font_style,
&builder.font_objects,
);
let font_name = format!("F{}", idx);
let _ = writeln!(stream, "/{} {:.1} Tf", font_name, first.font_size);
let is_custom = builder.custom_font_data.contains_key(&fk);
if is_custom {
if let Some(embed_data) = builder.custom_font_data.get(&fk) {
let mut hex = String::new();
for g in group.iter() {
let gid =
embed_data.gid_remap.get(&g.glyph_id).copied().unwrap_or(0);
let _ = write!(hex, "{:04X}", gid);
}
let _ = writeln!(stream, "<{}> Tj", hex);
}
} else {
let hex_str: String = group
.iter()
.map(|g| format!("{:02X}", g.glyph_id as u8))
.collect();
let _ = writeln!(stream, "<{}> Tj", hex_str);
}
}
}
let _ = writeln!(stream, "ET");
let _ = writeln!(stream, "Q");
if tagged_mcid.is_some() {
let _ = writeln!(stream, "EMC");
if let Some(ref mut tb) = tag_builder {
tb.end_element();
}
}
return;
}
}
// Overflow clipping: wrap children in q/clip/Q when overflow is Hidden
let clip_overflow = matches!(element.overflow, Overflow::Hidden);
if clip_overflow {
let clip_x = element.x;
let clip_y = page_height - element.y - element.height;
let clip_w = element.width;
let clip_h = element.height;
let _ = writeln!(
stream,
"q\n{:.2} {:.2} {:.2} {:.2} re W n",
clip_x, clip_y, clip_w, clip_h
);
}
for child in &element.children {
self.write_element(
stream,
child,
page_height,
builder,
page_idx,
element_counter,
page_number,
total_pages,
tag_builder.as_deref_mut(),
);
}
if clip_overflow {
let _ = writeln!(stream, "Q");
}
// Tagged PDF: emit EMC (end marked content)
if tagged_mcid.is_some() {
let _ = writeln!(stream, "EMC");
if let Some(ref mut tb) = tag_builder {
tb.end_element();
}
}
}
fn write_rounded_rect(
&self,
stream: &mut String,
x: f64,
y: f64,
w: f64,
h: f64,
r: &crate::style::CornerValues,
) {
let k = 0.5522847498;
let tl = r.top_left.min(w / 2.0).min(h / 2.0);
let tr = r.top_right.min(w / 2.0).min(h / 2.0);
let br = r.bottom_right.min(w / 2.0).min(h / 2.0);
let bl = r.bottom_left.min(w / 2.0).min(h / 2.0);
let _ = writeln!(stream, "{:.2} {:.2} m", x + bl, y);
let _ = writeln!(stream, "{:.2} {:.2} l", x + w - br, y);
if br > 0.0 {
let _ = writeln!(
stream,
"{:.2} {:.2} {:.2} {:.2} {:.2} {:.2} c",
x + w - br + br * k,
y,
x + w,
y + br - br * k,
x + w,
y + br
);
}
let _ = writeln!(stream, "{:.2} {:.2} l", x + w, y + h - tr);
if tr > 0.0 {
let _ = writeln!(
stream,
"{:.2} {:.2} {:.2} {:.2} {:.2} {:.2} c",
x + w,
y + h - tr + tr * k,
x + w - tr + tr * k,
y + h,
x + w - tr,
y + h
);
}
let _ = writeln!(stream, "{:.2} {:.2} l", x + tl, y + h);
if tl > 0.0 {
let _ = writeln!(
stream,
"{:.2} {:.2} {:.2} {:.2} {:.2} {:.2} c",
x + tl - tl * k,
y + h,
x,
y + h - tl + tl * k,
x,
y + h - tl
);
}
let _ = writeln!(stream, "{:.2} {:.2} l", x, y + bl);
if bl > 0.0 {
let _ = writeln!(
stream,
"{:.2} {:.2} {:.2} {:.2} {:.2} {:.2} c",
x,
y + bl - bl * k,
x + bl - bl * k,
y,
x + bl,
y
);
}
let _ = writeln!(stream, "h");
}
#[allow(clippy::too_many_arguments)]
fn write_border_sides(
&self,
stream: &mut String,
x: f64,
y: f64,
w: f64,
h: f64,
bw: &Edges,
bc: &crate::style::EdgeValues<Color>,
) {
if bw.top > 0.0 {
let _ = write!(
stream,
"q\n{:.3} {:.3} {:.3} RG\n{:.2} w\n{:.2} {:.2} m\n{:.2} {:.2} l\nS\nQ\n",
bc.top.r,
bc.top.g,
bc.top.b,
bw.top,
x,
y + h,
x + w,
y + h
);
}
if bw.bottom > 0.0 {
let _ = write!(
stream,
"q\n{:.3} {:.3} {:.3} RG\n{:.2} w\n{:.2} {:.2} m\n{:.2} {:.2} l\nS\nQ\n",
bc.bottom.r,
bc.bottom.g,
bc.bottom.b,
bw.bottom,
x,
y,
x + w,
y
);
}
if bw.left > 0.0 {
let _ = write!(
stream,
"q\n{:.3} {:.3} {:.3} RG\n{:.2} w\n{:.2} {:.2} m\n{:.2} {:.2} l\nS\nQ\n",
bc.left.r,
bc.left.g,
bc.left.b,
bw.left,
x,
y,
x,
y + h
);
}
if bw.right > 0.0 {
let _ = write!(
stream,
"q\n{:.3} {:.3} {:.3} RG\n{:.2} w\n{:.2} {:.2} m\n{:.2} {:.2} l\nS\nQ\n",
bc.right.r,
bc.right.g,
bc.right.b,
bw.right,
x + w,
y,
x + w,
y + h
);
}
}
/// Register fonts used across all pages — each unique (family, weight, italic)
/// combination gets its own PDF font object.
fn register_fonts(
&self,
builder: &mut PdfBuilder,
pages: &[LayoutPage],
font_context: &FontContext,
) -> Result<(), FormeError> {
// Collect font usage: glyph IDs, chars, and glyph→char mapping per font
let mut font_usage_map: HashMap<FontKey, FontUsage> = HashMap::new();
for page in pages {
Self::collect_font_usage(&page.elements, &mut font_usage_map);
}
let mut keys: Vec<FontKey> = font_usage_map.keys().cloned().collect();
// Sort for deterministic ordering, then dedup
keys.sort_by(|a, b| {
a.family
.cmp(&b.family)
.then(a.weight.cmp(&b.weight))
.then(a.italic.cmp(&b.italic))
});
keys.dedup();
// Always have at least Helvetica
if keys.is_empty() {
keys.push(FontKey {
family: "Helvetica".to_string(),
weight: 400,
italic: false,
});
}
for key in &keys {
let font_data = font_context.resolve(&key.family, key.weight, key.italic);
match font_data {
FontData::Standard(std_font) => {
let obj_id = builder.objects.len();
// Include /Widths so PDF viewers use our exact metrics
// instead of substituting a system font with different widths
let metrics = std_font.metrics();
let widths_str: String = metrics
.widths
.iter()
.map(|w| w.to_string())
.collect::<Vec<_>>()
.join(" ");
let font_dict = format!(
"<< /Type /Font /Subtype /Type1 /BaseFont /{} \
/Encoding /WinAnsiEncoding \
/FirstChar 32 /LastChar 255 /Widths [{}] >>",
std_font.pdf_name(),
widths_str,
);
builder.objects.push(PdfObject {
id: obj_id,
data: font_dict.into_bytes(),
});
builder.font_objects.push((key.clone(), obj_id));
}
FontData::Custom { data, .. } => {
let usage = font_usage_map.get(key);
let used_glyph_ids = usage.map(|u| &u.glyph_ids);
let used_chars = usage.map(|u| &u.chars);
let glyph_to_char = usage.map(|u| &u.glyph_to_char);
let type0_obj_id = Self::write_custom_font_objects(
builder,
key,
data,
used_glyph_ids.cloned().unwrap_or_default(),
used_chars.cloned().unwrap_or_default(),
glyph_to_char.cloned().unwrap_or_default(),
)?;
builder.font_objects.push((key.clone(), type0_obj_id));
}
}
}
Ok(())
}
/// Collect font usage data from layout elements: used chars, glyph IDs, and glyph→char mapping.
fn collect_font_usage(
elements: &[LayoutElement],
font_usage: &mut HashMap<FontKey, FontUsage>,
) {
for element in elements {
let lines_opt = match &element.draw {
DrawCommand::Text { lines, .. } => Some(lines),
DrawCommand::Watermark { lines, .. } => Some(lines),
_ => None,
};
if let Some(lines) = lines_opt {
for line in lines {
for glyph in &line.glyphs {
let italic =
matches!(glyph.font_style, FontStyle::Italic | FontStyle::Oblique);
let key = FontKey {
family: glyph.font_family.clone(),
weight: if glyph.font_weight >= 600 { 700 } else { 400 },
italic,
};
let usage = font_usage.entry(key).or_insert_with(|| FontUsage {
chars: HashSet::new(),
glyph_ids: HashSet::new(),
glyph_to_char: HashMap::new(),
});
usage.chars.insert(glyph.char_value);
usage.glyph_ids.insert(glyph.glyph_id);
// For ligatures, use the first char of the cluster
usage
.glyph_to_char
.entry(glyph.glyph_id)
.or_insert(glyph.char_value);
// If there's cluster_text, record all chars for this glyph
if let Some(ref ct) = glyph.cluster_text {
// First char already recorded above; cluster_text is for ToUnicode
if let Some(first_char) = ct.chars().next() {
usage
.glyph_to_char
.entry(glyph.glyph_id)
.or_insert(first_char);
}
}
}
}
}
Self::collect_font_usage(&element.children, font_usage);
}
}
/// Walk all pages, create XObject PDF objects for each image,
/// and populate the image_index_map for content stream reference.
fn register_images(&self, builder: &mut PdfBuilder, pages: &[LayoutPage]) {
for (page_idx, page) in pages.iter().enumerate() {
let mut element_counter = 0usize;
Self::collect_images_recursive(&page.elements, page_idx, &mut element_counter, builder);
}
}
fn collect_images_recursive(
elements: &[LayoutElement],
page_idx: usize,
element_counter: &mut usize,
builder: &mut PdfBuilder,
) {
for element in elements {
match &element.draw {
DrawCommand::Image { image_data } => {
let elem_idx = *element_counter;
*element_counter += 1;
let img_idx = builder.image_objects.len();
let xobj_id = Self::write_image_xobject(builder, image_data);
builder.image_objects.push(xobj_id);
builder
.image_index_map
.insert((page_idx, elem_idx), img_idx);
}
DrawCommand::ImagePlaceholder => {
*element_counter += 1;
}
_ => {
Self::collect_images_recursive(
&element.children,
page_idx,
element_counter,
builder,
);
}
}
}
}
/// Collect unique opacity values from all pages and create ExtGState PDF objects.
fn register_ext_gstates(&self, builder: &mut PdfBuilder, pages: &[LayoutPage]) {
let mut unique_opacities: Vec<f64> = Vec::new();
for page in pages {
Self::collect_opacities_recursive(&page.elements, &mut unique_opacities);
}
unique_opacities.sort_by(|a, b| a.partial_cmp(b).unwrap());
unique_opacities.dedup();
for (idx, &opacity) in unique_opacities.iter().enumerate() {
let obj_id = builder.objects.len();
let gs_name = format!("GS{}", idx);
let obj_data = format!(
"<< /Type /ExtGState /ca {:.4} /CA {:.4} >>",
opacity, opacity
);
builder.objects.push(PdfObject {
id: obj_id,
data: obj_data.into_bytes(),
});
let key = opacity.to_bits();
builder.ext_gstate_map.insert(key, (obj_id, gs_name));
}
}
fn collect_opacities_recursive(elements: &[LayoutElement], opacities: &mut Vec<f64>) {
for element in elements {
match &element.draw {
DrawCommand::Rect { opacity, .. }
| DrawCommand::Text { opacity, .. }
| DrawCommand::Watermark { opacity, .. }
if *opacity < 1.0 =>
{
opacities.push(*opacity);
}
DrawCommand::Chart { primitives } => {
for prim in primitives {
if let crate::chart::ChartPrimitive::FilledPath { opacity, .. } = prim {
if *opacity < 1.0 {
opacities.push(*opacity);
}
}
}
}
_ => {}
}
Self::collect_opacities_recursive(&element.children, opacities);
}
}
/// Build the ExtGState resource dict entries for a page.
fn build_ext_gstate_resource_dict(&self, builder: &PdfBuilder) -> String {
if builder.ext_gstate_map.is_empty() {
return String::new();
}
let mut entries: Vec<(&String, usize)> = builder
.ext_gstate_map
.values()
.map(|(obj_id, name)| (name, *obj_id))
.collect();
entries.sort_by_key(|(name, _)| (*name).clone());
entries
.iter()
.map(|(name, obj_id)| format!("/{} {} 0 R", name, obj_id))
.collect::<Vec<_>>()
.join(" ")
}
/// Write a single image as one or two XObject PDF objects.
/// Returns the main XObject ID.
fn write_image_xobject(
builder: &mut PdfBuilder,
image: &crate::image_loader::LoadedImage,
) -> usize {
use crate::image_loader::{ImagePixelData, JpegColorSpace};
match &image.pixel_data {
ImagePixelData::Jpeg { data, color_space } => {
let color_space_str = match color_space {
JpegColorSpace::DeviceRGB => "/DeviceRGB",
JpegColorSpace::DeviceGray => "/DeviceGray",
};
let obj_id = builder.objects.len();
let mut obj_data: Vec<u8> = Vec::new();
let _ = write!(
obj_data,
"<< /Type /XObject /Subtype /Image \
/Width {} /Height {} \
/ColorSpace {} \
/BitsPerComponent 8 \
/Filter /DCTDecode \
/Length {} >>\nstream\n",
image.width_px,
image.height_px,
color_space_str,
data.len()
);
obj_data.extend_from_slice(data);
obj_data.extend_from_slice(b"\nendstream");
builder.objects.push(PdfObject {
id: obj_id,
data: obj_data,
});
obj_id
}
ImagePixelData::Decoded { rgb, alpha } => {
// Write SMask first if alpha channel exists
let smask_id = alpha.as_ref().map(|alpha_data| {
let compressed_alpha = compress_to_vec_zlib(alpha_data, 6);
let smask_obj_id = builder.objects.len();
let mut smask_data: Vec<u8> = Vec::new();
let _ = write!(
smask_data,
"<< /Type /XObject /Subtype /Image \
/Width {} /Height {} \
/ColorSpace /DeviceGray \
/BitsPerComponent 8 \
/Filter /FlateDecode \
/Length {} >>\nstream\n",
image.width_px,
image.height_px,
compressed_alpha.len()
);
smask_data.extend_from_slice(&compressed_alpha);
smask_data.extend_from_slice(b"\nendstream");
builder.objects.push(PdfObject {
id: smask_obj_id,
data: smask_data,
});
smask_obj_id
});
// Write main RGB image XObject
let compressed_rgb = compress_to_vec_zlib(rgb, 6);
let obj_id = builder.objects.len();
let mut obj_data: Vec<u8> = Vec::new();
let smask_ref = smask_id
.map(|id| format!(" /SMask {} 0 R", id))
.unwrap_or_default();
let _ = write!(
obj_data,
"<< /Type /XObject /Subtype /Image \
/Width {} /Height {} \
/ColorSpace /DeviceRGB \
/BitsPerComponent 8 \
/Filter /FlateDecode \
/Length {}{} >>\nstream\n",
image.width_px,
image.height_px,
compressed_rgb.len(),
smask_ref
);
obj_data.extend_from_slice(&compressed_rgb);
obj_data.extend_from_slice(b"\nendstream");
builder.objects.push(PdfObject {
id: obj_id,
data: obj_data,
});
obj_id
}
}
}
/// Build the /XObject resource dict entries for a specific page.
fn build_xobject_resource_dict(&self, page_idx: usize, builder: &PdfBuilder) -> String {
let mut entries: Vec<(usize, usize)> = Vec::new();
for (&(pidx, _), &img_idx) in &builder.image_index_map {
if pidx == page_idx {
let obj_id = builder.image_objects[img_idx];
entries.push((img_idx, obj_id));
}
}
if entries.is_empty() {
return String::new();
}
entries.sort_by_key(|(idx, _)| *idx);
entries.dedup();
entries
.iter()
.map(|(idx, obj_id)| format!("/Im{} {} 0 R", idx, obj_id))
.collect::<Vec<_>>()
.join(" ")
}
/// Write the 5 CIDFont PDF objects for a custom TrueType font.
/// Returns the object ID of the Type0 root font dictionary.
///
/// `used_glyph_ids`: original glyph IDs from shaping (from PositionedGlyph.glyph_id).
/// `used_chars`: characters used (for char→gid fallback, e.g., page number placeholders).
/// `glyph_to_char_map`: maps original glyph ID → first Unicode char (for ToUnicode CMap).
fn write_custom_font_objects(
builder: &mut PdfBuilder,
key: &FontKey,
ttf_data: &[u8],
used_glyph_ids: HashSet<u16>,
used_chars: HashSet<char>,
glyph_to_char_map: HashMap<u16, char>,
) -> Result<usize, FormeError> {
let face = ttf_parser::Face::parse(ttf_data, 0).map_err(|e| {
FormeError::FontError(format!(
"Failed to parse TTF data for font '{}': {}",
key.family, e
))
})?;
let units_per_em = face.units_per_em();
let ascender = face.ascender();
let descender = face.descender();
// Build char → original glyph ID mapping (for fallback/placeholders)
let mut char_to_orig_gid: HashMap<char, u16> = HashMap::new();
for &ch in &used_chars {
if let Some(gid) = face.glyph_index(ch) {
char_to_orig_gid.insert(ch, gid.0);
}
}
// Combine shaped glyph IDs + char-based glyph IDs for subsetting.
// This ensures ligature glyphs (from shaping) AND individual char glyphs
// (for placeholder fallback) are all included.
let mut all_orig_gids: HashSet<u16> = used_glyph_ids.clone();
for &gid in char_to_orig_gid.values() {
all_orig_gids.insert(gid);
}
// Subset the font to only include used glyphs
let (embed_ttf, gid_remap) = match subset_ttf(ttf_data, &all_orig_gids) {
Ok(subset_result) => (subset_result.ttf_data, subset_result.gid_remap),
Err(_) => {
// Subsetting failed — fall back to embedding the full font (identity remap)
let identity: HashMap<u16, u16> =
all_orig_gids.iter().map(|&gid| (gid, gid)).collect();
(ttf_data.to_vec(), identity)
}
};
// Build char→new_gid mapping (for placeholder fallback in content stream)
let char_to_gid: HashMap<char, u16> = char_to_orig_gid
.iter()
.filter_map(|(&ch, &orig_gid)| gid_remap.get(&orig_gid).map(|&new_gid| (ch, new_gid)))
.collect();
// Build glyph_id→new_gid mapping (for shaped content stream)
let gid_remap_for_embed = gid_remap.clone();
// Build new_gid→char mapping for ToUnicode CMap
let mut new_gid_to_char: HashMap<u16, char> = HashMap::new();
// From shaped glyph→char mapping
for (&orig_gid, &ch) in &glyph_to_char_map {
if let Some(&new_gid) = gid_remap.get(&orig_gid) {
new_gid_to_char.entry(new_gid).or_insert(ch);
}
}
// Fill in from char→gid mapping too
for (&ch, &new_gid) in &char_to_gid {
new_gid_to_char.entry(new_gid).or_insert(ch);
}
let pdf_font_name = Self::sanitize_font_name(&key.family, key.weight, key.italic);
// 1. FontFile2 stream — compressed subset TTF bytes
let compressed_ttf = compress_to_vec_zlib(&embed_ttf, 6);
let fontfile2_id = builder.objects.len();
let mut fontfile2_data: Vec<u8> = Vec::new();
let _ = write!(
fontfile2_data,
"<< /Length {} /Length1 {} /Filter /FlateDecode >>\nstream\n",
compressed_ttf.len(),
embed_ttf.len()
);
fontfile2_data.extend_from_slice(&compressed_ttf);
fontfile2_data.extend_from_slice(b"\nendstream");
builder.objects.push(PdfObject {
id: fontfile2_id,
data: fontfile2_data,
});
// Parse the subset font for metrics (width array uses subset GIDs)
let subset_face = ttf_parser::Face::parse(&embed_ttf, 0).unwrap_or_else(|_| face.clone());
let subset_upem = subset_face.units_per_em();
// 2. FontDescriptor
let font_descriptor_id = builder.objects.len();
let bbox = face.global_bounding_box();
let scale = 1000.0 / units_per_em as f64;
let bbox_str = format!(
"[{} {} {} {}]",
(bbox.x_min as f64 * scale) as i32,
(bbox.y_min as f64 * scale) as i32,
(bbox.x_max as f64 * scale) as i32,
(bbox.y_max as f64 * scale) as i32,
);
let flags = 4u32;
let cap_height = face.capital_height().unwrap_or(ascender) as f64 * scale;
let stem_v = if key.weight >= 700 { 120 } else { 80 };
let font_descriptor_dict = format!(
"<< /Type /FontDescriptor /FontName /{} /Flags {} \
/FontBBox {} /ItalicAngle {} \
/Ascent {} /Descent {} /CapHeight {} /StemV {} \
/FontFile2 {} 0 R >>",
pdf_font_name,
flags,
bbox_str,
if key.italic { -12 } else { 0 },
(ascender as f64 * scale) as i32,
(descender as f64 * scale) as i32,
cap_height as i32,
stem_v,
fontfile2_id,
);
builder.objects.push(PdfObject {
id: font_descriptor_id,
data: font_descriptor_dict.into_bytes(),
});
// 3. CIDFont dictionary (DescendantFont)
let cidfont_id = builder.objects.len();
// Build /W array using new_gid→width from subset face
let w_array = Self::build_w_array_from_gids(&gid_remap, &subset_face, subset_upem);
let default_width = subset_face
.glyph_hor_advance(ttf_parser::GlyphId(0))
.map(|adv| (adv as f64 * 1000.0 / subset_upem as f64) as u32)
.unwrap_or(1000);
let cidfont_dict = format!(
"<< /Type /Font /Subtype /CIDFontType2 /BaseFont /{} \
/CIDSystemInfo << /Registry (Adobe) /Ordering (Identity) /Supplement 0 >> \
/FontDescriptor {} 0 R /DW {} /W {} \
/CIDToGIDMap /Identity >>",
pdf_font_name, font_descriptor_id, default_width, w_array,
);
builder.objects.push(PdfObject {
id: cidfont_id,
data: cidfont_dict.into_bytes(),
});
// 4. ToUnicode CMap
let tounicode_id = builder.objects.len();
let cmap_content = Self::build_tounicode_cmap_from_gids(&new_gid_to_char, &pdf_font_name);
let compressed_cmap = compress_to_vec_zlib(cmap_content.as_bytes(), 6);
let mut tounicode_data: Vec<u8> = Vec::new();
let _ = write!(
tounicode_data,
"<< /Length {} /Filter /FlateDecode >>\nstream\n",
compressed_cmap.len()
);
tounicode_data.extend_from_slice(&compressed_cmap);
tounicode_data.extend_from_slice(b"\nendstream");
builder.objects.push(PdfObject {
id: tounicode_id,
data: tounicode_data,
});
// 5. Type0 font dictionary (the root, referenced by /Resources)
let type0_id = builder.objects.len();
let type0_dict = format!(
"<< /Type /Font /Subtype /Type0 /BaseFont /{} \
/Encoding /Identity-H \
/DescendantFonts [{} 0 R] \
/ToUnicode {} 0 R >>",
pdf_font_name, cidfont_id, tounicode_id,
);
builder.objects.push(PdfObject {
id: type0_id,
data: type0_dict.into_bytes(),
});
// Store embedding data for content stream encoding
builder.custom_font_data.insert(
key.clone(),
CustomFontEmbedData {
ttf_data: embed_ttf,
gid_remap: gid_remap_for_embed,
glyph_to_char: glyph_to_char_map,
char_to_gid,
units_per_em,
ascender,
descender,
},
);
Ok(type0_id)
}
/// Build the /W array from gid_remap (orig_gid→new_gid) using the subset face.
fn build_w_array_from_gids(
gid_remap: &HashMap<u16, u16>,
face: &ttf_parser::Face,
units_per_em: u16,
) -> String {
let scale = 1000.0 / units_per_em as f64;
let mut entries: Vec<(u16, u32)> = Vec::new();
let mut seen_gids: HashSet<u16> = HashSet::new();
for &new_gid in gid_remap.values() {
if seen_gids.contains(&new_gid) {
continue;
}
seen_gids.insert(new_gid);
let advance = face
.glyph_hor_advance(ttf_parser::GlyphId(new_gid))
.unwrap_or(0);
let width = (advance as f64 * scale) as u32;
entries.push((new_gid, width));
}
entries.sort_by_key(|(gid, _)| *gid);
// Build the W array using individual entries: gid [width]
let mut result = String::from("[");
for (gid, width) in &entries {
let _ = write!(result, " {} [{}]", gid, width);
}
result.push_str(" ]");
result
}
/// Build a ToUnicode CMap from new_gid → char mapping.
fn build_tounicode_cmap_from_gids(gid_to_char: &HashMap<u16, char>, font_name: &str) -> String {
let mut gid_to_unicode: Vec<(u16, u32)> = gid_to_char
.iter()
.map(|(&gid, &ch)| (gid, ch as u32))
.collect();
gid_to_unicode.sort_by_key(|(gid, _)| *gid);
let mut cmap = String::new();
let _ = writeln!(cmap, "/CIDInit /ProcSet findresource begin");
let _ = writeln!(cmap, "12 dict begin");
let _ = writeln!(cmap, "begincmap");
let _ = writeln!(cmap, "/CIDSystemInfo");
let _ = writeln!(
cmap,
"<< /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def"
);
let _ = writeln!(cmap, "/CMapName /{}-UTF16 def", font_name);
let _ = writeln!(cmap, "/CMapType 2 def");
let _ = writeln!(cmap, "1 begincodespacerange");
let _ = writeln!(cmap, "<0000> <FFFF>");
let _ = writeln!(cmap, "endcodespacerange");
// PDF spec limits beginbfchar to 100 entries per block
for chunk in gid_to_unicode.chunks(100) {
let _ = writeln!(cmap, "{} beginbfchar", chunk.len());
for &(gid, unicode) in chunk {
let _ = writeln!(cmap, "<{:04X}> <{:04X}>", gid, unicode);
}
let _ = writeln!(cmap, "endbfchar");
}
let _ = writeln!(cmap, "endcmap");
let _ = writeln!(cmap, "CMapName currentdict /CMap defineresource pop");
let _ = writeln!(cmap, "end");
let _ = writeln!(cmap, "end");
cmap
}
/// Sanitize a font name for use as a PDF name object.
/// Strips spaces and special characters, appends weight/style suffixes.
fn sanitize_font_name(family: &str, weight: u32, italic: bool) -> String {
let mut name: String = family
.chars()
.filter(|c| c.is_alphanumeric() || *c == '-' || *c == '_')
.collect();
if weight >= 700 {
name.push_str("-Bold");
}
if italic {
name.push_str("-Italic");
}
// If name is empty after sanitization, use a fallback
if name.is_empty() {
name = "CustomFont".to_string();
}
name
}
fn build_font_resource_dict(&self, font_objects: &[(FontKey, usize)]) -> String {
font_objects
.iter()
.enumerate()
.map(|(i, (_, obj_id))| format!("/F{} {} 0 R", i, obj_id))
.collect::<Vec<_>>()
.join(" ")
}
/// Look up the font index (/F0, /F1, etc.) for a given family+weight+style.
fn font_index(
&self,
family: &str,
weight: u32,
font_style: FontStyle,
font_objects: &[(FontKey, usize)],
) -> usize {
let italic = matches!(font_style, FontStyle::Italic | FontStyle::Oblique);
let snapped_weight = if weight >= 600 { 700 } else { 400 };
// Exact match
for (i, (key, _)) in font_objects.iter().enumerate() {
if key.family == family && key.weight == snapped_weight && key.italic == italic {
return i;
}
}
// Fallback: try Helvetica with same weight/style
for (i, (key, _)) in font_objects.iter().enumerate() {
if key.family == "Helvetica" && key.weight == snapped_weight && key.italic == italic {
return i;
}
}
// Last resort: first font
0
}
/// Group consecutive glyphs by (font_family, font_weight, font_style, font_size, color)
/// for multi-font text run rendering.
fn group_glyphs_by_style(glyphs: &[PositionedGlyph]) -> Vec<Vec<&PositionedGlyph>> {
if glyphs.is_empty() {
return vec![];
}
let mut groups: Vec<Vec<&PositionedGlyph>> = Vec::new();
let mut current_group: Vec<&PositionedGlyph> = vec![&glyphs[0]];
for glyph in &glyphs[1..] {
let prev = current_group.last().unwrap();
let same_style = glyph.font_family == prev.font_family
&& glyph.font_weight == prev.font_weight
&& std::mem::discriminant(&glyph.font_style)
== std::mem::discriminant(&prev.font_style)
&& (glyph.font_size - prev.font_size).abs() < 0.01
&& Self::colors_equal(&glyph.color, &prev.color);
if same_style {
current_group.push(glyph);
} else {
groups.push(current_group);
current_group = vec![glyph];
}
}
groups.push(current_group);
groups
}
fn colors_equal(a: &Option<Color>, b: &Option<Color>) -> bool {
match (a, b) {
(None, None) => true,
(Some(ca), Some(cb)) => {
(ca.r - cb.r).abs() < 0.001
&& (ca.g - cb.g).abs() < 0.001
&& (ca.b - cb.b).abs() < 0.001
&& (ca.a - cb.a).abs() < 0.001
}
_ => false,
}
}
/// Collect link annotations from layout elements recursively.
/// When an element has an href, its rect covers all children, so we skip
/// recursing into children to avoid duplicate annotations.
fn collect_link_annotations(
elements: &[LayoutElement],
page_height: f64,
annotations: &mut Vec<LinkAnnotation>,
) {
for element in elements {
if let Some(ref href) = element.href {
if !href.is_empty() {
let pdf_y = page_height - element.y - element.height;
annotations.push(LinkAnnotation {
x: element.x,
y: pdf_y,
width: element.width,
height: element.height,
href: href.clone(),
});
// Don't recurse — parent annotation covers children
continue;
}
}
Self::collect_link_annotations(&element.children, page_height, annotations);
}
}
/// Collect bookmarks from layout elements.
fn collect_bookmarks(
elements: &[LayoutElement],
page_height: f64,
page_obj_id: usize,
bookmarks: &mut Vec<PdfBookmark>,
) {
for element in elements {
if let Some(ref title) = element.bookmark {
let y_pdf = page_height - element.y;
bookmarks.push(PdfBookmark {
title: title.clone(),
page_obj_id,
y_pdf,
});
}
Self::collect_bookmarks(&element.children, page_height, page_obj_id, bookmarks);
}
}
/// Build the PDF outline tree from bookmark entries.
/// Returns the object ID of the /Outlines dictionary.
fn write_outline_tree(&self, builder: &mut PdfBuilder, bookmarks: &[PdfBookmark]) -> usize {
// Reserve the Outlines dictionary object
let outlines_id = builder.objects.len();
builder.objects.push(PdfObject {
id: outlines_id,
data: vec![],
});
// Create outline item objects
let mut item_ids: Vec<usize> = Vec::new();
for _bm in bookmarks {
let item_id = builder.objects.len();
builder.objects.push(PdfObject {
id: item_id,
data: vec![],
});
item_ids.push(item_id);
}
// Fill in outline items with /Prev, /Next, /Parent, /Dest
for (i, (bm, &item_id)) in bookmarks.iter().zip(item_ids.iter()).enumerate() {
let mut dict = format!(
"<< /Title ({}) /Parent {} 0 R /Dest [{} 0 R /XYZ 0 {:.2} null]",
Self::escape_pdf_string(&bm.title),
outlines_id,
bm.page_obj_id,
bm.y_pdf,
);
if i > 0 {
let _ = write!(dict, " /Prev {} 0 R", item_ids[i - 1]);
}
if i + 1 < item_ids.len() {
let _ = write!(dict, " /Next {} 0 R", item_ids[i + 1]);
}
dict.push_str(" >>");
builder.objects[item_id].data = dict.into_bytes();
}
// Fill in Outlines dictionary
let first_id = item_ids.first().copied().unwrap_or(0);
let last_id = item_ids.last().copied().unwrap_or(0);
let outlines_dict = format!(
"<< /Type /Outlines /First {} 0 R /Last {} 0 R /Count {} >>",
first_id,
last_id,
bookmarks.len()
);
builder.objects[outlines_id].data = outlines_dict.into_bytes();
outlines_id
}
/// Write SVG drawing commands to a PDF content stream.
fn write_svg_commands(stream: &mut String, commands: &[SvgCommand]) {
for cmd in commands {
match cmd {
SvgCommand::MoveTo(x, y) => {
let _ = writeln!(stream, "{:.2} {:.2} m", x, y);
}
SvgCommand::LineTo(x, y) => {
let _ = writeln!(stream, "{:.2} {:.2} l", x, y);
}
SvgCommand::CurveTo(x1, y1, x2, y2, x3, y3) => {
let _ = writeln!(
stream,
"{:.2} {:.2} {:.2} {:.2} {:.2} {:.2} c",
x1, y1, x2, y2, x3, y3
);
}
SvgCommand::ClosePath => {
let _ = writeln!(stream, "h");
}
SvgCommand::SetFill(r, g, b) => {
let _ = writeln!(stream, "{:.3} {:.3} {:.3} rg", r, g, b);
}
SvgCommand::SetFillNone => {
// No-op in PDF; handled by fill/stroke selection
}
SvgCommand::SetStroke(r, g, b) => {
let _ = writeln!(stream, "{:.3} {:.3} {:.3} RG", r, g, b);
}
SvgCommand::SetStrokeNone => {
// No-op in PDF
}
SvgCommand::SetStrokeWidth(w) => {
let _ = writeln!(stream, "{:.2} w", w);
}
SvgCommand::Fill => {
let _ = writeln!(stream, "f");
}
SvgCommand::Stroke => {
let _ = writeln!(stream, "S");
}
SvgCommand::FillAndStroke => {
let _ = writeln!(stream, "B");
}
SvgCommand::SetLineCap(cap) => {
let _ = writeln!(stream, "{} J", cap);
}
SvgCommand::SetLineJoin(join) => {
let _ = writeln!(stream, "{} j", join);
}
SvgCommand::SaveState => {
let _ = writeln!(stream, "q");
}
SvgCommand::RestoreState => {
let _ = writeln!(stream, "Q");
}
}
}
}
/// Escape special characters in a PDF string.
pub(crate) fn escape_pdf_string(s: &str) -> String {
s.replace('\\', "\\\\")
.replace('(', "\\(")
.replace(')', "\\)")
}
/// Map a Unicode codepoint to a WinAnsiEncoding byte value.
fn unicode_to_winansi(ch: char) -> Option<u8> {
crate::font::unicode_to_winansi(ch)
}
/// Serialize all objects into the final PDF byte stream.
fn serialize(&self, builder: &PdfBuilder, info_obj_id: Option<usize>) -> Vec<u8> {
let mut output: Vec<u8> = Vec::new();
let mut offsets: Vec<usize> = vec![0; builder.objects.len()];
// Header
output.extend_from_slice(b"%PDF-1.7\n");
output.extend_from_slice(b"%\xe2\xe3\xcf\xd3\n");
for (i, obj) in builder.objects.iter().enumerate().skip(1) {
offsets[i] = output.len();
let header = format!("{} 0 obj\n", i);
output.extend_from_slice(header.as_bytes());
output.extend_from_slice(&obj.data);
output.extend_from_slice(b"\nendobj\n\n");
}
let xref_offset = output.len();
let _ = writeln!(output, "xref\n0 {}", builder.objects.len());
let _ = writeln!(output, "0000000000 65535 f ");
for offset in offsets.iter().skip(1) {
let _ = writeln!(output, "{:010} 00000 n ", offset);
}
let _ = write!(
output,
"trailer\n<< /Size {} /Root 1 0 R",
builder.objects.len()
);
if let Some(info_id) = info_obj_id {
let _ = write!(output, " /Info {} 0 R", info_id);
}
let _ = writeln!(output, " >>\nstartxref\n{}\n%%EOF", xref_offset);
output
}
}
/// Write a single chart drawing primitive to the PDF content stream.
///
/// Called within a Y-flipped coordinate system (1 0 0 -1 x page_h-y cm),
/// so chart primitives use top-left origin (Y increases downward).
fn write_chart_primitive(
stream: &mut String,
prim: &crate::chart::ChartPrimitive,
_chart_height: f64,
builder: &PdfBuilder,
) {
use crate::chart::{ChartPrimitive, TextAnchor};
use crate::font::metrics::unicode_to_winansi;
match prim {
ChartPrimitive::Rect { x, y, w, h, fill } => {
let _ = writeln!(stream, "{:.3} {:.3} {:.3} rg", fill.r, fill.g, fill.b);
let _ = writeln!(stream, "{:.2} {:.2} {:.2} {:.2} re f", x, y, w, h);
}
ChartPrimitive::Line {
x1,
y1,
x2,
y2,
stroke,
width,
} => {
let _ = writeln!(stream, "{:.3} {:.3} {:.3} RG", stroke.r, stroke.g, stroke.b);
let _ = writeln!(stream, "{:.2} w", width);
let _ = writeln!(stream, "{:.2} {:.2} m {:.2} {:.2} l S", x1, y1, x2, y2);
}
ChartPrimitive::Polyline {
points,
stroke,
width,
} => {
if points.len() < 2 {
return;
}
let _ = writeln!(stream, "{:.3} {:.3} {:.3} RG", stroke.r, stroke.g, stroke.b);
let _ = writeln!(stream, "{:.2} w", width);
let _ = writeln!(stream, "{:.2} {:.2} m", points[0].0, points[0].1);
for &(px, py) in &points[1..] {
let _ = writeln!(stream, "{:.2} {:.2} l", px, py);
}
let _ = writeln!(stream, "S");
}
ChartPrimitive::FilledPath {
points,
fill,
opacity,
} => {
if points.len() < 3 {
return;
}
let _ = writeln!(stream, "q");
// Set opacity via ExtGState if available
if *opacity < 1.0 {
if let Some((_, gs_name)) = builder.ext_gstate_map.get(&opacity.to_bits()) {
let _ = writeln!(stream, "/{} gs", gs_name);
}
}
let _ = writeln!(stream, "{:.3} {:.3} {:.3} rg", fill.r, fill.g, fill.b);
let _ = writeln!(stream, "{:.2} {:.2} m", points[0].0, points[0].1);
for &(px, py) in &points[1..] {
let _ = writeln!(stream, "{:.2} {:.2} l", px, py);
}
let _ = writeln!(stream, "h f");
let _ = writeln!(stream, "Q");
}
ChartPrimitive::Circle { cx, cy, r, fill } => {
// Approximate circle with 4 cubic bezier curves
let kappa: f64 = 0.5523;
let kr = kappa * r;
let _ = writeln!(stream, "{:.3} {:.3} {:.3} rg", fill.r, fill.g, fill.b);
let _ = writeln!(stream, "{:.2} {:.2} m", cx + r, cy);
let _ = writeln!(
stream,
"{:.2} {:.2} {:.2} {:.2} {:.2} {:.2} c",
cx + r,
cy + kr,
cx + kr,
cy + r,
cx,
cy + r
);
let _ = writeln!(
stream,
"{:.2} {:.2} {:.2} {:.2} {:.2} {:.2} c",
cx - kr,
cy + r,
cx - r,
cy + kr,
cx - r,
cy
);
let _ = writeln!(
stream,
"{:.2} {:.2} {:.2} {:.2} {:.2} {:.2} c",
cx - r,
cy - kr,
cx - kr,
cy - r,
cx,
cy - r
);
let _ = writeln!(
stream,
"{:.2} {:.2} {:.2} {:.2} {:.2} {:.2} c",
cx + kr,
cy - r,
cx + r,
cy - kr,
cx + r,
cy
);
let _ = writeln!(stream, "f");
}
ChartPrimitive::ArcSector {
cx,
cy,
r,
start_angle,
end_angle,
fill,
} => {
let _ = writeln!(stream, "{:.3} {:.3} {:.3} rg", fill.r, fill.g, fill.b);
// Move to center
let _ = writeln!(stream, "{:.2} {:.2} m", cx, cy);
// Line to arc start
let sx = cx + r * start_angle.cos();
let sy = cy + r * start_angle.sin();
let _ = writeln!(stream, "{:.2} {:.2} l", sx, sy);
// Approximate arc with cubic bezier segments (max 90° per segment)
let mut angle = *start_angle;
let total = end_angle - start_angle;
let segments = ((total.abs() / std::f64::consts::FRAC_PI_2).ceil() as usize).max(1);
let step = total / segments as f64;
for _ in 0..segments {
let a1 = angle;
let a2 = angle + step;
let alpha = 4.0 / 3.0 * ((a2 - a1) / 4.0).tan();
let p1x = cx + r * a1.cos();
let p1y = cy + r * a1.sin();
let p2x = cx + r * a2.cos();
let p2y = cy + r * a2.sin();
let cp1x = p1x - alpha * r * a1.sin();
let cp1y = p1y + alpha * r * a1.cos();
let cp2x = p2x + alpha * r * a2.sin();
let cp2y = p2y - alpha * r * a2.cos();
let _ = writeln!(
stream,
"{:.4} {:.4} {:.4} {:.4} {:.4} {:.4} c",
cp1x, cp1y, cp2x, cp2y, p2x, p2y
);
angle = a2;
}
// Close path back to center and fill
let _ = writeln!(stream, "h f");
}
ChartPrimitive::Label {
text,
x,
y,
font_size,
color,
anchor,
} => {
// Measure text width for anchor alignment
let metrics = crate::font::StandardFont::Helvetica.metrics();
let text_width = metrics.measure_string(text, *font_size, 0.0);
let x_offset = match anchor {
TextAnchor::Left => 0.0,
TextAnchor::Center => -text_width / 2.0,
TextAnchor::Right => -text_width,
};
// Find Helvetica font index in font_objects
let font_idx = builder
.font_objects
.iter()
.enumerate()
.find(|(_, (key, _))| key.family == "Helvetica" && key.weight == 400 && !key.italic)
.map(|(i, _)| i)
.unwrap_or(0);
// Encode text to WinAnsi
let encoded: String = text
.chars()
.map(|ch| {
if let Some(code) = unicode_to_winansi(ch) {
code as char
} else if (ch as u32) >= 32 && (ch as u32) <= 255 {
ch
} else {
'?'
}
})
.collect();
let escaped = pdf_escape_string(&encoded);
// Undo Y-flip for text rendering, then position
let _ = writeln!(stream, "q");
let _ = writeln!(stream, "1 0 0 -1 {:.4} {:.4} cm", x + x_offset, *y);
let _ = writeln!(
stream,
"BT /F{} {:.1} Tf {:.3} {:.3} {:.3} rg 0 0 Td ({}) Tj ET",
font_idx, font_size, color.r, color.g, color.b, escaped
);
let _ = writeln!(stream, "Q");
}
}
}
/// Escape a string for use in a PDF text string (parentheses and backslash).
fn pdf_escape_string(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for ch in s.chars() {
match ch {
'(' => out.push_str("\\("),
')' => out.push_str("\\)"),
'\\' => out.push_str("\\\\"),
_ => out.push(ch),
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use crate::font::FontContext;
#[test]
fn test_escape_pdf_string() {
assert_eq!(
PdfWriter::escape_pdf_string("Hello (World)"),
"Hello \\(World\\)"
);
assert_eq!(PdfWriter::escape_pdf_string("back\\slash"), "back\\\\slash");
}
#[test]
fn test_empty_document_produces_valid_pdf() {
let writer = PdfWriter::new();
let font_context = FontContext::new();
let pages = vec![LayoutPage {
width: 595.28,
height: 841.89,
elements: vec![],
fixed_header: vec![],
fixed_footer: vec![],
watermarks: vec![],
config: PageConfig::default(),
}];
let metadata = Metadata::default();
let bytes = writer
.write(&pages, &metadata, &font_context, false, None, None)
.unwrap();
assert!(bytes.starts_with(b"%PDF-1.7"));
assert!(bytes.windows(5).any(|w| w == b"%%EOF"));
assert!(bytes.windows(4).any(|w| w == b"xref"));
assert!(bytes.windows(7).any(|w| w == b"trailer"));
}
#[test]
fn test_metadata_in_pdf() {
let writer = PdfWriter::new();
let font_context = FontContext::new();
let pages = vec![LayoutPage {
width: 595.28,
height: 841.89,
elements: vec![],
fixed_header: vec![],
fixed_footer: vec![],
watermarks: vec![],
config: PageConfig::default(),
}];
let metadata = Metadata {
title: Some("Test Document".to_string()),
author: Some("Forme".to_string()),
subject: None,
creator: None,
lang: None,
};
let bytes = writer
.write(&pages, &metadata, &font_context, false, None, None)
.unwrap();
let text = String::from_utf8_lossy(&bytes);
assert!(text.contains("/Title (Test Document)"));
assert!(text.contains("/Author (Forme)"));
}
#[test]
fn test_bold_font_registered_separately() {
let writer = PdfWriter::new();
let font_context = FontContext::new();
// Create pages with both regular and bold text
let pages = vec![LayoutPage {
width: 595.28,
height: 841.89,
elements: vec![
LayoutElement {
x: 54.0,
y: 54.0,
width: 100.0,
height: 16.8,
draw: DrawCommand::Text {
lines: vec![TextLine {
x: 54.0,
y: 66.0,
width: 50.0,
height: 16.8,
glyphs: vec![PositionedGlyph {
glyph_id: 65,
x_offset: 0.0,
y_offset: 0.0,
x_advance: 8.0,
font_size: 12.0,
font_family: "Helvetica".to_string(),
font_weight: 400,
font_style: FontStyle::Normal,
char_value: 'A',
color: None,
href: None,
text_decoration: TextDecoration::None,
letter_spacing: 0.0,
cluster_text: None,
}],
word_spacing: 0.0,
}],
color: Color::BLACK,
text_decoration: TextDecoration::None,
opacity: 1.0,
},
children: vec![],
node_type: None,
resolved_style: None,
source_location: None,
href: None,
bookmark: None,
alt: None,
is_header_row: false,
overflow: Overflow::default(),
},
LayoutElement {
x: 54.0,
y: 74.0,
width: 100.0,
height: 16.8,
draw: DrawCommand::Text {
lines: vec![TextLine {
x: 54.0,
y: 86.0,
width: 50.0,
height: 16.8,
glyphs: vec![PositionedGlyph {
glyph_id: 65,
x_offset: 0.0,
y_offset: 0.0,
x_advance: 8.0,
font_size: 12.0,
font_family: "Helvetica".to_string(),
font_weight: 700,
font_style: FontStyle::Normal,
char_value: 'A',
color: None,
href: None,
text_decoration: TextDecoration::None,
letter_spacing: 0.0,
cluster_text: None,
}],
word_spacing: 0.0,
}],
color: Color::BLACK,
text_decoration: TextDecoration::None,
opacity: 1.0,
},
children: vec![],
node_type: None,
resolved_style: None,
source_location: None,
href: None,
bookmark: None,
alt: None,
is_header_row: false,
overflow: Overflow::default(),
},
],
fixed_header: vec![],
fixed_footer: vec![],
watermarks: vec![],
config: PageConfig::default(),
}];
let metadata = Metadata::default();
let bytes = writer
.write(&pages, &metadata, &font_context, false, None, None)
.unwrap();
let text = String::from_utf8_lossy(&bytes);
// Should have both Helvetica and Helvetica-Bold registered
assert!(
text.contains("Helvetica"),
"Should contain regular Helvetica"
);
assert!(
text.contains("Helvetica-Bold"),
"Should contain Helvetica-Bold"
);
}
#[test]
fn test_sanitize_font_name() {
assert_eq!(PdfWriter::sanitize_font_name("Inter", 400, false), "Inter");
assert_eq!(
PdfWriter::sanitize_font_name("Inter", 700, false),
"Inter-Bold"
);
assert_eq!(
PdfWriter::sanitize_font_name("Inter", 400, true),
"Inter-Italic"
);
assert_eq!(
PdfWriter::sanitize_font_name("Inter", 700, true),
"Inter-Bold-Italic"
);
assert_eq!(
PdfWriter::sanitize_font_name("Noto Sans", 400, false),
"NotoSans"
);
assert_eq!(
PdfWriter::sanitize_font_name("Font (Display)", 400, false),
"FontDisplay"
);
}
#[test]
fn test_tounicode_cmap_format() {
// glyph_to_char: maps subset glyph IDs → Unicode chars
let mut glyph_to_char = HashMap::new();
glyph_to_char.insert(36u16, 'A');
glyph_to_char.insert(37u16, 'B');
let cmap = PdfWriter::build_tounicode_cmap_from_gids(&glyph_to_char, "TestFont");
assert!(cmap.contains("begincmap"), "CMap should contain begincmap");
assert!(cmap.contains("endcmap"), "CMap should contain endcmap");
assert!(
cmap.contains("beginbfchar"),
"CMap should contain beginbfchar"
);
assert!(cmap.contains("endbfchar"), "CMap should contain endbfchar");
assert!(
cmap.contains("<0024> <0041>"),
"Should map gid 0x0024 to Unicode 'A' 0x0041"
);
assert!(
cmap.contains("<0025> <0042>"),
"Should map gid 0x0025 to Unicode 'B' 0x0042"
);
assert!(
cmap.contains("begincodespacerange"),
"Should define codespace range"
);
assert!(
cmap.contains("<0000> <FFFF>"),
"Codespace should be 0000-FFFF"
);
}
#[test]
fn test_w_array_format() {
let mut char_to_gid = HashMap::new();
char_to_gid.insert('A', 36u16);
// We need actual font data to test this properly, so just verify format
// with a minimal check that the function produces valid output
let w_array_str = "[ 36 [600] ]";
assert!(w_array_str.starts_with('['));
assert!(w_array_str.ends_with(']'));
}
#[test]
fn test_hex_glyph_encoding() {
// Verify the hex format used for custom font text encoding
let gid: u16 = 0x0041;
let hex = format!("{:04X}", gid);
assert_eq!(hex, "0041");
let gids = [0x0041u16, 0x0042, 0x0043];
let hex_str: String = gids.iter().map(|g| format!("{:04X}", g)).collect();
assert_eq!(hex_str, "004100420043");
}
#[test]
fn test_standard_font_still_uses_text_string() {
let writer = PdfWriter::new();
let font_context = FontContext::new();
let pages = vec![LayoutPage {
width: 595.28,
height: 841.89,
elements: vec![LayoutElement {
x: 54.0,
y: 54.0,
width: 100.0,
height: 16.8,
draw: DrawCommand::Text {
lines: vec![TextLine {
x: 54.0,
y: 66.0,
width: 50.0,
height: 16.8,
glyphs: vec![PositionedGlyph {
glyph_id: 65,
x_offset: 0.0,
y_offset: 0.0,
x_advance: 8.0,
font_size: 12.0,
font_family: "Helvetica".to_string(),
font_weight: 400,
font_style: FontStyle::Normal,
char_value: 'H',
color: None,
href: None,
text_decoration: TextDecoration::None,
letter_spacing: 0.0,
cluster_text: None,
}],
word_spacing: 0.0,
}],
color: Color::BLACK,
text_decoration: TextDecoration::None,
opacity: 1.0,
},
children: vec![],
node_type: None,
resolved_style: None,
source_location: None,
href: None,
bookmark: None,
alt: None,
is_header_row: false,
overflow: Overflow::default(),
}],
fixed_header: vec![],
fixed_footer: vec![],
watermarks: vec![],
config: PageConfig::default(),
}];
let metadata = Metadata::default();
let bytes = writer
.write(&pages, &metadata, &font_context, false, None, None)
.unwrap();
let text = String::from_utf8_lossy(&bytes);
// Standard fonts should use Type1, not CIDFontType2
assert!(
text.contains("/Type1"),
"Standard font should use Type1 subtype"
);
assert!(
!text.contains("CIDFontType2"),
"Standard font should not use CIDFontType2"
);
}
}