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
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
use crate::document::Document;
use crate::error::{PdfError, Result};
use crate::objects::{Dictionary, Object, ObjectId};
use crate::text::fonts::embedding::CjkFontType;
use crate::text::fonts::truetype::CmapSubtable;
use crate::writer::{ObjectStreamConfig, ObjectStreamWriter, XRefStreamWriter};
use chrono::{DateTime, Utc};
use std::collections::HashMap;
use std::io::{BufWriter, Write};
use std::path::Path;
/// Configuration for PDF writer
#[derive(Debug, Clone)]
pub struct WriterConfig {
/// Use XRef streams instead of traditional XRef tables (PDF 1.5+)
pub use_xref_streams: bool,
/// Use Object Streams for compressing multiple objects together (PDF 1.5+)
pub use_object_streams: bool,
/// PDF version to write (default: 1.7)
pub pdf_version: String,
/// Enable compression for streams (default: true)
pub compress_streams: bool,
/// Enable incremental updates mode (ISO 32000-1 §7.5.6)
pub incremental_update: bool,
}
impl Default for WriterConfig {
fn default() -> Self {
Self {
use_xref_streams: false,
use_object_streams: false,
pdf_version: "1.7".to_string(),
compress_streams: true,
incremental_update: false,
}
}
}
impl WriterConfig {
/// Create a modern PDF 1.5+ configuration with all compression features enabled
pub fn modern() -> Self {
Self {
use_xref_streams: true,
use_object_streams: true,
pdf_version: "1.5".to_string(),
compress_streams: true,
incremental_update: false,
}
}
/// Create a legacy PDF 1.4 configuration without modern compression
pub fn legacy() -> Self {
Self {
use_xref_streams: false,
use_object_streams: false,
pdf_version: "1.4".to_string(),
compress_streams: true,
incremental_update: false,
}
}
/// Create configuration for incremental updates (ISO 32000-1 §7.5.6)
pub fn incremental() -> Self {
Self {
use_xref_streams: false,
use_object_streams: false,
pdf_version: "1.4".to_string(),
compress_streams: true,
incremental_update: true,
}
}
}
pub struct PdfWriter<W: Write> {
writer: W,
xref_positions: HashMap<ObjectId, u64>,
current_position: u64,
next_object_id: u32,
// Maps for tracking object IDs during writing
catalog_id: Option<ObjectId>,
pages_id: Option<ObjectId>,
info_id: Option<ObjectId>,
// Maps for tracking form fields and their widgets
#[allow(dead_code)]
field_widget_map: HashMap<String, Vec<ObjectId>>, // field name -> widget IDs
#[allow(dead_code)]
field_id_map: HashMap<String, ObjectId>, // field name -> field ID
form_field_ids: Vec<ObjectId>, // form field IDs to add to page annotations
page_ids: Vec<ObjectId>, // page IDs for form field references
// Configuration
config: WriterConfig,
// Characters used in document (for font subsetting)
document_used_chars: Option<std::collections::HashSet<char>>,
// Object stream buffering (when use_object_streams is enabled)
buffered_objects: HashMap<ObjectId, Vec<u8>>,
compressed_object_map: HashMap<ObjectId, (ObjectId, u32)>, // obj_id -> (stream_id, index)
// Incremental update support (ISO 32000-1 §7.5.6)
prev_xref_offset: Option<u64>,
base_pdf_size: Option<u64>,
// Encryption support
encrypt_obj_id: Option<ObjectId>,
file_id: Option<Vec<u8>>,
encryption_state: Option<WriterEncryptionState>,
pending_encrypt_dict: Option<Dictionary>,
}
/// Holds the encryption key and encryptor for encrypting objects during write
struct WriterEncryptionState {
encryptor: crate::encryption::ObjectEncryptor,
}
impl<W: Write> PdfWriter<W> {
pub fn new_with_writer(writer: W) -> Self {
Self::with_config(writer, WriterConfig::default())
}
pub fn with_config(writer: W, config: WriterConfig) -> Self {
Self {
writer,
xref_positions: HashMap::new(),
current_position: 0,
next_object_id: 1, // Start at 1 for sequential numbering
catalog_id: None,
pages_id: None,
info_id: None,
field_widget_map: HashMap::new(),
field_id_map: HashMap::new(),
form_field_ids: Vec::new(),
page_ids: Vec::new(),
config,
document_used_chars: None,
buffered_objects: HashMap::new(),
compressed_object_map: HashMap::new(),
prev_xref_offset: None,
base_pdf_size: None,
encrypt_obj_id: None,
file_id: None,
encryption_state: None,
pending_encrypt_dict: None,
}
}
pub fn write_document(&mut self, document: &mut Document) -> Result<()> {
// Store used characters for font subsetting
if !document.used_characters.is_empty() {
self.document_used_chars = Some(document.used_characters.clone());
}
self.write_header()?;
// Reserve object IDs for fixed objects (written in order)
self.catalog_id = Some(self.allocate_object_id());
self.pages_id = Some(self.allocate_object_id());
self.info_id = Some(self.allocate_object_id());
// Initialize encryption state BEFORE writing objects
// (objects need to be encrypted as they are written)
if let Some(ref encryption) = document.encryption {
self.init_encryption(encryption)?;
}
// Write custom fonts first (so pages can reference them)
let font_refs = self.write_fonts(document)?;
// Write pages (they contain widget annotations and font references)
self.write_pages(document, &font_refs)?;
// Write form fields (must be after pages so we can track widgets)
self.write_form_fields(document)?;
// Write catalog (must be after forms so AcroForm has correct field references)
self.write_catalog(document)?;
// Write document info
self.write_info(document)?;
// Write /Encrypt dict AFTER all objects (it must NOT be encrypted itself)
self.write_encryption_dict()?;
// Flush buffered objects as object streams (if enabled)
if self.config.use_object_streams {
self.flush_object_streams()?;
}
// Write xref table or stream
let xref_position = self.current_position;
if self.config.use_xref_streams {
self.write_xref_stream()?;
} else {
self.write_xref()?;
}
// Write trailer (only for traditional xref)
if !self.config.use_xref_streams {
self.write_trailer(xref_position)?;
}
if let Ok(()) = self.writer.flush() {
// Flush succeeded
}
Ok(())
}
/// Write an incremental update to an existing PDF (ISO 32000-1 §7.5.6)
///
/// This appends new/modified objects to the end of an existing PDF file
/// without modifying the original content. The base PDF is copied first,
/// then new pages are ADDED to the end of the document.
///
/// For REPLACING specific pages (e.g., form filling), use `write_incremental_with_page_replacement`.
///
/// # Arguments
///
/// * `base_pdf_path` - Path to the existing PDF file
/// * `document` - Document containing NEW pages to add
///
/// # Returns
///
/// Returns Ok(()) if the incremental update was written successfully
///
/// # Example - Adding Pages
///
/// ```no_run
/// use oxidize_pdf::{Document, Page, writer::{PdfWriter, WriterConfig}};
/// use std::fs::File;
/// use std::io::BufWriter;
///
/// let mut doc = Document::new();
/// doc.add_page(Page::a4()); // This will be added as a NEW page
///
/// let file = File::create("output.pdf").unwrap();
/// let writer = BufWriter::new(file);
/// let config = WriterConfig::incremental();
/// let mut pdf_writer = PdfWriter::with_config(writer, config);
/// pdf_writer.write_incremental_update("base.pdf", &mut doc).unwrap();
/// ```
pub fn write_incremental_update(
&mut self,
base_pdf_path: impl AsRef<std::path::Path>,
document: &mut Document,
) -> Result<()> {
use std::io::{BufReader, Read, Seek, SeekFrom};
// Step 1: Parse the base PDF to get catalog and page information
let base_pdf_file = std::fs::File::open(base_pdf_path.as_ref())?;
let mut pdf_reader = crate::parser::PdfReader::new(BufReader::new(base_pdf_file))?;
// Get catalog from base PDF
let base_catalog = pdf_reader.catalog()?;
// Extract Pages reference from base catalog
let (base_pages_id, base_pages_gen) = base_catalog
.get("Pages")
.and_then(|obj| {
if let crate::parser::objects::PdfObject::Reference(id, gen) = obj {
Some((*id, *gen))
} else {
None
}
})
.ok_or_else(|| {
crate::error::PdfError::InvalidStructure(
"Base PDF catalog missing /Pages reference".to_string(),
)
})?;
// Get the pages dictionary from the base PDF using the reference
let base_pages_obj = pdf_reader.get_object(base_pages_id, base_pages_gen)?;
let base_pages_kids = if let crate::parser::objects::PdfObject::Dictionary(dict) =
base_pages_obj
{
dict.get("Kids")
.and_then(|obj| {
if let crate::parser::objects::PdfObject::Array(arr) = obj {
// Convert PdfObject::Reference to writer::Object::Reference
// PdfArray.0 gives access to the internal Vec<PdfObject>
Some(
arr.0
.iter()
.filter_map(|item| {
if let crate::parser::objects::PdfObject::Reference(id, gen) =
item
{
Some(crate::objects::Object::Reference(
crate::objects::ObjectId::new(*id, *gen),
))
} else {
None
}
})
.collect::<Vec<_>>(),
)
} else {
None
}
})
.unwrap_or_default()
} else {
Vec::new()
};
// Count existing pages
let base_page_count = base_pages_kids.len();
// Step 2: Copy the base PDF content
let base_pdf = std::fs::File::open(base_pdf_path.as_ref())?;
let mut base_reader = BufReader::new(base_pdf);
// Find the startxref offset in the base PDF
base_reader.seek(SeekFrom::End(-100))?;
let mut end_buffer = vec![0u8; 100];
let bytes_read = base_reader.read(&mut end_buffer)?;
end_buffer.truncate(bytes_read);
let end_str = String::from_utf8_lossy(&end_buffer);
let prev_xref = if let Some(startxref_pos) = end_str.find("startxref") {
let after_startxref = &end_str[startxref_pos + 9..];
let number_str: String = after_startxref
.chars()
.skip_while(|c| c.is_whitespace())
.take_while(|c| c.is_ascii_digit())
.collect();
number_str.parse::<u64>().map_err(|_| {
crate::error::PdfError::InvalidStructure(
"Could not parse startxref offset".to_string(),
)
})?
} else {
return Err(crate::error::PdfError::InvalidStructure(
"startxref not found in base PDF".to_string(),
));
};
// Copy entire base PDF
base_reader.seek(SeekFrom::Start(0))?;
let base_size = std::io::copy(&mut base_reader, &mut self.writer)? as u64;
// Store base PDF info for trailer
self.prev_xref_offset = Some(prev_xref);
self.base_pdf_size = Some(base_size);
self.current_position = base_size;
// Step 3: Write new/modified objects only
if !document.used_characters.is_empty() {
self.document_used_chars = Some(document.used_characters.clone());
}
// Allocate IDs for new objects
self.catalog_id = Some(self.allocate_object_id());
self.pages_id = Some(self.allocate_object_id());
self.info_id = Some(self.allocate_object_id());
// Write custom fonts first
let font_refs = self.write_fonts(document)?;
// Write NEW pages only (not rewriting all pages)
self.write_pages(document, &font_refs)?;
// Write form fields
self.write_form_fields(document)?;
// Step 4: Write modified catalog that references BOTH old and new pages
let catalog_id = self.get_catalog_id()?;
let new_pages_id = self.get_pages_id()?;
let mut catalog = crate::objects::Dictionary::new();
catalog.set("Type", crate::objects::Object::Name("Catalog".to_string()));
catalog.set("Pages", crate::objects::Object::Reference(new_pages_id));
// Note: For now, we only preserve the Pages reference.
// Full catalog preservation (Outlines, AcroForm, etc.) would require
// converting parser::PdfObject to writer::Object, which is a future enhancement.
self.write_object(catalog_id, crate::objects::Object::Dictionary(catalog))?;
// Step 5: Write new Pages tree that includes BOTH base pages and new pages
let mut all_pages_kids = base_pages_kids;
// Add references to new pages
for page_id in &self.page_ids {
all_pages_kids.push(crate::objects::Object::Reference(*page_id));
}
let mut pages_dict = crate::objects::Dictionary::new();
pages_dict.set("Type", crate::objects::Object::Name("Pages".to_string()));
pages_dict.set("Kids", crate::objects::Object::Array(all_pages_kids));
pages_dict.set(
"Count",
crate::objects::Object::Integer((base_page_count + self.page_ids.len()) as i64),
);
self.write_object(new_pages_id, crate::objects::Object::Dictionary(pages_dict))?;
// Write document info
self.write_info(document)?;
// Step 6: Write new XRef table with /Prev pointer
let xref_position = self.current_position;
self.write_xref()?;
// Step 7: Write trailer with /Prev
self.write_trailer(xref_position)?;
self.writer.flush()?;
Ok(())
}
/// Replaces pages in an existing PDF using incremental update structure (ISO 32000-1 §7.5.6).
///
/// # Use Cases
/// This API is ideal for:
/// - **Dynamic page generation**: You have logic to generate complete pages from data
/// - **Template variants**: Switching between multiple pre-generated page versions
/// - **Page repair**: Regenerating corrupted or problematic pages from scratch
///
/// # Manual Content Recreation Required
/// **IMPORTANT**: This API requires you to **manually recreate** the entire page content.
/// The replaced page will contain ONLY what you provide in `document.pages`.
///
/// If you need to modify existing content (e.g., fill form fields on an existing page),
/// you must recreate the base content AND add your modifications.
///
/// # Example: Form Filling with Manual Recreation
/// ```rust,no_run
/// use oxidize_pdf::{Document, Page, text::Font, writer::{PdfWriter, WriterConfig}};
/// use std::fs::File;
/// use std::io::BufWriter;
///
/// let mut filled_doc = Document::new();
/// let mut page = Page::a4();
///
/// // Step 1: Recreate the template content (REQUIRED - you must know this)
/// page.text()
/// .set_font(Font::Helvetica, 12.0)
/// .at(50.0, 700.0)
/// .write("Name: _______________________________")?;
///
/// // Step 2: Add your filled data at the appropriate position
/// page.text()
/// .set_font(Font::Helvetica, 12.0)
/// .at(110.0, 700.0)
/// .write("John Smith")?;
///
/// filled_doc.add_page(page);
///
/// let file = File::create("filled.pdf")?;
/// let writer = BufWriter::new(file);
/// let mut pdf_writer = PdfWriter::with_config(writer, WriterConfig::incremental());
///
/// pdf_writer.write_incremental_with_page_replacement("template.pdf", &mut filled_doc)?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// # ISO Compliance
/// This function implements ISO 32000-1 §7.5.6 incremental updates:
/// - Preserves original PDF bytes (append-only)
/// - Uses /Prev pointer in trailer
/// - Maintains cross-reference chain
/// - Compatible with digital signatures on base PDF
///
/// # Future: Automatic Overlay API
/// For automatic form filling (load + modify + save) without manual recreation,
/// a future `write_incremental_with_overlay()` API is planned. This will require
/// implementation of `Document::load()` and content overlay system.
///
/// # Parameters
/// - `base_pdf_path`: Path to the existing PDF to modify
/// - `document`: Document containing replacement pages (first N pages will replace base pages 0..N-1)
///
/// # Returns
/// - `Ok(())` if incremental update was written successfully
/// - `Err(PdfError)` if base PDF cannot be read, parsed, or structure is invalid
pub fn write_incremental_with_page_replacement(
&mut self,
base_pdf_path: impl AsRef<std::path::Path>,
document: &mut Document,
) -> Result<()> {
use std::io::Cursor;
// Step 1: Read the entire base PDF into memory (avoids double file open)
let base_pdf_bytes = std::fs::read(base_pdf_path.as_ref())?;
let base_size = base_pdf_bytes.len() as u64;
// Step 2: Parse from memory to get page information
let mut pdf_reader = crate::parser::PdfReader::new(Cursor::new(&base_pdf_bytes))?;
let base_catalog = pdf_reader.catalog()?;
let (base_pages_id, base_pages_gen) = base_catalog
.get("Pages")
.and_then(|obj| {
if let crate::parser::objects::PdfObject::Reference(id, gen) = obj {
Some((*id, *gen))
} else {
None
}
})
.ok_or_else(|| {
crate::error::PdfError::InvalidStructure(
"Base PDF catalog missing /Pages reference".to_string(),
)
})?;
let base_pages_obj = pdf_reader.get_object(base_pages_id, base_pages_gen)?;
let base_pages_kids = if let crate::parser::objects::PdfObject::Dictionary(dict) =
base_pages_obj
{
dict.get("Kids")
.and_then(|obj| {
if let crate::parser::objects::PdfObject::Array(arr) = obj {
Some(
arr.0
.iter()
.filter_map(|item| {
if let crate::parser::objects::PdfObject::Reference(id, gen) =
item
{
Some(crate::objects::Object::Reference(
crate::objects::ObjectId::new(*id, *gen),
))
} else {
None
}
})
.collect::<Vec<_>>(),
)
} else {
None
}
})
.unwrap_or_default()
} else {
Vec::new()
};
let base_page_count = base_pages_kids.len();
// Step 3: Find startxref offset from the bytes
let start_search = if base_size > 100 { base_size - 100 } else { 0 } as usize;
let end_bytes = &base_pdf_bytes[start_search..];
let end_str = String::from_utf8_lossy(end_bytes);
let prev_xref = if let Some(startxref_pos) = end_str.find("startxref") {
let after_startxref = &end_str[startxref_pos + 9..];
let number_str: String = after_startxref
.chars()
.skip_while(|c| c.is_whitespace())
.take_while(|c| c.is_ascii_digit())
.collect();
number_str.parse::<u64>().map_err(|_| {
crate::error::PdfError::InvalidStructure(
"Could not parse startxref offset".to_string(),
)
})?
} else {
return Err(crate::error::PdfError::InvalidStructure(
"startxref not found in base PDF".to_string(),
));
};
// Step 4: Copy base PDF bytes to output
self.writer.write_all(&base_pdf_bytes)?;
self.prev_xref_offset = Some(prev_xref);
self.base_pdf_size = Some(base_size);
self.current_position = base_size;
// Step 3: Write replacement pages
if !document.used_characters.is_empty() {
self.document_used_chars = Some(document.used_characters.clone());
}
self.catalog_id = Some(self.allocate_object_id());
self.pages_id = Some(self.allocate_object_id());
self.info_id = Some(self.allocate_object_id());
let font_refs = self.write_fonts(document)?;
self.write_pages(document, &font_refs)?;
self.write_form_fields(document)?;
// Step 4: Create Pages tree with REPLACEMENTS
let catalog_id = self.get_catalog_id()?;
let new_pages_id = self.get_pages_id()?;
let mut catalog = crate::objects::Dictionary::new();
catalog.set("Type", crate::objects::Object::Name("Catalog".to_string()));
catalog.set("Pages", crate::objects::Object::Reference(new_pages_id));
self.write_object(catalog_id, crate::objects::Object::Dictionary(catalog))?;
// Build new Kids array: replace first N pages, keep rest from base
let mut all_pages_kids = Vec::new();
let replacement_count = document.pages.len();
// Add replacement pages (these override base pages at same indices)
for page_id in &self.page_ids {
all_pages_kids.push(crate::objects::Object::Reference(*page_id));
}
// Add remaining base pages that weren't replaced
if replacement_count < base_page_count {
for i in replacement_count..base_page_count {
if let Some(page_ref) = base_pages_kids.get(i) {
all_pages_kids.push(page_ref.clone());
}
}
}
let mut pages_dict = crate::objects::Dictionary::new();
pages_dict.set("Type", crate::objects::Object::Name("Pages".to_string()));
pages_dict.set(
"Kids",
crate::objects::Object::Array(all_pages_kids.clone()),
);
pages_dict.set(
"Count",
crate::objects::Object::Integer(all_pages_kids.len() as i64),
);
self.write_object(new_pages_id, crate::objects::Object::Dictionary(pages_dict))?;
self.write_info(document)?;
let xref_position = self.current_position;
self.write_xref()?;
self.write_trailer(xref_position)?;
self.writer.flush()?;
Ok(())
}
/// Overlays content onto existing PDF pages using incremental updates (PLANNED).
///
/// **STATUS**: Not yet implemented. This API is planned for a future release.
///
/// # What This Will Do
/// When implemented, this function will allow you to:
/// - Load an existing PDF
/// - Modify specific elements (fill form fields, add annotations, watermarks)
/// - Save incrementally without recreating entire pages
///
/// # Difference from Page Replacement
/// - **Page Replacement** (`write_incremental_with_page_replacement`): Replaces entire pages with manually recreated content
/// - **Overlay** (this function): Modifies existing pages by adding/changing specific elements
///
/// # Planned Usage (Future)
/// ```rust,ignore
/// // This code will work in a future release
/// let mut pdf_writer = PdfWriter::with_config(writer, WriterConfig::incremental());
///
/// let overlays = vec![
/// PageOverlay::new(0)
/// .add_text(110.0, 700.0, "John Smith")
/// .add_annotation(Annotation::text(200.0, 500.0, "Review this")),
/// ];
///
/// pdf_writer.write_incremental_with_overlay("form.pdf", overlays)?;
/// ```
///
/// # Implementation Requirements
/// This function requires:
/// 1. `Document::load()` - Load existing PDF into Document structure
/// 2. `Page::from_parsed()` - Convert parsed pages to writable format
/// 3. Content stream overlay system - Append to existing content streams
/// 4. Resource merging - Combine new resources with existing ones
///
/// Estimated implementation effort: 6-7 days
///
/// # Current Workaround
/// Until this is implemented, use `write_incremental_with_page_replacement()` with manual
/// page recreation. See that function's documentation for examples.
///
/// # Parameters
/// - `base_pdf_path`: Path to the existing PDF to modify (future)
/// - `overlays`: Content to overlay on existing pages (future)
///
/// # Returns
/// Currently always returns `PdfError::NotImplemented`
pub fn write_incremental_with_overlay<P: AsRef<std::path::Path>>(
&mut self,
base_pdf_path: P,
mut overlay_fn: impl FnMut(&mut crate::Page) -> Result<()>,
) -> Result<()> {
use std::io::Cursor;
// Step 1: Read the entire base PDF into memory
let base_pdf_bytes = std::fs::read(base_pdf_path.as_ref())?;
let base_size = base_pdf_bytes.len() as u64;
// Step 2: Parse from memory to get page information
let pdf_reader = crate::parser::PdfReader::new(Cursor::new(&base_pdf_bytes))?;
let parsed_doc = crate::parser::PdfDocument::new(pdf_reader);
// Get all pages from base PDF
let page_count = parsed_doc.page_count()?;
// Step 3: Find startxref offset from the bytes
let start_search = if base_size > 100 { base_size - 100 } else { 0 } as usize;
let end_bytes = &base_pdf_bytes[start_search..];
let end_str = String::from_utf8_lossy(end_bytes);
let prev_xref = if let Some(startxref_pos) = end_str.find("startxref") {
let after_startxref = &end_str[startxref_pos + 9..];
let number_str: String = after_startxref
.chars()
.skip_while(|c| c.is_whitespace())
.take_while(|c| c.is_ascii_digit())
.collect();
number_str.parse::<u64>().map_err(|_| {
crate::error::PdfError::InvalidStructure(
"Could not parse startxref offset".to_string(),
)
})?
} else {
return Err(crate::error::PdfError::InvalidStructure(
"startxref not found in base PDF".to_string(),
));
};
// Step 5: Copy base PDF bytes to output
self.writer.write_all(&base_pdf_bytes)?;
self.prev_xref_offset = Some(prev_xref);
self.base_pdf_size = Some(base_size);
self.current_position = base_size;
// Step 6: Build temporary document with overlaid pages
let mut temp_doc = crate::Document::new();
for page_idx in 0..page_count {
// Convert parsed page to writable with content preservation
let parsed_page = parsed_doc.get_page(page_idx)?;
let mut writable_page =
crate::Page::from_parsed_with_content(&parsed_page, &parsed_doc)?;
// Apply overlay function
overlay_fn(&mut writable_page)?;
// Add to temporary document
temp_doc.add_page(writable_page);
}
// Step 7: Write document with standard writer methods
// This ensures consistent object numbering
if !temp_doc.used_characters.is_empty() {
self.document_used_chars = Some(temp_doc.used_characters.clone());
}
self.catalog_id = Some(self.allocate_object_id());
self.pages_id = Some(self.allocate_object_id());
self.info_id = Some(self.allocate_object_id());
let font_refs = self.write_fonts(&temp_doc)?;
self.write_pages(&temp_doc, &font_refs)?;
self.write_form_fields(&mut temp_doc)?;
// Step 8: Create new catalog and pages tree
let catalog_id = self.get_catalog_id()?;
let new_pages_id = self.get_pages_id()?;
let mut catalog = crate::objects::Dictionary::new();
catalog.set("Type", crate::objects::Object::Name("Catalog".to_string()));
catalog.set("Pages", crate::objects::Object::Reference(new_pages_id));
self.write_object(catalog_id, crate::objects::Object::Dictionary(catalog))?;
// Build new Kids array with ALL overlaid pages
let mut all_pages_kids = Vec::new();
for page_id in &self.page_ids {
all_pages_kids.push(crate::objects::Object::Reference(*page_id));
}
let mut pages_dict = crate::objects::Dictionary::new();
pages_dict.set("Type", crate::objects::Object::Name("Pages".to_string()));
pages_dict.set(
"Kids",
crate::objects::Object::Array(all_pages_kids.clone()),
);
pages_dict.set(
"Count",
crate::objects::Object::Integer(all_pages_kids.len() as i64),
);
self.write_object(new_pages_id, crate::objects::Object::Dictionary(pages_dict))?;
self.write_info(&temp_doc)?;
let xref_position = self.current_position;
self.write_xref()?;
self.write_trailer(xref_position)?;
self.writer.flush()?;
Ok(())
}
fn write_header(&mut self) -> Result<()> {
let header = format!("%PDF-{}\n", self.config.pdf_version);
self.write_bytes(header.as_bytes())?;
// Binary comment to ensure file is treated as binary
self.write_bytes(&[b'%', 0xE2, 0xE3, 0xCF, 0xD3, b'\n'])?;
Ok(())
}
/// Convert pdf_objects types to writer objects types
/// This is a temporary bridge until type unification is complete
fn convert_pdf_objects_dict_to_writer(
&self,
pdf_dict: &crate::pdf_objects::Dictionary,
) -> crate::objects::Dictionary {
let mut writer_dict = crate::objects::Dictionary::new();
for (key, value) in pdf_dict.iter() {
let writer_obj = self.convert_pdf_object_to_writer(value);
writer_dict.set(key.as_str(), writer_obj);
}
writer_dict
}
fn convert_pdf_object_to_writer(
&self,
obj: &crate::pdf_objects::Object,
) -> crate::objects::Object {
use crate::objects::Object as WriterObj;
use crate::pdf_objects::Object as PdfObj;
match obj {
PdfObj::Null => WriterObj::Null,
PdfObj::Boolean(b) => WriterObj::Boolean(*b),
PdfObj::Integer(i) => WriterObj::Integer(*i),
PdfObj::Real(f) => WriterObj::Real(*f),
PdfObj::String(s) => {
WriterObj::String(String::from_utf8_lossy(s.as_bytes()).to_string())
}
PdfObj::Name(n) => WriterObj::Name(n.as_str().to_string()),
PdfObj::Array(arr) => {
let items: Vec<WriterObj> = arr
.iter()
.map(|item| self.convert_pdf_object_to_writer(item))
.collect();
WriterObj::Array(items)
}
PdfObj::Dictionary(dict) => {
WriterObj::Dictionary(self.convert_pdf_objects_dict_to_writer(dict))
}
PdfObj::Stream(stream) => {
let dict = self.convert_pdf_objects_dict_to_writer(&stream.dict);
WriterObj::Stream(dict, stream.data.clone())
}
PdfObj::Reference(id) => {
WriterObj::Reference(crate::objects::ObjectId::new(id.number(), id.generation()))
}
}
}
fn write_catalog(&mut self, document: &mut Document) -> Result<()> {
let catalog_id = self.get_catalog_id()?;
let pages_id = self.get_pages_id()?;
let mut catalog = Dictionary::new();
catalog.set("Type", Object::Name("Catalog".to_string()));
catalog.set("Pages", Object::Reference(pages_id));
// Process FormManager if present to update AcroForm
// We'll write the actual fields after pages are written
if let Some(_form_manager) = &document.form_manager {
// Ensure AcroForm exists
if document.acro_form.is_none() {
document.acro_form = Some(crate::forms::AcroForm::new());
}
}
// Add AcroForm if present
if let Some(acro_form) = &document.acro_form {
// Reserve object ID for AcroForm
let acro_form_id = self.allocate_object_id();
// Write AcroForm object
self.write_object(acro_form_id, Object::Dictionary(acro_form.to_dict()))?;
// Reference it in catalog
catalog.set("AcroForm", Object::Reference(acro_form_id));
}
// Add Outlines if present
if let Some(outline_tree) = &document.outline {
if !outline_tree.items.is_empty() {
let outline_root_id = self.write_outline_tree(outline_tree)?;
catalog.set("Outlines", Object::Reference(outline_root_id));
}
}
// Add StructTreeRoot if present (Tagged PDF - ISO 32000-1 §14.8)
if let Some(struct_tree) = &document.struct_tree {
if !struct_tree.is_empty() {
let struct_tree_root_id = self.write_struct_tree(struct_tree)?;
catalog.set("StructTreeRoot", Object::Reference(struct_tree_root_id));
// Mark as Tagged PDF
catalog.set("MarkInfo", {
let mut mark_info = Dictionary::new();
mark_info.set("Marked", Object::Boolean(true));
Object::Dictionary(mark_info)
});
}
}
// Add XMP Metadata stream (ISO 32000-1 §14.3.2)
// Generate XMP from document metadata and embed as stream
let xmp_metadata = document.create_xmp_metadata();
let xmp_packet = xmp_metadata.to_xmp_packet();
let metadata_id = self.allocate_object_id();
// Create metadata stream dictionary
let mut metadata_dict = Dictionary::new();
metadata_dict.set("Type", Object::Name("Metadata".to_string()));
metadata_dict.set("Subtype", Object::Name("XML".to_string()));
metadata_dict.set("Length", Object::Integer(xmp_packet.len() as i64));
// Write XMP metadata stream
self.write_object(
metadata_id,
Object::Stream(metadata_dict, xmp_packet.into_bytes()),
)?;
// Reference it in catalog
catalog.set("Metadata", Object::Reference(metadata_id));
self.write_object(catalog_id, Object::Dictionary(catalog))?;
Ok(())
}
fn write_page_content(&mut self, content_id: ObjectId, page: &crate::page::Page) -> Result<()> {
let mut page_copy = page.clone();
let content = page_copy.generate_content()?;
// Create stream with compression if enabled
#[cfg(feature = "compression")]
{
use crate::objects::Stream;
let mut stream = Stream::new(content);
// Only compress if config allows it
if self.config.compress_streams {
stream.compress_flate()?;
}
self.write_object(
content_id,
Object::Stream(stream.dictionary().clone(), stream.data().to_vec()),
)?;
}
#[cfg(not(feature = "compression"))]
{
let mut stream_dict = Dictionary::new();
stream_dict.set("Length", Object::Integer(content.len() as i64));
self.write_object(content_id, Object::Stream(stream_dict, content))?;
}
Ok(())
}
fn write_outline_tree(
&mut self,
outline_tree: &crate::structure::OutlineTree,
) -> Result<ObjectId> {
// Create root outline dictionary
let outline_root_id = self.allocate_object_id();
let mut outline_root = Dictionary::new();
outline_root.set("Type", Object::Name("Outlines".to_string()));
if !outline_tree.items.is_empty() {
// Reserve IDs for all outline items
let mut item_ids = Vec::new();
// Count all items and assign IDs
fn count_items(items: &[crate::structure::OutlineItem]) -> usize {
let mut count = items.len();
for item in items {
count += count_items(&item.children);
}
count
}
let total_items = count_items(&outline_tree.items);
// Reserve IDs for all items
for _ in 0..total_items {
item_ids.push(self.allocate_object_id());
}
let mut id_index = 0;
// Write root items
let first_id = item_ids[0];
let last_id = item_ids[outline_tree.items.len() - 1];
outline_root.set("First", Object::Reference(first_id));
outline_root.set("Last", Object::Reference(last_id));
// Visible count
let visible_count = outline_tree.visible_count();
outline_root.set("Count", Object::Integer(visible_count));
// Write all items recursively
let mut written_items = Vec::new();
for (i, item) in outline_tree.items.iter().enumerate() {
let item_id = item_ids[id_index];
id_index += 1;
let prev_id = if i > 0 { Some(item_ids[i - 1]) } else { None };
let next_id = if i < outline_tree.items.len() - 1 {
Some(item_ids[i + 1])
} else {
None
};
// Write this item and its children
let children_ids = self.write_outline_item(
item,
item_id,
outline_root_id,
prev_id,
next_id,
&mut item_ids,
&mut id_index,
)?;
written_items.extend(children_ids);
}
}
self.write_object(outline_root_id, Object::Dictionary(outline_root))?;
Ok(outline_root_id)
}
#[allow(clippy::too_many_arguments)]
fn write_outline_item(
&mut self,
item: &crate::structure::OutlineItem,
item_id: ObjectId,
parent_id: ObjectId,
prev_id: Option<ObjectId>,
next_id: Option<ObjectId>,
all_ids: &mut Vec<ObjectId>,
id_index: &mut usize,
) -> Result<Vec<ObjectId>> {
let mut written_ids = vec![item_id];
// Handle children if any
let (first_child_id, last_child_id) = if !item.children.is_empty() {
let first_idx = *id_index;
let first_id = all_ids[first_idx];
let last_idx = first_idx + item.children.len() - 1;
let last_id = all_ids[last_idx];
// Write children
for (i, child) in item.children.iter().enumerate() {
let child_id = all_ids[*id_index];
*id_index += 1;
let child_prev = if i > 0 {
Some(all_ids[first_idx + i - 1])
} else {
None
};
let child_next = if i < item.children.len() - 1 {
Some(all_ids[first_idx + i + 1])
} else {
None
};
let child_ids = self.write_outline_item(
child, child_id, item_id, // This item is the parent
child_prev, child_next, all_ids, id_index,
)?;
written_ids.extend(child_ids);
}
(Some(first_id), Some(last_id))
} else {
(None, None)
};
// Create item dictionary
let item_dict = crate::structure::outline_item_to_dict(
item,
parent_id,
first_child_id,
last_child_id,
prev_id,
next_id,
);
self.write_object(item_id, Object::Dictionary(item_dict))?;
Ok(written_ids)
}
/// Writes the structure tree for Tagged PDF (ISO 32000-1 §14.8)
fn write_struct_tree(
&mut self,
struct_tree: &crate::structure::StructTree,
) -> Result<ObjectId> {
// Allocate IDs for StructTreeRoot and all elements
let struct_tree_root_id = self.allocate_object_id();
let mut element_ids = Vec::new();
for _ in 0..struct_tree.len() {
element_ids.push(self.allocate_object_id());
}
// Build parent map: element_index -> parent_id
let mut parent_map: std::collections::HashMap<usize, ObjectId> =
std::collections::HashMap::new();
// Root element's parent is StructTreeRoot
if let Some(root_index) = struct_tree.root_index() {
parent_map.insert(root_index, struct_tree_root_id);
// Recursively map all children to their parents
fn map_children_parents(
tree: &crate::structure::StructTree,
parent_index: usize,
parent_id: ObjectId,
element_ids: &[ObjectId],
parent_map: &mut std::collections::HashMap<usize, ObjectId>,
) {
if let Some(parent_elem) = tree.get(parent_index) {
for &child_index in &parent_elem.children {
parent_map.insert(child_index, parent_id);
map_children_parents(
tree,
child_index,
element_ids[child_index],
element_ids,
parent_map,
);
}
}
}
map_children_parents(
struct_tree,
root_index,
element_ids[root_index],
&element_ids,
&mut parent_map,
);
}
// Write all structure elements with parent references
for (index, element) in struct_tree.iter().enumerate() {
let element_id = element_ids[index];
let mut element_dict = Dictionary::new();
element_dict.set("Type", Object::Name("StructElem".to_string()));
element_dict.set("S", Object::Name(element.structure_type.as_pdf_name()));
// Parent reference (ISO 32000-1 §14.7.2 - required)
if let Some(&parent_id) = parent_map.get(&index) {
element_dict.set("P", Object::Reference(parent_id));
}
// Element ID (optional)
if let Some(ref id) = element.id {
element_dict.set("ID", Object::String(id.clone()));
}
// Attributes
if let Some(ref lang) = element.attributes.lang {
element_dict.set("Lang", Object::String(lang.clone()));
}
if let Some(ref alt) = element.attributes.alt {
element_dict.set("Alt", Object::String(alt.clone()));
}
if let Some(ref actual_text) = element.attributes.actual_text {
element_dict.set("ActualText", Object::String(actual_text.clone()));
}
if let Some(ref title) = element.attributes.title {
element_dict.set("T", Object::String(title.clone()));
}
if let Some(bbox) = element.attributes.bbox {
element_dict.set(
"BBox",
Object::Array(vec![
Object::Real(bbox[0]),
Object::Real(bbox[1]),
Object::Real(bbox[2]),
Object::Real(bbox[3]),
]),
);
}
// Kids (children elements + marked content references)
let mut kids = Vec::new();
// Add child element references
for &child_index in &element.children {
kids.push(Object::Reference(element_ids[child_index]));
}
// Add marked content references (MCIDs)
for mcid_ref in &element.mcids {
let mut mcr = Dictionary::new();
mcr.set("Type", Object::Name("MCR".to_string()));
mcr.set("Pg", Object::Integer(mcid_ref.page_index as i64));
mcr.set("MCID", Object::Integer(mcid_ref.mcid as i64));
kids.push(Object::Dictionary(mcr));
}
if !kids.is_empty() {
element_dict.set("K", Object::Array(kids));
}
self.write_object(element_id, Object::Dictionary(element_dict))?;
}
// Create StructTreeRoot dictionary
let mut struct_tree_root = Dictionary::new();
struct_tree_root.set("Type", Object::Name("StructTreeRoot".to_string()));
// Add root element(s) as K entry
if let Some(root_index) = struct_tree.root_index() {
struct_tree_root.set("K", Object::Reference(element_ids[root_index]));
}
// Add RoleMap if not empty
if !struct_tree.role_map.mappings().is_empty() {
let mut role_map = Dictionary::new();
for (custom_type, standard_type) in struct_tree.role_map.mappings() {
role_map.set(
custom_type.as_str(),
Object::Name(standard_type.as_pdf_name().to_string()),
);
}
struct_tree_root.set("RoleMap", Object::Dictionary(role_map));
}
self.write_object(struct_tree_root_id, Object::Dictionary(struct_tree_root))?;
Ok(struct_tree_root_id)
}
fn write_form_fields(&mut self, document: &mut Document) -> Result<()> {
// Add collected form field IDs to AcroForm
if !self.form_field_ids.is_empty() {
if let Some(acro_form) = &mut document.acro_form {
// Clear any existing fields and add the ones we found
acro_form.fields.clear();
for field_id in &self.form_field_ids {
acro_form.add_field(*field_id);
}
// Ensure AcroForm has the right properties
acro_form.need_appearances = true;
if acro_form.da.is_none() {
acro_form.da = Some("/Helv 12 Tf 0 g".to_string());
}
}
}
Ok(())
}
fn write_info(&mut self, document: &Document) -> Result<()> {
let info_id = self.get_info_id()?;
let mut info_dict = Dictionary::new();
if let Some(ref title) = document.metadata.title {
info_dict.set("Title", Object::String(title.clone()));
}
if let Some(ref author) = document.metadata.author {
info_dict.set("Author", Object::String(author.clone()));
}
if let Some(ref subject) = document.metadata.subject {
info_dict.set("Subject", Object::String(subject.clone()));
}
if let Some(ref keywords) = document.metadata.keywords {
info_dict.set("Keywords", Object::String(keywords.clone()));
}
if let Some(ref creator) = document.metadata.creator {
info_dict.set("Creator", Object::String(creator.clone()));
}
if let Some(ref producer) = document.metadata.producer {
info_dict.set("Producer", Object::String(producer.clone()));
}
// Add creation date
if let Some(creation_date) = document.metadata.creation_date {
let date_string = format_pdf_date(creation_date);
info_dict.set("CreationDate", Object::String(date_string));
}
// Add modification date
if let Some(mod_date) = document.metadata.modification_date {
let date_string = format_pdf_date(mod_date);
info_dict.set("ModDate", Object::String(date_string));
}
// Add PDF signature (anti-spoofing and licensing)
// This is written AFTER user-configurable metadata so it cannot be overridden
let edition = super::Edition::OpenSource;
let signature = super::PdfSignature::new(document, edition);
signature.write_to_info_dict(&mut info_dict);
self.write_object(info_id, Object::Dictionary(info_dict))?;
Ok(())
}
fn write_fonts(&mut self, document: &Document) -> Result<HashMap<String, ObjectId>> {
let mut font_refs = HashMap::new();
// Write custom fonts from the document
for font_name in document.custom_font_names() {
if let Some(font) = document.get_custom_font(&font_name) {
// For now, write all custom fonts as TrueType with Identity-H for Unicode support
// The font from document is Arc<fonts::Font>, not text::font_manager::CustomFont
let font_id = self.write_font_with_unicode_support(&font_name, &font)?;
font_refs.insert(font_name.clone(), font_id);
}
}
Ok(font_refs)
}
/// Write font with automatic Unicode support detection
fn write_font_with_unicode_support(
&mut self,
font_name: &str,
font: &crate::fonts::Font,
) -> Result<ObjectId> {
// Check if any text in the document needs Unicode
// For simplicity, always use Type0 for full Unicode support
self.write_type0_font_from_font(font_name, font)
}
/// Write a Type0 font with CID support from fonts::Font
fn write_type0_font_from_font(
&mut self,
font_name: &str,
font: &crate::fonts::Font,
) -> Result<ObjectId> {
// Get used characters from document for subsetting
let used_chars = self.document_used_chars.clone().unwrap_or_else(|| {
// If no tracking, include common characters as fallback
let mut chars = std::collections::HashSet::new();
for ch in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 .,!?".chars()
{
chars.insert(ch);
}
chars
});
// Allocate IDs for all font objects
let font_id = self.allocate_object_id();
let descendant_font_id = self.allocate_object_id();
let descriptor_id = self.allocate_object_id();
let font_file_id = self.allocate_object_id();
let to_unicode_id = self.allocate_object_id();
// Write font file (embedded TTF data with subsetting for large fonts)
// Keep track of the glyph mapping if we subset the font
// IMPORTANT: We need the ORIGINAL font for width calculations, not the subset
let (font_data_to_embed, subset_glyph_mapping, original_font_for_widths, embed_as_raw_cff) =
if font.data.len() > 100_000 && !used_chars.is_empty() {
match crate::text::fonts::truetype_subsetter::subset_font(
font.data.clone(),
&used_chars,
) {
Ok(subset_result) => (
subset_result.font_data,
Some(subset_result.glyph_mapping),
font.clone(),
subset_result.is_raw_cff,
),
Err(_) => {
if font.data.len() < 25_000_000 {
(font.data.clone(), None, font.clone(), false)
} else {
(Vec::new(), None, font.clone(), false)
}
}
}
} else {
(font.data.clone(), None, font.clone(), false)
};
if !font_data_to_embed.is_empty() {
let mut font_file_dict = Dictionary::new();
if embed_as_raw_cff {
// CID-keyed CFF: embed raw CFF bytes with /CIDFontType0C
// This is the industry standard for CID fonts in PDF.
font_file_dict.set("Subtype", Object::Name("CIDFontType0C".to_string()));
} else {
match font.format {
crate::fonts::FontFormat::OpenType => {
font_file_dict.set("Subtype", Object::Name("OpenType".to_string()));
font_file_dict
.set("Length1", Object::Integer(font_data_to_embed.len() as i64));
}
crate::fonts::FontFormat::TrueType => {
font_file_dict
.set("Length1", Object::Integer(font_data_to_embed.len() as i64));
}
}
}
let font_stream_obj = Object::Stream(font_file_dict, font_data_to_embed);
self.write_object(font_file_id, font_stream_obj)?;
} else {
// No font data to embed
let font_file_dict = Dictionary::new();
let font_stream_obj = Object::Stream(font_file_dict, Vec::new());
self.write_object(font_file_id, font_stream_obj)?;
}
// Write font descriptor
let mut descriptor = Dictionary::new();
descriptor.set("Type", Object::Name("FontDescriptor".to_string()));
descriptor.set("FontName", Object::Name(font_name.to_string()));
descriptor.set("Flags", Object::Integer(4)); // Symbolic font
descriptor.set(
"FontBBox",
Object::Array(vec![
Object::Integer(font.descriptor.font_bbox[0] as i64),
Object::Integer(font.descriptor.font_bbox[1] as i64),
Object::Integer(font.descriptor.font_bbox[2] as i64),
Object::Integer(font.descriptor.font_bbox[3] as i64),
]),
);
descriptor.set(
"ItalicAngle",
Object::Real(font.descriptor.italic_angle as f64),
);
descriptor.set("Ascent", Object::Real(font.descriptor.ascent as f64));
descriptor.set("Descent", Object::Real(font.descriptor.descent as f64));
descriptor.set("CapHeight", Object::Real(font.descriptor.cap_height as f64));
descriptor.set("StemV", Object::Real(font.descriptor.stem_v as f64));
// Use appropriate FontFile type based on font format
let font_file_key = match font.format {
crate::fonts::FontFormat::OpenType => "FontFile3", // CFF/OpenType fonts
crate::fonts::FontFormat::TrueType => "FontFile2", // TrueType fonts
};
descriptor.set(font_file_key, Object::Reference(font_file_id));
self.write_object(descriptor_id, Object::Dictionary(descriptor))?;
// Write CIDFont (descendant font)
let mut cid_font = Dictionary::new();
cid_font.set("Type", Object::Name("Font".to_string()));
// Use ISO 32000-1 §9.7.4 correct CIDFont subtype based on font format
let is_cff = matches!(font.format, crate::fonts::FontFormat::OpenType);
let cid_font_subtype = if CjkFontType::should_use_cidfonttype2(is_cff) {
"CIDFontType2" // TrueType fonts
} else {
"CIDFontType0" // CFF/OpenType fonts
};
cid_font.set("Subtype", Object::Name(cid_font_subtype.to_string()));
cid_font.set("BaseFont", Object::Name(font_name.to_string()));
// CIDSystemInfo - Use appropriate values for CJK fonts
let mut cid_system_info = Dictionary::new();
let (registry, ordering, supplement) =
if let Some(cjk_type) = CjkFontType::detect_from_name(font_name) {
cjk_type.cid_system_info()
} else {
("Adobe", "Identity", 0)
};
cid_system_info.set("Registry", Object::String(registry.to_string()));
cid_system_info.set("Ordering", Object::String(ordering.to_string()));
cid_system_info.set("Supplement", Object::Integer(supplement as i64));
cid_font.set("CIDSystemInfo", Object::Dictionary(cid_system_info));
cid_font.set("FontDescriptor", Object::Reference(descriptor_id));
// Calculate a better default width based on font metrics
let default_width = self.calculate_default_width(font);
cid_font.set("DW", Object::Integer(default_width));
// Generate proper width array from font metrics
// IMPORTANT: Use the ORIGINAL font for width calculations, not the subset
// But pass the subset mapping to know which characters we're using
let w_array = self.generate_width_array(
&original_font_for_widths,
default_width,
subset_glyph_mapping.as_ref(),
);
cid_font.set("W", Object::Array(w_array));
// CIDToGIDMap - Only required for CIDFontType2 (TrueType)
// For CIDFontType0 (CFF/OpenType), CIDToGIDMap should NOT be present per ISO 32000-1:2008 §9.7.4.2
// CFF fonts use CIDs directly as glyph identifiers, so no mapping is needed
if cid_font_subtype == "CIDFontType2" {
// TrueType fonts need CIDToGIDMap to map CIDs (Unicode code points) to Glyph IDs
let cid_to_gid_map =
self.generate_cid_to_gid_map(font, subset_glyph_mapping.as_ref())?;
if !cid_to_gid_map.is_empty() {
// Write the CIDToGIDMap as a stream
let cid_to_gid_map_id = self.allocate_object_id();
let mut map_dict = Dictionary::new();
map_dict.set("Length", Object::Integer(cid_to_gid_map.len() as i64));
let map_stream = Object::Stream(map_dict, cid_to_gid_map);
self.write_object(cid_to_gid_map_id, map_stream)?;
cid_font.set("CIDToGIDMap", Object::Reference(cid_to_gid_map_id));
} else {
cid_font.set("CIDToGIDMap", Object::Name("Identity".to_string()));
}
}
// Note: For CIDFontType0 (CFF), we intentionally omit CIDToGIDMap
self.write_object(descendant_font_id, Object::Dictionary(cid_font))?;
// Write ToUnicode CMap
let cmap_data = self.generate_tounicode_cmap_from_font(font);
let cmap_dict = Dictionary::new();
let cmap_stream = Object::Stream(cmap_dict, cmap_data);
self.write_object(to_unicode_id, cmap_stream)?;
// Write Type0 font (main font)
let mut type0_font = Dictionary::new();
type0_font.set("Type", Object::Name("Font".to_string()));
type0_font.set("Subtype", Object::Name("Type0".to_string()));
type0_font.set("BaseFont", Object::Name(font_name.to_string()));
type0_font.set("Encoding", Object::Name("Identity-H".to_string()));
type0_font.set(
"DescendantFonts",
Object::Array(vec![Object::Reference(descendant_font_id)]),
);
type0_font.set("ToUnicode", Object::Reference(to_unicode_id));
self.write_object(font_id, Object::Dictionary(type0_font))?;
Ok(font_id)
}
/// Calculate default width based on common characters
fn calculate_default_width(&self, font: &crate::fonts::Font) -> i64 {
use crate::text::fonts::truetype::TrueTypeFont;
// Try to calculate from actual font metrics
if let Ok(tt_font) = TrueTypeFont::parse(font.data.clone()) {
if let Ok(cmap_tables) = tt_font.parse_cmap() {
if let Some(cmap) = CmapSubtable::select_best_or_first(&cmap_tables) {
if let Ok(widths) = tt_font.get_glyph_widths(&cmap.mappings) {
// NOTE: get_glyph_widths already returns widths in PDF units (1000 per em)
// Calculate average width of common Latin characters
let common_chars =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ";
let mut total_width = 0;
let mut count = 0;
for ch in common_chars.chars() {
let unicode = ch as u32;
if let Some(&pdf_width) = widths.get(&unicode) {
total_width += pdf_width as i64;
count += 1;
}
}
if count > 0 {
return total_width / count;
}
}
}
}
}
// Fallback default if we can't calculate
500
}
/// Generate width array for CID font
fn generate_width_array(
&self,
font: &crate::fonts::Font,
_default_width: i64,
subset_mapping: Option<&HashMap<u32, u16>>,
) -> Vec<Object> {
use crate::text::fonts::truetype::TrueTypeFont;
let mut w_array = Vec::new();
// Try to get actual glyph widths from the font
if let Ok(tt_font) = TrueTypeFont::parse(font.data.clone()) {
// IMPORTANT: Always use ORIGINAL mappings for width calculation
// The subset_mapping has NEW GlyphIDs which don't correspond to the right glyphs
// in the original font's width table
let char_to_glyph = {
// Parse cmap to get original mappings
if let Ok(cmap_tables) = tt_font.parse_cmap() {
if let Some(cmap) = CmapSubtable::select_best_or_first(&cmap_tables) {
// If we have subset_mapping, filter to only include used characters
if let Some(subset_map) = subset_mapping {
let mut filtered = HashMap::new();
for unicode in subset_map.keys() {
// Get the ORIGINAL GlyphID for this Unicode
if let Some(&orig_glyph) = cmap.mappings.get(unicode) {
filtered.insert(*unicode, orig_glyph);
}
}
filtered
} else {
cmap.mappings.clone()
}
} else {
HashMap::new()
}
} else {
HashMap::new()
}
};
if !char_to_glyph.is_empty() {
// Get actual widths from the font
if let Ok(widths) = tt_font.get_glyph_widths(&char_to_glyph) {
// NOTE: get_glyph_widths already returns widths scaled to PDF units (1000 per em)
// So we DON'T need to scale them again here
// Group consecutive characters with same width for efficiency
let mut sorted_chars: Vec<_> = widths.iter().collect();
sorted_chars.sort_by_key(|(unicode, _)| *unicode);
let mut i = 0;
while i < sorted_chars.len() {
let start_unicode = *sorted_chars[i].0;
// Width is already in PDF units from get_glyph_widths
let pdf_width = *sorted_chars[i].1 as i64;
// Find consecutive characters with same width
let mut end_unicode = start_unicode;
let mut j = i + 1;
while j < sorted_chars.len() && *sorted_chars[j].0 == end_unicode + 1 {
let next_pdf_width = *sorted_chars[j].1 as i64;
if next_pdf_width == pdf_width {
end_unicode = *sorted_chars[j].0;
j += 1;
} else {
break;
}
}
// Add to W array
if start_unicode == end_unicode {
// Single character
w_array.push(Object::Integer(start_unicode as i64));
w_array.push(Object::Array(vec![Object::Integer(pdf_width)]));
} else {
// Range of characters
w_array.push(Object::Integer(start_unicode as i64));
w_array.push(Object::Integer(end_unicode as i64));
w_array.push(Object::Integer(pdf_width));
}
i = j;
}
return w_array;
}
}
}
// Fallback to reasonable default widths if we can't parse the font
let ranges = vec![
// Space character should be narrower
(0x20, 0x20, 250), // Space
(0x21, 0x2F, 333), // Punctuation
(0x30, 0x39, 500), // Numbers (0-9)
(0x3A, 0x40, 333), // More punctuation
(0x41, 0x5A, 667), // Uppercase letters (A-Z)
(0x5B, 0x60, 333), // Brackets
(0x61, 0x7A, 500), // Lowercase letters (a-z)
(0x7B, 0x7E, 333), // More brackets
// Extended Latin
(0xA0, 0xA0, 250), // Non-breaking space
(0xA1, 0xBF, 333), // Latin-1 punctuation
(0xC0, 0xD6, 667), // Latin-1 uppercase
(0xD7, 0xD7, 564), // Multiplication sign
(0xD8, 0xDE, 667), // More Latin-1 uppercase
(0xDF, 0xF6, 500), // Latin-1 lowercase
(0xF7, 0xF7, 564), // Division sign
(0xF8, 0xFF, 500), // More Latin-1 lowercase
// Latin Extended-A
(0x100, 0x17F, 500), // Latin Extended-A
// Symbols and special characters
(0x2000, 0x200F, 250), // Various spaces
(0x2010, 0x2027, 333), // Hyphens and dashes
(0x2028, 0x202F, 250), // More spaces
(0x2030, 0x206F, 500), // General Punctuation
(0x2070, 0x209F, 400), // Superscripts
(0x20A0, 0x20CF, 600), // Currency symbols
(0x2100, 0x214F, 700), // Letterlike symbols
(0x2190, 0x21FF, 600), // Arrows
(0x2200, 0x22FF, 600), // Mathematical operators
(0x2300, 0x23FF, 600), // Miscellaneous technical
(0x2500, 0x257F, 500), // Box drawing
(0x2580, 0x259F, 500), // Block elements
(0x25A0, 0x25FF, 600), // Geometric shapes
(0x2600, 0x26FF, 600), // Miscellaneous symbols
(0x2700, 0x27BF, 600), // Dingbats
];
// Convert ranges to W array format
for (start, end, width) in ranges {
if start == end {
// Single character
w_array.push(Object::Integer(start));
w_array.push(Object::Array(vec![Object::Integer(width)]));
} else {
// Range of characters
w_array.push(Object::Integer(start));
w_array.push(Object::Integer(end));
w_array.push(Object::Integer(width));
}
}
w_array
}
/// Generate CIDToGIDMap for Type0 font
fn generate_cid_to_gid_map(
&mut self,
font: &crate::fonts::Font,
subset_mapping: Option<&HashMap<u32, u16>>,
) -> Result<Vec<u8>> {
use crate::text::fonts::truetype::TrueTypeFont;
// If we have a subset mapping, use it directly
// Otherwise, parse the font to get the original cmap table
let cmap_mappings = if let Some(subset_map) = subset_mapping {
// Use the subset mapping directly
subset_map.clone()
} else {
// Parse the font to get the original cmap table
let tt_font = TrueTypeFont::parse(font.data.clone())?;
let cmap_tables = tt_font.parse_cmap()?;
// Find the best cmap table (prefer Format 12 for CJK)
let cmap = CmapSubtable::select_best_or_first(&cmap_tables).ok_or_else(|| {
crate::error::PdfError::FontError("No Unicode cmap table found".to_string())
})?;
cmap.mappings.clone()
};
// Build the CIDToGIDMap
// Since we use Unicode code points as CIDs, we need to map Unicode → GlyphID
// The map is a binary array where index = CID (Unicode) * 2, value = GlyphID (big-endian)
// OPTIMIZATION: Only create map for characters actually used in the document
// Get used characters from document tracking
let used_chars = self.document_used_chars.clone().unwrap_or_default();
// Find the maximum Unicode value from used characters or full font
let max_unicode = if !used_chars.is_empty() {
// If we have used chars tracking, only map up to the highest used character
used_chars
.iter()
.map(|ch| *ch as u32)
.max()
.unwrap_or(0x00FF) // At least Basic Latin
.min(0xFFFF) as usize
} else {
// Fallback to original behavior if no tracking
cmap_mappings
.keys()
.max()
.copied()
.unwrap_or(0xFFFF)
.min(0xFFFF) as usize
};
// Create the map: 2 bytes per entry
let mut map = vec![0u8; (max_unicode + 1) * 2];
// Fill in the mappings
let mut sample_mappings = Vec::new();
for (&unicode, &glyph_id) in &cmap_mappings {
if unicode <= max_unicode as u32 {
let idx = (unicode as usize) * 2;
// Write glyph_id in big-endian format
map[idx] = (glyph_id >> 8) as u8;
map[idx + 1] = (glyph_id & 0xFF) as u8;
// Collect some sample mappings for debugging
if unicode == 0x0041 || unicode == 0x0061 || unicode == 0x00E1 || unicode == 0x00F1
{
sample_mappings.push((unicode, glyph_id));
}
}
}
Ok(map)
}
/// Generate ToUnicode CMap for Type0 font from fonts::Font
fn generate_tounicode_cmap_from_font(&self, font: &crate::fonts::Font) -> Vec<u8> {
use crate::text::fonts::truetype::TrueTypeFont;
let mut cmap = String::new();
// CMap header
cmap.push_str("/CIDInit /ProcSet findresource begin\n");
cmap.push_str("12 dict begin\n");
cmap.push_str("begincmap\n");
cmap.push_str("/CIDSystemInfo\n");
cmap.push_str("<< /Registry (Adobe)\n");
cmap.push_str(" /Ordering (UCS)\n");
cmap.push_str(" /Supplement 0\n");
cmap.push_str(">> def\n");
cmap.push_str("/CMapName /Adobe-Identity-UCS def\n");
cmap.push_str("/CMapType 2 def\n");
cmap.push_str("1 begincodespacerange\n");
cmap.push_str("<0000> <FFFF>\n");
cmap.push_str("endcodespacerange\n");
// Try to get actual mappings from the font
let mut mappings = Vec::new();
let mut has_font_mappings = false;
if let Ok(tt_font) = TrueTypeFont::parse(font.data.clone()) {
if let Ok(cmap_tables) = tt_font.parse_cmap() {
// Find the best cmap table (prefer Format 12 for CJK)
if let Some(cmap_table) = CmapSubtable::select_best_or_first(&cmap_tables) {
// For Identity-H encoding, we use Unicode code points as CIDs
// So the ToUnicode CMap should map CID (=Unicode) → Unicode
for (&unicode, &glyph_id) in &cmap_table.mappings {
if glyph_id > 0 && unicode <= 0xFFFF {
// Only non-.notdef glyphs
// Map CID (which is Unicode value) to Unicode
mappings.push((unicode, unicode));
}
}
has_font_mappings = true;
}
}
}
// If we couldn't get font mappings, use identity mapping for common ranges
if !has_font_mappings {
// Basic Latin and Latin-1 Supplement (0x0020-0x00FF)
for i in 0x0020..=0x00FF {
mappings.push((i, i));
}
// Latin Extended-A (0x0100-0x017F)
for i in 0x0100..=0x017F {
mappings.push((i, i));
}
// CJK Unicode ranges - CRITICAL for CJK font support
// Hiragana (Japanese)
for i in 0x3040..=0x309F {
mappings.push((i, i));
}
// Katakana (Japanese)
for i in 0x30A0..=0x30FF {
mappings.push((i, i));
}
// CJK Unified Ideographs (Chinese, Japanese, Korean)
for i in 0x4E00..=0x9FFF {
mappings.push((i, i));
}
// Hangul Syllables (Korean)
for i in 0xAC00..=0xD7AF {
mappings.push((i, i));
}
// Common symbols and punctuation
for i in 0x2000..=0x206F {
mappings.push((i, i));
}
// Mathematical symbols
for i in 0x2200..=0x22FF {
mappings.push((i, i));
}
// Arrows
for i in 0x2190..=0x21FF {
mappings.push((i, i));
}
// Box drawing
for i in 0x2500..=0x259F {
mappings.push((i, i));
}
// Geometric shapes
for i in 0x25A0..=0x25FF {
mappings.push((i, i));
}
// Miscellaneous symbols
for i in 0x2600..=0x26FF {
mappings.push((i, i));
}
}
// Sort mappings by CID for better organization
mappings.sort_by_key(|&(cid, _)| cid);
// Use more efficient bfrange where possible
let mut i = 0;
while i < mappings.len() {
// Check if we can use a range
let start_cid = mappings[i].0;
let start_unicode = mappings[i].1;
let mut end_idx = i;
// Find consecutive mappings
while end_idx + 1 < mappings.len()
&& mappings[end_idx + 1].0 == mappings[end_idx].0 + 1
&& mappings[end_idx + 1].1 == mappings[end_idx].1 + 1
&& end_idx - i < 99
// Max 100 per block
{
end_idx += 1;
}
if end_idx > i {
// Use bfrange for consecutive mappings
cmap.push_str("1 beginbfrange\n");
cmap.push_str(&format!(
"<{:04X}> <{:04X}> <{:04X}>\n",
start_cid, mappings[end_idx].0, start_unicode
));
cmap.push_str("endbfrange\n");
i = end_idx + 1;
} else {
// Use bfchar for individual mappings
let mut chars = Vec::new();
let chunk_end = (i + 100).min(mappings.len());
for item in &mappings[i..chunk_end] {
chars.push(*item);
}
if !chars.is_empty() {
cmap.push_str(&format!("{} beginbfchar\n", chars.len()));
for (cid, unicode) in chars {
cmap.push_str(&format!("<{:04X}> <{:04X}>\n", cid, unicode));
}
cmap.push_str("endbfchar\n");
}
i = chunk_end;
}
}
// CMap footer
cmap.push_str("endcmap\n");
cmap.push_str("CMapName currentdict /CMap defineresource pop\n");
cmap.push_str("end\n");
cmap.push_str("end\n");
cmap.into_bytes()
}
/// Write a regular TrueType font
#[allow(dead_code)]
fn write_truetype_font(
&mut self,
font_name: &str,
font: &crate::text::font_manager::CustomFont,
) -> Result<ObjectId> {
// Allocate IDs for font objects
let font_id = self.allocate_object_id();
let descriptor_id = self.allocate_object_id();
let font_file_id = self.allocate_object_id();
// Write font file (embedded TTF data)
if let Some(ref data) = font.font_data {
let mut font_file_dict = Dictionary::new();
font_file_dict.set("Length1", Object::Integer(data.len() as i64));
let font_stream_obj = Object::Stream(font_file_dict, data.clone());
self.write_object(font_file_id, font_stream_obj)?;
}
// Write font descriptor
let mut descriptor = Dictionary::new();
descriptor.set("Type", Object::Name("FontDescriptor".to_string()));
descriptor.set("FontName", Object::Name(font_name.to_string()));
descriptor.set("Flags", Object::Integer(32)); // Non-symbolic font
descriptor.set(
"FontBBox",
Object::Array(vec![
Object::Integer(-1000),
Object::Integer(-1000),
Object::Integer(2000),
Object::Integer(2000),
]),
);
descriptor.set("ItalicAngle", Object::Integer(0));
descriptor.set("Ascent", Object::Integer(font.descriptor.ascent as i64));
descriptor.set("Descent", Object::Integer(font.descriptor.descent as i64));
descriptor.set(
"CapHeight",
Object::Integer(font.descriptor.cap_height as i64),
);
descriptor.set("StemV", Object::Integer(font.descriptor.stem_v as i64));
descriptor.set("FontFile2", Object::Reference(font_file_id));
self.write_object(descriptor_id, Object::Dictionary(descriptor))?;
// Write font dictionary
let mut font_dict = Dictionary::new();
font_dict.set("Type", Object::Name("Font".to_string()));
font_dict.set("Subtype", Object::Name("TrueType".to_string()));
font_dict.set("BaseFont", Object::Name(font_name.to_string()));
font_dict.set("FirstChar", Object::Integer(0));
font_dict.set("LastChar", Object::Integer(255));
// Create widths array (simplified - all 600)
let widths: Vec<Object> = (0..256).map(|_| Object::Integer(600)).collect();
font_dict.set("Widths", Object::Array(widths));
font_dict.set("FontDescriptor", Object::Reference(descriptor_id));
// Use WinAnsiEncoding for regular TrueType
font_dict.set("Encoding", Object::Name("WinAnsiEncoding".to_string()));
self.write_object(font_id, Object::Dictionary(font_dict))?;
Ok(font_id)
}
fn write_pages(
&mut self,
document: &Document,
font_refs: &HashMap<String, ObjectId>,
) -> Result<()> {
let pages_id = self.get_pages_id()?;
let mut pages_dict = Dictionary::new();
pages_dict.set("Type", Object::Name("Pages".to_string()));
pages_dict.set("Count", Object::Integer(document.pages.len() as i64));
let mut kids = Vec::new();
// Allocate page object IDs sequentially
let mut page_ids = Vec::new();
let mut content_ids = Vec::new();
for _ in 0..document.pages.len() {
page_ids.push(self.allocate_object_id());
content_ids.push(self.allocate_object_id());
}
for page_id in &page_ids {
kids.push(Object::Reference(*page_id));
}
pages_dict.set("Kids", Object::Array(kids));
self.write_object(pages_id, Object::Dictionary(pages_dict))?;
// Store page IDs for form field references
self.page_ids = page_ids.clone();
// Write individual pages with font references
for (i, page) in document.pages.iter().enumerate() {
let page_id = page_ids[i];
let content_id = content_ids[i];
self.write_page_with_fonts(page_id, pages_id, content_id, page, document, font_refs)?;
self.write_page_content(content_id, page)?;
}
Ok(())
}
/// Compatibility alias for `write_pages` to maintain backwards compatibility
#[allow(dead_code)]
fn write_pages_with_fonts(
&mut self,
document: &Document,
font_refs: &HashMap<String, ObjectId>,
) -> Result<()> {
self.write_pages(document, font_refs)
}
fn write_page_with_fonts(
&mut self,
page_id: ObjectId,
parent_id: ObjectId,
content_id: ObjectId,
page: &crate::page::Page,
_document: &Document,
font_refs: &HashMap<String, ObjectId>,
) -> Result<()> {
// Start with the page's dictionary which includes annotations
let mut page_dict = page.to_dict();
page_dict.set("Type", Object::Name("Page".to_string()));
page_dict.set("Parent", Object::Reference(parent_id));
page_dict.set("Contents", Object::Reference(content_id));
// Get resources dictionary or create new one
let mut resources = if let Some(Object::Dictionary(res)) = page_dict.get("Resources") {
res.clone()
} else {
Dictionary::new()
};
// Add font resources
let mut font_dict = Dictionary::new();
// Add ALL standard PDF fonts (Type1) with WinAnsiEncoding
// This fixes the text rendering issue in dashboards where HelveticaBold was missing
// Helvetica family
let mut helvetica_dict = Dictionary::new();
helvetica_dict.set("Type", Object::Name("Font".to_string()));
helvetica_dict.set("Subtype", Object::Name("Type1".to_string()));
helvetica_dict.set("BaseFont", Object::Name("Helvetica".to_string()));
helvetica_dict.set("Encoding", Object::Name("WinAnsiEncoding".to_string()));
font_dict.set("Helvetica", Object::Dictionary(helvetica_dict));
let mut helvetica_bold_dict = Dictionary::new();
helvetica_bold_dict.set("Type", Object::Name("Font".to_string()));
helvetica_bold_dict.set("Subtype", Object::Name("Type1".to_string()));
helvetica_bold_dict.set("BaseFont", Object::Name("Helvetica-Bold".to_string()));
helvetica_bold_dict.set("Encoding", Object::Name("WinAnsiEncoding".to_string()));
font_dict.set("Helvetica-Bold", Object::Dictionary(helvetica_bold_dict));
let mut helvetica_oblique_dict = Dictionary::new();
helvetica_oblique_dict.set("Type", Object::Name("Font".to_string()));
helvetica_oblique_dict.set("Subtype", Object::Name("Type1".to_string()));
helvetica_oblique_dict.set("BaseFont", Object::Name("Helvetica-Oblique".to_string()));
helvetica_oblique_dict.set("Encoding", Object::Name("WinAnsiEncoding".to_string()));
font_dict.set(
"Helvetica-Oblique",
Object::Dictionary(helvetica_oblique_dict),
);
let mut helvetica_bold_oblique_dict = Dictionary::new();
helvetica_bold_oblique_dict.set("Type", Object::Name("Font".to_string()));
helvetica_bold_oblique_dict.set("Subtype", Object::Name("Type1".to_string()));
helvetica_bold_oblique_dict.set(
"BaseFont",
Object::Name("Helvetica-BoldOblique".to_string()),
);
helvetica_bold_oblique_dict.set("Encoding", Object::Name("WinAnsiEncoding".to_string()));
font_dict.set(
"Helvetica-BoldOblique",
Object::Dictionary(helvetica_bold_oblique_dict),
);
// Times family
let mut times_dict = Dictionary::new();
times_dict.set("Type", Object::Name("Font".to_string()));
times_dict.set("Subtype", Object::Name("Type1".to_string()));
times_dict.set("BaseFont", Object::Name("Times-Roman".to_string()));
times_dict.set("Encoding", Object::Name("WinAnsiEncoding".to_string()));
font_dict.set("Times-Roman", Object::Dictionary(times_dict));
let mut times_bold_dict = Dictionary::new();
times_bold_dict.set("Type", Object::Name("Font".to_string()));
times_bold_dict.set("Subtype", Object::Name("Type1".to_string()));
times_bold_dict.set("BaseFont", Object::Name("Times-Bold".to_string()));
times_bold_dict.set("Encoding", Object::Name("WinAnsiEncoding".to_string()));
font_dict.set("Times-Bold", Object::Dictionary(times_bold_dict));
let mut times_italic_dict = Dictionary::new();
times_italic_dict.set("Type", Object::Name("Font".to_string()));
times_italic_dict.set("Subtype", Object::Name("Type1".to_string()));
times_italic_dict.set("BaseFont", Object::Name("Times-Italic".to_string()));
times_italic_dict.set("Encoding", Object::Name("WinAnsiEncoding".to_string()));
font_dict.set("Times-Italic", Object::Dictionary(times_italic_dict));
let mut times_bold_italic_dict = Dictionary::new();
times_bold_italic_dict.set("Type", Object::Name("Font".to_string()));
times_bold_italic_dict.set("Subtype", Object::Name("Type1".to_string()));
times_bold_italic_dict.set("BaseFont", Object::Name("Times-BoldItalic".to_string()));
times_bold_italic_dict.set("Encoding", Object::Name("WinAnsiEncoding".to_string()));
font_dict.set(
"Times-BoldItalic",
Object::Dictionary(times_bold_italic_dict),
);
// Courier family
let mut courier_dict = Dictionary::new();
courier_dict.set("Type", Object::Name("Font".to_string()));
courier_dict.set("Subtype", Object::Name("Type1".to_string()));
courier_dict.set("BaseFont", Object::Name("Courier".to_string()));
courier_dict.set("Encoding", Object::Name("WinAnsiEncoding".to_string()));
font_dict.set("Courier", Object::Dictionary(courier_dict));
let mut courier_bold_dict = Dictionary::new();
courier_bold_dict.set("Type", Object::Name("Font".to_string()));
courier_bold_dict.set("Subtype", Object::Name("Type1".to_string()));
courier_bold_dict.set("BaseFont", Object::Name("Courier-Bold".to_string()));
courier_bold_dict.set("Encoding", Object::Name("WinAnsiEncoding".to_string()));
font_dict.set("Courier-Bold", Object::Dictionary(courier_bold_dict));
let mut courier_oblique_dict = Dictionary::new();
courier_oblique_dict.set("Type", Object::Name("Font".to_string()));
courier_oblique_dict.set("Subtype", Object::Name("Type1".to_string()));
courier_oblique_dict.set("BaseFont", Object::Name("Courier-Oblique".to_string()));
courier_oblique_dict.set("Encoding", Object::Name("WinAnsiEncoding".to_string()));
font_dict.set("Courier-Oblique", Object::Dictionary(courier_oblique_dict));
let mut courier_bold_oblique_dict = Dictionary::new();
courier_bold_oblique_dict.set("Type", Object::Name("Font".to_string()));
courier_bold_oblique_dict.set("Subtype", Object::Name("Type1".to_string()));
courier_bold_oblique_dict.set("BaseFont", Object::Name("Courier-BoldOblique".to_string()));
courier_bold_oblique_dict.set("Encoding", Object::Name("WinAnsiEncoding".to_string()));
font_dict.set(
"Courier-BoldOblique",
Object::Dictionary(courier_bold_oblique_dict),
);
// Add custom fonts (Type0 fonts for Unicode support)
for (font_name, font_id) in font_refs {
font_dict.set(font_name, Object::Reference(*font_id));
}
resources.set("Font", Object::Dictionary(font_dict));
// Add images and Form XObjects as XObjects
let has_images = !page.images().is_empty();
let has_forms = !page.form_xobjects().is_empty();
if has_images || has_forms {
let mut xobject_dict = Dictionary::new();
for (name, image) in page.images() {
// Use sequential ObjectId allocation to avoid conflicts
let image_id = self.allocate_object_id();
// Check if image has transparency (alpha channel)
if image.has_transparency() {
// Handle transparent images with SMask
let (mut main_obj, smask_obj) = image.to_pdf_object_with_transparency()?;
// If we have a soft mask, write it as a separate object and reference it
if let Some(smask_stream) = smask_obj {
let smask_id = self.allocate_object_id();
self.write_object(smask_id, smask_stream)?;
// Add SMask reference to the main image dictionary
if let Object::Stream(ref mut dict, _) = main_obj {
dict.set("SMask", Object::Reference(smask_id));
}
}
// Write the main image XObject (now with SMask reference if applicable)
self.write_object(image_id, main_obj)?;
} else {
// Write the image XObject without transparency
self.write_object(image_id, image.to_pdf_object())?;
}
// Add reference to XObject dictionary
xobject_dict.set(name, Object::Reference(image_id));
}
// Write Form XObjects (used for overlay/watermark operations)
for (name, form) in page.form_xobjects() {
let form_id = self.allocate_object_id();
let stream = form.to_stream()?;
let stream_obj =
Object::Stream(stream.dictionary().clone(), stream.data().to_vec());
self.write_object(form_id, stream_obj)?;
xobject_dict.set(name, Object::Reference(form_id));
}
resources.set("XObject", Object::Dictionary(xobject_dict));
}
// Add ExtGState resources for transparency
if let Some(extgstate_states) = page.get_extgstate_resources() {
let mut extgstate_dict = Dictionary::new();
for (name, state) in extgstate_states {
let mut state_dict = Dictionary::new();
state_dict.set("Type", Object::Name("ExtGState".to_string()));
// Add transparency parameters
if let Some(alpha_stroke) = state.alpha_stroke {
state_dict.set("CA", Object::Real(alpha_stroke));
}
if let Some(alpha_fill) = state.alpha_fill {
state_dict.set("ca", Object::Real(alpha_fill));
}
// Add other parameters as needed
if let Some(line_width) = state.line_width {
state_dict.set("LW", Object::Real(line_width));
}
if let Some(line_cap) = state.line_cap {
state_dict.set("LC", Object::Integer(line_cap as i64));
}
if let Some(line_join) = state.line_join {
state_dict.set("LJ", Object::Integer(line_join as i64));
}
if let Some(dash_pattern) = &state.dash_pattern {
let dash_objects: Vec<Object> = dash_pattern
.array
.iter()
.map(|&d| Object::Real(d))
.collect();
state_dict.set(
"D",
Object::Array(vec![
Object::Array(dash_objects),
Object::Real(dash_pattern.phase),
]),
);
}
extgstate_dict.set(name, Object::Dictionary(state_dict));
}
if !extgstate_dict.is_empty() {
resources.set("ExtGState", Object::Dictionary(extgstate_dict));
}
}
// Merge preserved resources from original PDF (if any)
// Phase 2.3: Rename preserved fonts to avoid conflicts with overlay fonts
if let Some(preserved_res) = page.get_preserved_resources() {
// Convert pdf_objects::Dictionary to writer Dictionary FIRST
let mut preserved_writer_dict = self.convert_pdf_objects_dict_to_writer(preserved_res);
// Step 1: Rename preserved fonts (F1 → OrigF1)
if let Some(Object::Dictionary(fonts)) = preserved_writer_dict.get("Font") {
// Rename font dictionary keys using our utility function
let renamed_fonts = crate::writer::rename_preserved_fonts(fonts);
// Replace Font dictionary with renamed version
preserved_writer_dict.set("Font", Object::Dictionary(renamed_fonts));
}
// Phase 3.3: Write embedded font streams as indirect objects
// Fonts that were resolved in Phase 3.2 have embedded Stream objects
// We need to write these streams as separate PDF objects and replace with References
if let Some(Object::Dictionary(fonts)) = preserved_writer_dict.get("Font") {
let mut fonts_with_refs = crate::objects::Dictionary::new();
for (font_name, font_obj) in fonts.iter() {
if let Object::Dictionary(font_dict) = font_obj {
// Try to extract and write embedded font streams
let updated_font = self.write_embedded_font_streams(font_dict)?;
fonts_with_refs.set(font_name, Object::Dictionary(updated_font));
} else {
// Not a dictionary, keep as-is
fonts_with_refs.set(font_name, font_obj.clone());
}
}
// Replace Font dictionary with version that has References instead of Streams
preserved_writer_dict.set("Font", Object::Dictionary(fonts_with_refs));
}
// Write preserved XObject streams as indirect objects
// XObjects resolved in from_parsed_with_content may contain inline Stream data.
// Per ISO 32000-1 §7.3.8, streams MUST be indirect objects.
if let Some(Object::Dictionary(xobjects)) = preserved_writer_dict.get("XObject") {
let mut xobjects_with_refs = crate::objects::Dictionary::new();
tracing::debug!(
"Externalizing {} preserved XObject entries as indirect objects",
xobjects.len()
);
for (xobj_name, xobj_obj) in xobjects.iter() {
match xobj_obj {
Object::Stream(dict, data) => {
let obj_id = self.allocate_object_id();
self.write_object(obj_id, Object::Stream(dict.clone(), data.clone()))?;
xobjects_with_refs.set(xobj_name, Object::Reference(obj_id));
}
Object::Dictionary(dict) => {
// Dictionary XObjects may contain nested streams (e.g., SMask)
let externalized = self.externalize_streams_in_dict(dict)?;
xobjects_with_refs.set(xobj_name, Object::Dictionary(externalized));
}
_ => {
xobjects_with_refs.set(xobj_name, xobj_obj.clone());
}
}
}
preserved_writer_dict.set("XObject", Object::Dictionary(xobjects_with_refs));
}
// Merge each resource category (Font, XObject, ColorSpace, etc.)
for (key, value) in preserved_writer_dict.iter() {
// If the resource category already exists, merge dictionaries
if let Some(Object::Dictionary(existing)) = resources.get(key) {
if let Object::Dictionary(preserved_dict) = value {
let mut merged = existing.clone();
// Add all preserved resources, giving priority to existing (overlay wins)
for (res_name, res_obj) in preserved_dict.iter() {
if !merged.contains_key(res_name) {
merged.set(res_name, res_obj.clone());
}
}
resources.set(key, Object::Dictionary(merged));
}
} else {
// Resource category doesn't exist yet, add it directly
resources.set(key, value.clone());
}
}
}
page_dict.set("Resources", Object::Dictionary(resources));
// Handle form widget annotations
if let Some(Object::Array(annots)) = page_dict.get("Annots") {
let mut new_annots = Vec::new();
for annot in annots {
if let Object::Dictionary(ref annot_dict) = annot {
if let Some(Object::Name(subtype)) = annot_dict.get("Subtype") {
if subtype == "Widget" {
// Process widget annotation
let widget_id = self.allocate_object_id();
self.write_object(widget_id, annot.clone())?;
new_annots.push(Object::Reference(widget_id));
// Track widget for form fields
if let Some(Object::Name(_ft)) = annot_dict.get("FT") {
if let Some(Object::String(field_name)) = annot_dict.get("T") {
self.field_widget_map
.entry(field_name.clone())
.or_default()
.push(widget_id);
self.field_id_map.insert(field_name.clone(), widget_id);
self.form_field_ids.push(widget_id);
}
}
continue;
}
}
}
new_annots.push(annot.clone());
}
if !new_annots.is_empty() {
page_dict.set("Annots", Object::Array(new_annots));
}
}
self.write_object(page_id, Object::Dictionary(page_dict))?;
Ok(())
}
}
impl PdfWriter<BufWriter<std::fs::File>> {
pub fn new(path: impl AsRef<Path>) -> Result<Self> {
let file = std::fs::File::create(path)?;
let writer = BufWriter::new(file);
Ok(Self {
writer,
xref_positions: HashMap::new(),
current_position: 0,
next_object_id: 1,
catalog_id: None,
pages_id: None,
info_id: None,
field_widget_map: HashMap::new(),
field_id_map: HashMap::new(),
form_field_ids: Vec::new(),
page_ids: Vec::new(),
config: WriterConfig::default(),
document_used_chars: None,
buffered_objects: HashMap::new(),
compressed_object_map: HashMap::new(),
prev_xref_offset: None,
base_pdf_size: None,
encrypt_obj_id: None,
file_id: None,
encryption_state: None,
pending_encrypt_dict: None,
})
}
}
impl<W: Write> PdfWriter<W> {
/// Write embedded font streams as indirect objects (Phase 3.3 + Phase 3.4)
///
/// Takes a font dictionary that may contain embedded Stream objects
/// in its FontDescriptor, writes those streams as separate PDF objects,
/// and returns an updated font dictionary with References instead of Streams.
///
/// For Type0 (composite) fonts, also handles:
/// - DescendantFonts array with embedded CIDFont dictionaries
/// - ToUnicode stream embedded directly in Type0 font
/// - CIDFont → FontDescriptor → FontFile2/FontFile3 chain
///
/// # Example
/// FontDescriptor:
/// FontFile2: Stream(dict, font_data) → Write stream as obj 50
/// FontFile2: Reference(50, 0) → Updated reference
/// Walks a dictionary and writes any inline Stream values as indirect objects,
/// replacing them with References. Required because PDF streams must be indirect
/// objects (ISO 32000-1 §7.3.8).
fn externalize_streams_in_dict(
&mut self,
dict: &crate::objects::Dictionary,
) -> Result<crate::objects::Dictionary> {
let mut result = crate::objects::Dictionary::new();
for (key, value) in dict.iter() {
match value {
Object::Stream(d, data) => {
let obj_id = self.allocate_object_id();
self.write_object(obj_id, Object::Stream(d.clone(), data.clone()))?;
result.set(key, Object::Reference(obj_id));
}
_ => {
result.set(key, value.clone());
}
}
}
Ok(result)
}
fn write_embedded_font_streams(
&mut self,
font_dict: &crate::objects::Dictionary,
) -> Result<crate::objects::Dictionary> {
let mut updated_font = font_dict.clone();
// Phase 3.4: Check for Type0 fonts with embedded DescendantFonts
if let Some(Object::Name(subtype)) = font_dict.get("Subtype") {
if subtype == "Type0" {
// Process DescendantFonts array
if let Some(Object::Array(descendants)) = font_dict.get("DescendantFonts") {
let mut updated_descendants = Vec::new();
for descendant in descendants {
match descendant {
Object::Dictionary(cidfont) => {
// CIDFont is embedded as Dictionary, process its FontDescriptor
let updated_cidfont =
self.write_cidfont_embedded_streams(cidfont)?;
// Write CIDFont as a separate object
let cidfont_id = self.allocate_object_id();
self.write_object(cidfont_id, Object::Dictionary(updated_cidfont))?;
// Replace with reference
updated_descendants.push(Object::Reference(cidfont_id));
}
Object::Reference(_) => {
// Already a reference, keep as-is
updated_descendants.push(descendant.clone());
}
_ => {
updated_descendants.push(descendant.clone());
}
}
}
updated_font.set("DescendantFonts", Object::Array(updated_descendants));
}
// Process ToUnicode stream if embedded
if let Some(Object::Stream(stream_dict, stream_data)) = font_dict.get("ToUnicode") {
let tounicode_id = self.allocate_object_id();
self.write_object(
tounicode_id,
Object::Stream(stream_dict.clone(), stream_data.clone()),
)?;
updated_font.set("ToUnicode", Object::Reference(tounicode_id));
}
return Ok(updated_font);
}
}
// Original Phase 3.3 logic for simple fonts (Type1, TrueType, etc.)
// Check if font has a FontDescriptor
if let Some(Object::Dictionary(descriptor)) = font_dict.get("FontDescriptor") {
let mut updated_descriptor = descriptor.clone();
let font_file_keys = ["FontFile", "FontFile2", "FontFile3"];
// Check each font file key for embedded streams
for key in &font_file_keys {
if let Some(Object::Stream(stream_dict, stream_data)) = descriptor.get(*key) {
// Found embedded stream! Write it as a separate object
let stream_id = self.allocate_object_id();
let stream_obj = Object::Stream(stream_dict.clone(), stream_data.clone());
self.write_object(stream_id, stream_obj)?;
// Replace Stream with Reference to the newly written object
updated_descriptor.set(*key, Object::Reference(stream_id));
}
// If it's already a Reference, leave it as-is
}
// Update FontDescriptor in font dictionary
updated_font.set("FontDescriptor", Object::Dictionary(updated_descriptor));
}
Ok(updated_font)
}
/// Helper function to process CIDFont embedded streams (Phase 3.4)
fn write_cidfont_embedded_streams(
&mut self,
cidfont: &crate::objects::Dictionary,
) -> Result<crate::objects::Dictionary> {
let mut updated_cidfont = cidfont.clone();
// Process FontDescriptor
if let Some(Object::Dictionary(descriptor)) = cidfont.get("FontDescriptor") {
let mut updated_descriptor = descriptor.clone();
let font_file_keys = ["FontFile", "FontFile2", "FontFile3"];
// Write embedded font streams
for key in &font_file_keys {
if let Some(Object::Stream(stream_dict, stream_data)) = descriptor.get(*key) {
let stream_id = self.allocate_object_id();
self.write_object(
stream_id,
Object::Stream(stream_dict.clone(), stream_data.clone()),
)?;
updated_descriptor.set(*key, Object::Reference(stream_id));
}
}
// Write FontDescriptor as a separate object
let descriptor_id = self.allocate_object_id();
self.write_object(descriptor_id, Object::Dictionary(updated_descriptor))?;
// Update CIDFont to reference the FontDescriptor
updated_cidfont.set("FontDescriptor", Object::Reference(descriptor_id));
}
// Process CIDToGIDMap if present and embedded as stream
if let Some(Object::Stream(map_dict, map_data)) = cidfont.get("CIDToGIDMap") {
let map_id = self.allocate_object_id();
self.write_object(map_id, Object::Stream(map_dict.clone(), map_data.clone()))?;
updated_cidfont.set("CIDToGIDMap", Object::Reference(map_id));
}
Ok(updated_cidfont)
}
fn allocate_object_id(&mut self) -> ObjectId {
let id = ObjectId::new(self.next_object_id, 0);
self.next_object_id += 1;
id
}
/// Get catalog_id, returning error if not initialized
fn get_catalog_id(&self) -> Result<ObjectId> {
self.catalog_id.ok_or_else(|| {
PdfError::InvalidOperation(
"catalog_id not initialized - write_document() must be called first".to_string(),
)
})
}
/// Get pages_id, returning error if not initialized
fn get_pages_id(&self) -> Result<ObjectId> {
self.pages_id.ok_or_else(|| {
PdfError::InvalidOperation(
"pages_id not initialized - write_document() must be called first".to_string(),
)
})
}
/// Get info_id, returning error if not initialized
fn get_info_id(&self) -> Result<ObjectId> {
self.info_id.ok_or_else(|| {
PdfError::InvalidOperation(
"info_id not initialized - write_document() must be called first".to_string(),
)
})
}
fn write_object(&mut self, id: ObjectId, object: Object) -> Result<()> {
use crate::writer::ObjectStreamWriter;
// Encrypt the object if encryption is active
let object = if let Some(ref enc_state) = self.encryption_state {
let mut obj = object;
enc_state.encryptor.encrypt_object(&mut obj, &id)?;
obj
} else {
object
};
// If object streams enabled and object is compressible, buffer it
if self.config.use_object_streams && ObjectStreamWriter::can_compress(&object) {
let mut buffer = Vec::new();
self.write_object_value_to_buffer(&object, &mut buffer)?;
self.buffered_objects.insert(id, buffer);
return Ok(());
}
// Otherwise write immediately (streams, encryption dicts, etc.)
self.xref_positions.insert(id, self.current_position);
// Pre-format header to count exact bytes once
let header = format!("{} {} obj\n", id.number(), id.generation());
self.write_bytes(header.as_bytes())?;
self.write_object_value(&object)?;
self.write_bytes(b"\nendobj\n")?;
Ok(())
}
fn write_object_value(&mut self, object: &Object) -> Result<()> {
match object {
Object::Null => self.write_bytes(b"null")?,
Object::Boolean(b) => self.write_bytes(if *b { b"true" } else { b"false" })?,
Object::Integer(i) => self.write_bytes(i.to_string().as_bytes())?,
Object::Real(f) => self.write_bytes(
format!("{f:.6}")
.trim_end_matches('0')
.trim_end_matches('.')
.as_bytes(),
)?,
Object::String(s) => {
self.write_bytes(b"(")?;
self.write_bytes(s.as_bytes())?;
self.write_bytes(b")")?;
}
Object::ByteString(bytes) => {
// Write as PDF hex string <AABB...> for byte-perfect binary data
self.write_bytes(b"<")?;
for byte in bytes {
self.write_bytes(format!("{byte:02X}").as_bytes())?;
}
self.write_bytes(b">")?;
}
Object::Name(n) => {
self.write_bytes(b"/")?;
self.write_bytes(n.as_bytes())?;
}
Object::Array(arr) => {
self.write_bytes(b"[")?;
for (i, obj) in arr.iter().enumerate() {
if i > 0 {
self.write_bytes(b" ")?;
}
self.write_object_value(obj)?;
}
self.write_bytes(b"]")?;
}
Object::Dictionary(dict) => {
self.write_bytes(b"<<")?;
for (key, value) in dict.entries() {
self.write_bytes(b"\n/")?;
self.write_bytes(key.as_bytes())?;
self.write_bytes(b" ")?;
self.write_object_value(value)?;
}
self.write_bytes(b"\n>>")?;
}
Object::Stream(dict, data) => {
// CRITICAL: Ensure Length in dictionary matches actual data length
// This prevents "Bad Length" PDF syntax errors
let mut corrected_dict = dict.clone();
corrected_dict.set("Length", Object::Integer(data.len() as i64));
self.write_object_value(&Object::Dictionary(corrected_dict))?;
self.write_bytes(b"\nstream\n")?;
self.write_bytes(data)?;
self.write_bytes(b"\nendstream")?;
}
Object::Reference(id) => {
let ref_str = format!("{} {} R", id.number(), id.generation());
self.write_bytes(ref_str.as_bytes())?;
}
}
Ok(())
}
/// Write object value to a buffer (for object streams)
fn write_object_value_to_buffer(&self, object: &Object, buffer: &mut Vec<u8>) -> Result<()> {
match object {
Object::Null => buffer.extend_from_slice(b"null"),
Object::Boolean(b) => buffer.extend_from_slice(if *b { b"true" } else { b"false" }),
Object::Integer(i) => buffer.extend_from_slice(i.to_string().as_bytes()),
Object::Real(f) => buffer.extend_from_slice(
format!("{f:.6}")
.trim_end_matches('0')
.trim_end_matches('.')
.as_bytes(),
),
Object::String(s) => {
buffer.push(b'(');
buffer.extend_from_slice(s.as_bytes());
buffer.push(b')');
}
Object::ByteString(bytes) => {
buffer.push(b'<');
for byte in bytes {
buffer.extend_from_slice(format!("{byte:02X}").as_bytes());
}
buffer.push(b'>');
}
Object::Name(n) => {
buffer.push(b'/');
buffer.extend_from_slice(n.as_bytes());
}
Object::Array(arr) => {
buffer.push(b'[');
for (i, obj) in arr.iter().enumerate() {
if i > 0 {
buffer.push(b' ');
}
self.write_object_value_to_buffer(obj, buffer)?;
}
buffer.push(b']');
}
Object::Dictionary(dict) => {
buffer.extend_from_slice(b"<<");
for (key, value) in dict.entries() {
buffer.extend_from_slice(b"\n/");
buffer.extend_from_slice(key.as_bytes());
buffer.push(b' ');
self.write_object_value_to_buffer(value, buffer)?;
}
buffer.extend_from_slice(b"\n>>");
}
Object::Stream(_, _) => {
// Streams should never be compressed in object streams
return Err(crate::error::PdfError::ObjectStreamError(
"Cannot compress stream objects in object streams".to_string(),
));
}
Object::Reference(id) => {
let ref_str = format!("{} {} R", id.number(), id.generation());
buffer.extend_from_slice(ref_str.as_bytes());
}
}
Ok(())
}
/// Flush buffered objects as compressed object streams
fn flush_object_streams(&mut self) -> Result<()> {
if self.buffered_objects.is_empty() {
return Ok(());
}
// Create object stream writer
let config = ObjectStreamConfig {
max_objects_per_stream: 100,
compression_level: 6,
enabled: true,
};
let mut os_writer = ObjectStreamWriter::new(config);
// Sort buffered objects by ID for deterministic output
let mut buffered: Vec<_> = self.buffered_objects.iter().collect();
buffered.sort_by_key(|(id, _)| id.number());
// Add all buffered objects to the stream writer
for (id, data) in buffered {
os_writer.add_object(*id, data.clone())?;
}
// Finalize and get completed streams
let streams = os_writer.finalize()?;
// Write each object stream to the PDF
for mut stream in streams {
let stream_id = stream.stream_id;
// Generate compressed stream data
let compressed_data = stream.generate_stream_data(6)?;
// Generate stream dictionary
let dict = stream.generate_dictionary(&compressed_data);
// Track compressed object mapping for xref
for (index, (obj_id, _)) in stream.objects.iter().enumerate() {
self.compressed_object_map
.insert(*obj_id, (stream_id, index as u32));
}
// Write the object stream itself
self.xref_positions.insert(stream_id, self.current_position);
let header = format!("{} {} obj\n", stream_id.number(), stream_id.generation());
self.write_bytes(header.as_bytes())?;
self.write_object_value(&Object::Dictionary(dict))?;
self.write_bytes(b"\nstream\n")?;
self.write_bytes(&compressed_data)?;
self.write_bytes(b"\nendstream\nendobj\n")?;
}
Ok(())
}
fn write_xref(&mut self) -> Result<()> {
self.write_bytes(b"xref\n")?;
// Sort by object number and write entries
let mut entries: Vec<_> = self
.xref_positions
.iter()
.map(|(id, pos)| (*id, *pos))
.collect();
entries.sort_by_key(|(id, _)| id.number());
// Find the highest object number to determine size
let max_obj_num = entries.iter().map(|(id, _)| id.number()).max().unwrap_or(0);
// Write subsection header - PDF 1.7 spec allows multiple subsections
// For simplicity, write one subsection from 0 to max
self.write_bytes(b"0 ")?;
self.write_bytes((max_obj_num + 1).to_string().as_bytes())?;
self.write_bytes(b"\n")?;
// Write free object entry
self.write_bytes(b"0000000000 65535 f \n")?;
// Write entries for all object numbers from 1 to max
// Fill in gaps with free entries
for obj_num in 1..=max_obj_num {
let _obj_id = ObjectId::new(obj_num, 0);
if let Some((_, position)) = entries.iter().find(|(id, _)| id.number() == obj_num) {
let entry = format!("{:010} {:05} n \n", position, 0);
self.write_bytes(entry.as_bytes())?;
} else {
// Free entry for gap
self.write_bytes(b"0000000000 00000 f \n")?;
}
}
Ok(())
}
fn write_xref_stream(&mut self) -> Result<()> {
let catalog_id = self.get_catalog_id()?;
let info_id = self.get_info_id()?;
// Allocate object ID for the xref stream
let xref_stream_id = self.allocate_object_id();
let xref_position = self.current_position;
// Create XRef stream writer with trailer information
let mut xref_writer = XRefStreamWriter::new(xref_stream_id);
xref_writer.set_trailer_info(catalog_id, info_id);
// Add free entry for object 0
xref_writer.add_free_entry(0, 65535);
// Sort entries by object number
let mut entries: Vec<_> = self
.xref_positions
.iter()
.map(|(id, pos)| (*id, *pos))
.collect();
entries.sort_by_key(|(id, _)| id.number());
// Find the highest object number (including the xref stream itself)
let max_obj_num = entries
.iter()
.map(|(id, _)| id.number())
.max()
.unwrap_or(0)
.max(xref_stream_id.number());
// Add entries for all objects (including compressed objects)
for obj_num in 1..=max_obj_num {
let obj_id = ObjectId::new(obj_num, 0);
if obj_num == xref_stream_id.number() {
// The xref stream entry will be added with the correct position
xref_writer.add_in_use_entry(xref_position, 0);
} else if let Some((stream_id, index)) = self.compressed_object_map.get(&obj_id) {
// Type 2: Object is compressed in an object stream
xref_writer.add_compressed_entry(stream_id.number(), *index);
} else if let Some((id, position)) =
entries.iter().find(|(id, _)| id.number() == obj_num)
{
// Type 1: Regular in-use entry
xref_writer.add_in_use_entry(*position, id.generation());
} else {
// Type 0: Free entry for gap
xref_writer.add_free_entry(0, 0);
}
}
// Mark position for xref stream object
self.xref_positions.insert(xref_stream_id, xref_position);
// Write object header
self.write_bytes(
format!(
"{} {} obj\n",
xref_stream_id.number(),
xref_stream_id.generation()
)
.as_bytes(),
)?;
// Get the encoded data
let uncompressed_data = xref_writer.encode_entries();
let final_data = if self.config.compress_streams {
crate::compression::compress(&uncompressed_data)?
} else {
uncompressed_data
};
// Create and write dictionary
let mut dict = xref_writer.create_dictionary(None);
dict.set("Length", Object::Integer(final_data.len() as i64));
// Add filter if compression is enabled
if self.config.compress_streams {
dict.set("Filter", Object::Name("FlateDecode".to_string()));
}
self.write_bytes(b"<<")?;
for (key, value) in dict.iter() {
self.write_bytes(b"\n/")?;
self.write_bytes(key.as_bytes())?;
self.write_bytes(b" ")?;
self.write_object_value(value)?;
}
self.write_bytes(b"\n>>\n")?;
// Write stream
self.write_bytes(b"stream\n")?;
self.write_bytes(&final_data)?;
self.write_bytes(b"\nendstream\n")?;
self.write_bytes(b"endobj\n")?;
// Write startxref and EOF
self.write_bytes(b"\nstartxref\n")?;
self.write_bytes(xref_position.to_string().as_bytes())?;
self.write_bytes(b"\n%%EOF\n")?;
Ok(())
}
/// Write the encryption dictionary as an indirect object and store
/// the object ID and file ID for the trailer.
/// Initialize encryption state: generates file ID, creates encryption dict,
/// computes encryption key, and builds the ObjectEncryptor.
/// The /Encrypt dict object is written later (after all other objects) since it
/// must NOT be encrypted itself (ISO 32000-1 §7.6.1).
fn init_encryption(&mut self, encryption: &crate::document::DocumentEncryption) -> Result<()> {
use crate::encryption::{
CryptFilterManager, CryptFilterMethod, FunctionalCryptFilter, ObjectEncryptor,
};
use std::sync::Arc;
// Generate file ID (16 random bytes, required by ISO 32000-1 §7.5.5)
let mut fid = vec![0u8; 16];
use rand::Rng;
rand::rng().fill_bytes(&mut fid);
let enc_dict = encryption
.create_encryption_dict(Some(&fid))
.map_err(|e| PdfError::EncryptionError(format!("encryption dict: {}", e)))?;
// Compute encryption key
let enc_key = encryption
.get_encryption_key(&enc_dict, Some(&fid))
.map_err(|e| PdfError::EncryptionError(format!("encryption key: {}", e)))?;
// Build CryptFilterManager based on encryption strength
let handler = encryption.handler();
let (method, key_len) = match encryption.strength {
crate::document::EncryptionStrength::Rc4_40bit => (CryptFilterMethod::V2, Some(5)),
crate::document::EncryptionStrength::Rc4_128bit => (CryptFilterMethod::V2, Some(16)),
crate::document::EncryptionStrength::Aes128 => (CryptFilterMethod::AESV2, Some(16)),
crate::document::EncryptionStrength::Aes256 => (CryptFilterMethod::AESV3, Some(32)),
};
let std_filter = FunctionalCryptFilter {
name: "StdCF".to_string(),
method,
length: key_len,
auth_event: crate::encryption::AuthEvent::DocOpen,
recipients: None,
};
let mut filter_manager =
CryptFilterManager::new(Box::new(handler), "StdCF".to_string(), "StdCF".to_string());
filter_manager.add_filter(std_filter);
let encryptor =
ObjectEncryptor::new(Arc::new(filter_manager), enc_key, enc_dict.encrypt_metadata);
// Reserve ID for /Encrypt dict (will be written at the end)
let encrypt_id = self.allocate_object_id();
self.encrypt_obj_id = Some(encrypt_id);
self.file_id = Some(fid);
self.encryption_state = Some(WriterEncryptionState { encryptor });
// Store the dict to write later
self.pending_encrypt_dict = Some(enc_dict.to_dict());
Ok(())
}
/// Write the /Encrypt dictionary object (must NOT be encrypted per ISO 32000-1 §7.6.1)
fn write_encryption_dict(&mut self) -> Result<()> {
if let (Some(encrypt_id), Some(dict)) =
(self.encrypt_obj_id, self.pending_encrypt_dict.take())
{
// Temporarily disable encryption so the /Encrypt dict is not encrypted
let enc_state = self.encryption_state.take();
self.write_object(encrypt_id, Object::Dictionary(dict))?;
self.encryption_state = enc_state;
}
Ok(())
}
fn write_trailer(&mut self, xref_position: u64) -> Result<()> {
let catalog_id = self.get_catalog_id()?;
let info_id = self.get_info_id()?;
// Find the highest object number to determine size
let max_obj_num = self
.xref_positions
.keys()
.map(|id| id.number())
.max()
.unwrap_or(0);
let mut trailer = Dictionary::new();
trailer.set("Size", Object::Integer((max_obj_num + 1) as i64));
trailer.set("Root", Object::Reference(catalog_id));
trailer.set("Info", Object::Reference(info_id));
// Add /Prev pointer for incremental updates (ISO 32000-1 §7.5.6)
if let Some(prev_xref) = self.prev_xref_offset {
trailer.set("Prev", Object::Integer(prev_xref as i64));
}
// Add /Encrypt reference and /ID array for encrypted documents
if let Some(encrypt_id) = self.encrypt_obj_id {
trailer.set("Encrypt", Object::Reference(encrypt_id));
}
if let Some(ref fid) = self.file_id {
trailer.set(
"ID",
Object::Array(vec![
Object::ByteString(fid.clone()),
Object::ByteString(fid.clone()),
]),
);
}
self.write_bytes(b"trailer\n")?;
self.write_object_value(&Object::Dictionary(trailer))?;
self.write_bytes(b"\nstartxref\n")?;
self.write_bytes(xref_position.to_string().as_bytes())?;
self.write_bytes(b"\n%%EOF\n")?;
Ok(())
}
fn write_bytes(&mut self, data: &[u8]) -> Result<()> {
self.writer.write_all(data)?;
self.current_position += data.len() as u64;
Ok(())
}
#[allow(dead_code)]
fn create_widget_appearance_stream(&mut self, widget_dict: &Dictionary) -> Result<ObjectId> {
// Get widget rectangle
let rect = if let Some(Object::Array(rect_array)) = widget_dict.get("Rect") {
if rect_array.len() >= 4 {
if let (
Some(Object::Real(x1)),
Some(Object::Real(y1)),
Some(Object::Real(x2)),
Some(Object::Real(y2)),
) = (
rect_array.first(),
rect_array.get(1),
rect_array.get(2),
rect_array.get(3),
) {
(*x1, *y1, *x2, *y2)
} else {
(0.0, 0.0, 100.0, 20.0) // Default
}
} else {
(0.0, 0.0, 100.0, 20.0) // Default
}
} else {
(0.0, 0.0, 100.0, 20.0) // Default
};
let width = rect.2 - rect.0;
let height = rect.3 - rect.1;
// Create appearance stream content
let mut content = String::new();
// Set graphics state
content.push_str("q\n");
// Draw border (black)
content.push_str("0 0 0 RG\n"); // Black stroke color
content.push_str("1 w\n"); // 1pt line width
// Draw rectangle border
content.push_str(&format!("0 0 {width} {height} re\n"));
content.push_str("S\n"); // Stroke
// Fill with white background
content.push_str("1 1 1 rg\n"); // White fill color
content.push_str(&format!("0.5 0.5 {} {} re\n", width - 1.0, height - 1.0));
content.push_str("f\n"); // Fill
// Restore graphics state
content.push_str("Q\n");
// Create stream dictionary
let mut stream_dict = Dictionary::new();
stream_dict.set("Type", Object::Name("XObject".to_string()));
stream_dict.set("Subtype", Object::Name("Form".to_string()));
stream_dict.set(
"BBox",
Object::Array(vec![
Object::Real(0.0),
Object::Real(0.0),
Object::Real(width),
Object::Real(height),
]),
);
stream_dict.set("Resources", Object::Dictionary(Dictionary::new()));
stream_dict.set("Length", Object::Integer(content.len() as i64));
// Write the appearance stream
let stream_id = self.allocate_object_id();
self.write_object(stream_id, Object::Stream(stream_dict, content.into_bytes()))?;
Ok(stream_id)
}
#[allow(dead_code)]
fn create_field_appearance_stream(
&mut self,
field_dict: &Dictionary,
widget: &crate::forms::Widget,
) -> Result<ObjectId> {
let width = widget.rect.upper_right.x - widget.rect.lower_left.x;
let height = widget.rect.upper_right.y - widget.rect.lower_left.y;
// Create appearance stream content
let mut content = String::new();
// Set graphics state
content.push_str("q\n");
// Draw background if specified
if let Some(bg_color) = &widget.appearance.background_color {
match bg_color {
crate::graphics::Color::Gray(g) => {
content.push_str(&format!("{g} g\n"));
}
crate::graphics::Color::Rgb(r, g, b) => {
content.push_str(&format!("{r} {g} {b} rg\n"));
}
crate::graphics::Color::Cmyk(c, m, y, k) => {
content.push_str(&format!("{c} {m} {y} {k} k\n"));
}
}
content.push_str(&format!("0 0 {width} {height} re\n"));
content.push_str("f\n");
}
// Draw border
if let Some(border_color) = &widget.appearance.border_color {
match border_color {
crate::graphics::Color::Gray(g) => {
content.push_str(&format!("{g} G\n"));
}
crate::graphics::Color::Rgb(r, g, b) => {
content.push_str(&format!("{r} {g} {b} RG\n"));
}
crate::graphics::Color::Cmyk(c, m, y, k) => {
content.push_str(&format!("{c} {m} {y} {k} K\n"));
}
}
content.push_str(&format!("{} w\n", widget.appearance.border_width));
content.push_str(&format!("0 0 {width} {height} re\n"));
content.push_str("S\n");
}
// For checkboxes, add a checkmark if checked
if let Some(Object::Name(ft)) = field_dict.get("FT") {
if ft == "Btn" {
if let Some(Object::Name(v)) = field_dict.get("V") {
if v == "Yes" {
// Draw checkmark
content.push_str("0 0 0 RG\n"); // Black
content.push_str("2 w\n");
let margin = width * 0.2;
content.push_str(&format!("{} {} m\n", margin, height / 2.0));
content.push_str(&format!("{} {} l\n", width / 2.0, margin));
content.push_str(&format!("{} {} l\n", width - margin, height - margin));
content.push_str("S\n");
}
}
}
}
// Restore graphics state
content.push_str("Q\n");
// Create stream dictionary
let mut stream_dict = Dictionary::new();
stream_dict.set("Type", Object::Name("XObject".to_string()));
stream_dict.set("Subtype", Object::Name("Form".to_string()));
stream_dict.set(
"BBox",
Object::Array(vec![
Object::Real(0.0),
Object::Real(0.0),
Object::Real(width),
Object::Real(height),
]),
);
stream_dict.set("Resources", Object::Dictionary(Dictionary::new()));
stream_dict.set("Length", Object::Integer(content.len() as i64));
// Write the appearance stream
let stream_id = self.allocate_object_id();
self.write_object(stream_id, Object::Stream(stream_dict, content.into_bytes()))?;
Ok(stream_id)
}
}
/// Format a DateTime as a PDF date string (D:YYYYMMDDHHmmSSOHH'mm)
fn format_pdf_date(date: DateTime<Utc>) -> String {
// Format the UTC date according to PDF specification
// D:YYYYMMDDHHmmSSOHH'mm where O is the relationship of local time to UTC (+ or -)
let formatted = date.format("D:%Y%m%d%H%M%S");
// For UTC, the offset is always +00'00
format!("{formatted}+00'00")
}
#[cfg(test)]
mod tests;
#[cfg(test)]
mod rigorous_tests;