ironpress 1.4.1

Pure Rust HTML/CSS/Markdown to PDF converter with layout engine, LaTeX math, tables, images, custom fonts, and streaming output. No browser, no system dependencies.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
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
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
#![warn(missing_docs)]
//! # ironpress
//!
//! Pure Rust HTML/CSS/Markdown to PDF converter. No browser, no system dependencies.
//!
//! ironpress converts HTML (with CSS) and Markdown into PDF documents using a
//! built-in layout engine. Unlike other Rust PDF crates, it does not shell out
//! to headless Chrome or wkhtmltopdf.
//!
//! ## Features
//!
//! - All common HTML elements: headings, paragraphs, lists, tables, images, links, semantic sections
//! - CSS support: selectors, flexbox, grid, floats, positioning, transforms, gradients, custom properties
//! - Built-in Markdown parser (no external dependencies)
//! - Custom TrueType font embedding
//! - JPEG and PNG images (data URIs and local files)
//! - Streaming output via `std::io::Write`
//! - Async file I/O via optional `tokio` integration
//! - HTML sanitization enabled by default
//!
//! ## Quick start
//!
//! ```
//! let pdf = ironpress::html_to_pdf("<h1>Hello</h1><p>World</p>").unwrap();
//! assert!(pdf.starts_with(b"%PDF"));
//! ```
//!
//! ## Markdown
//!
//! ```
//! let pdf = ironpress::markdown_to_pdf("# Hello\n\nWorld").unwrap();
//! assert!(pdf.starts_with(b"%PDF"));
//! ```
//!
//! ## Builder API
//!
//! ```
//! use ironpress::{HtmlConverter, PageSize, Margin};
//!
//! let pdf = HtmlConverter::new()
//!     .page_size(PageSize::LETTER)
//!     .margin(Margin::uniform(54.0))
//!     .sanitize(false)
//!     .convert("<h1>Hello</h1>")
//!     .unwrap();
//! ```
//!
//! ## Streaming output
//!
//! ```
//! let mut buf = Vec::new();
//! ironpress::html_to_pdf_writer("<h1>Hello</h1>", &mut buf).unwrap();
//! assert!(buf.starts_with(b"%PDF"));
//! ```
//!
//! ## Custom fonts
//!
//! ```no_run
//! use ironpress::HtmlConverter;
//!
//! let ttf = std::fs::read("fonts/MyFont.ttf").unwrap();
//! let pdf = HtmlConverter::new()
//!     .add_font("MyFont", ttf)
//!     .convert(r#"<p style="font-family: MyFont">Custom text</p>"#)
//!     .unwrap();
//! ```

/// Adobe Font Metrics for standard PDF fonts (Helvetica, Times, Courier).
pub(crate) mod bidi;
/// CLI argument parsing and conversion logic.
pub mod cli;
/// Error types for conversion failures.
pub mod error;
pub(crate) mod fonts;
pub(crate) mod layout;
pub(crate) mod parser;
pub(crate) mod render;
pub(crate) mod security;
pub(crate) mod style;
pub(crate) mod system_fonts;
pub(crate) mod text;
/// Public types: page size, margins, and colors.
pub mod types;
pub(crate) mod util;

/// Fetch bytes from a remote URL (requires the `remote` feature).
/// Returns `None` when the feature is disabled or the request fails.
#[allow(unused_variables)]
fn fetch_remote_bytes(url: &str) -> Option<Vec<u8>> {
    #[cfg(feature = "remote")]
    {
        let resp = ureq::get(url).call().ok()?;
        resp.into_body()
            .with_config()
            .limit(10 * 1024 * 1024)
            .read_to_vec()
            .ok()
    }
    #[cfg(not(feature = "remote"))]
    {
        None
    }
}

pub use error::IronpressError;
pub use types::{Margin, PageSize};

/// Convert an HTML string to PDF bytes using default settings (A4, 1-inch margins).
///
/// The HTML is sanitized before conversion to remove potentially dangerous
/// elements like `<script>`, `<iframe>`, and event handlers.
///
/// # Example
///
/// ```
/// let pdf = ironpress::html_to_pdf("<h1>Title</h1><p>Hello World</p>").unwrap();
/// assert!(pdf.starts_with(b"%PDF"));
/// ```
pub fn html_to_pdf(html: &str) -> Result<Vec<u8>, IronpressError> {
    HtmlConverter::new().convert(html)
}

/// Convert a Markdown string to PDF bytes using default settings (A4, 1-inch margins).
///
/// # Example
///
/// ```
/// let pdf = ironpress::markdown_to_pdf("# Hello\n\nWorld").unwrap();
/// assert!(pdf.starts_with(b"%PDF"));
/// ```
pub fn markdown_to_pdf(md: &str) -> Result<Vec<u8>, IronpressError> {
    let html = parser::markdown::markdown_to_html(md);
    HtmlConverter::new().convert(&html)
}

/// Convert a Markdown file to a PDF file using default settings.
///
/// # Example
///
/// ```no_run
/// ironpress::convert_markdown_file("input.md", "output.pdf").unwrap();
/// ```
pub fn convert_markdown_file(input: &str, output: &str) -> Result<(), IronpressError> {
    let md = std::fs::read_to_string(input)?;
    let pdf = markdown_to_pdf(&md)?;
    std::fs::write(output, pdf)?;
    Ok(())
}

/// Convert an HTML file to a PDF file using default settings.
///
/// # Example
///
/// ```no_run
/// ironpress::convert_file("input.html", "output.pdf").unwrap();
/// ```
pub fn convert_file(input: &str, output: &str) -> Result<(), IronpressError> {
    let html = std::fs::read_to_string(input)?;
    let pdf = html_to_pdf(&html)?;
    std::fs::write(output, pdf)?;
    Ok(())
}

/// Convert an HTML string to PDF, writing output to any `std::io::Write` implementation.
///
/// This is the streaming variant of [`html_to_pdf`]. Instead of returning a `Vec<u8>`,
/// it writes PDF content directly to the provided writer.
pub fn html_to_pdf_writer<W: std::io::Write>(
    html: &str,
    writer: &mut W,
) -> Result<(), IronpressError> {
    HtmlConverter::new().convert_to_writer(html, writer)
}

/// Convert a Markdown string to PDF, writing output to any `std::io::Write` implementation.
///
/// This is the streaming variant of [`markdown_to_pdf`].
pub fn markdown_to_pdf_writer<W: std::io::Write>(
    md: &str,
    writer: &mut W,
) -> Result<(), IronpressError> {
    let html = parser::markdown::markdown_to_html(md);
    HtmlConverter::new().convert_to_writer(&html, writer)
}

/// Async version of [`convert_file`]. Requires the `async` feature.
///
/// Uses `tokio::fs` for async file I/O and `tokio::task::spawn_blocking`
/// for the CPU-bound conversion step.
#[cfg(feature = "async")]
pub async fn convert_file_async(input: &str, output: &str) -> Result<(), IronpressError> {
    let html = tokio::fs::read_to_string(input).await?;
    let pdf = tokio::task::spawn_blocking(move || html_to_pdf(&html))
        .await
        .map_err(|e| IronpressError::RenderError(format!("task join error: {e}")))?;
    let pdf = pdf?;
    tokio::fs::write(output, pdf).await?;
    Ok(())
}

/// Async version of [`convert_markdown_file`]. Requires the `async` feature.
///
/// Uses `tokio::fs` for async file I/O and `tokio::task::spawn_blocking`
/// for the CPU-bound conversion step.
#[cfg(feature = "async")]
pub async fn convert_markdown_file_async(input: &str, output: &str) -> Result<(), IronpressError> {
    let md = tokio::fs::read_to_string(input).await?;
    let pdf = tokio::task::spawn_blocking(move || markdown_to_pdf(&md))
        .await
        .map_err(|e| IronpressError::RenderError(format!("task join error: {e}")))?;
    let pdf = pdf?;
    tokio::fs::write(output, pdf).await?;
    Ok(())
}

/// Builder for HTML-to-PDF conversion with custom options.
///
/// Use [`HtmlConverter::new`] to start, chain configuration methods,
/// then call [`convert`](HtmlConverter::convert) or
/// [`convert_to_writer`](HtmlConverter::convert_to_writer) to produce PDF output.
///
/// # Example
///
/// ```
/// use ironpress::{HtmlConverter, PageSize, Margin};
///
/// let pdf = HtmlConverter::new()
///     .page_size(PageSize::LETTER)
///     .margin(Margin::uniform(54.0))
///     .convert("<h1>Hello</h1>")
///     .unwrap();
/// ```
pub struct HtmlConverter {
    page_size: PageSize,
    margin: Margin,
    sanitize: bool,
    custom_fonts: std::collections::HashMap<String, Vec<u8>>,
    /// Base directory for resolving relative paths in `@import` and `@font-face` rules.
    base_path: Option<std::path::PathBuf>,
    /// Optional header text rendered at the top of each page.
    header: Option<String>,
    /// Optional footer text rendered at the bottom of each page.
    /// Use `{page}` for current page number and `{pages}` for total page count.
    footer: Option<String>,
}

impl HtmlConverter {
    /// Create a new converter with default settings (A4, 1-inch margins, sanitization enabled).
    pub fn new() -> Self {
        Self {
            page_size: PageSize::default(),
            margin: Margin::default(),
            sanitize: true,
            custom_fonts: std::collections::HashMap::new(),
            base_path: None,
            header: None,
            footer: None,
        }
    }

    /// Set the page size.
    pub fn page_size(mut self, size: PageSize) -> Self {
        self.page_size = size;
        self
    }

    /// Set the page margins.
    pub fn margin(mut self, margin: Margin) -> Self {
        self.margin = margin;
        self
    }

    /// Enable or disable HTML sanitization (enabled by default).
    pub fn sanitize(mut self, enabled: bool) -> Self {
        self.sanitize = enabled;
        self
    }

    /// Register a custom TrueType font.
    ///
    /// The `name` should match the `font-family` value used in CSS.
    /// The `ttf_data` is the raw contents of a `.ttf` file.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ironpress::HtmlConverter;
    ///
    /// let ttf_data = std::fs::read("MyFont.ttf").unwrap();
    /// let pdf = HtmlConverter::new()
    ///     .add_font("MyFont", ttf_data)
    ///     .convert(r#"<p style="font-family: MyFont">Custom text</p>"#)
    ///     .unwrap();
    /// ```
    pub fn add_font(mut self, name: &str, ttf_data: Vec<u8>) -> Self {
        self.custom_fonts
            .insert(name.to_ascii_lowercase(), ttf_data);
        self
    }

    /// Set the base directory for resolving relative paths in CSS `@import`
    /// and `@font-face` rules.
    ///
    /// When set, `@import "styles.css"` will resolve the path relative to
    /// this directory, and `@font-face { src: url("fonts/MyFont.ttf") }` will
    /// load the font file from this directory.
    ///
    /// Only local file paths are supported. Remote URLs (http/https) are
    /// rejected for security.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ironpress::HtmlConverter;
    /// use std::path::Path;
    ///
    /// let pdf = HtmlConverter::new()
    ///     .base_path(Path::new("/path/to/project"))
    ///     .convert(r#"<style>@import "styles.css";</style><p>Hello</p>"#)
    ///     .unwrap();
    /// ```
    pub fn base_path(mut self, path: &std::path::Path) -> Self {
        self.base_path = Some(path.to_path_buf());
        self
    }

    /// Set a header text rendered at the top of each page (in the top margin area).
    pub fn header(mut self, text: impl Into<String>) -> Self {
        self.header = Some(text.into());
        self
    }

    /// Set a footer text rendered at the bottom of each page (in the bottom margin area).
    ///
    /// Use `{page}` for the current page number and `{pages}` for the total page count.
    /// For example: `"Page {page} of {pages}"`.
    pub fn footer(mut self, text: impl Into<String>) -> Self {
        self.footer = Some(text.into());
        self
    }

    /// Convert a Markdown string to PDF bytes.
    ///
    /// The Markdown is first converted to HTML using the built-in parser,
    /// then processed through the normal HTML-to-PDF pipeline.
    ///
    /// # Example
    ///
    /// ```
    /// use ironpress::HtmlConverter;
    ///
    /// let pdf = HtmlConverter::new()
    ///     .convert_markdown("# Hello\n\nWorld")
    ///     .unwrap();
    /// ```
    pub fn convert_markdown(&self, md: &str) -> Result<Vec<u8>, IronpressError> {
        let html = parser::markdown::markdown_to_html(md);
        self.convert(&html)
    }

    /// Convert an HTML string to PDF bytes.
    pub fn convert(&self, html: &str) -> Result<Vec<u8>, IronpressError> {
        let mut buf = Vec::new();
        self.convert_to_writer(html, &mut buf)?;
        Ok(buf)
    }

    /// Convert an HTML string to PDF, writing directly to any `std::io::Write` implementation.
    pub fn convert_to_writer<W: std::io::Write>(
        &self,
        html: &str,
        writer: &mut W,
    ) -> Result<(), IronpressError> {
        // Step 1: Sanitize
        let html = if self.sanitize {
            security::sanitizer::sanitize_html(html)?
        } else {
            html.to_string()
        };

        // Step 2: Parse HTML and extract stylesheets
        let result = parser::html::parse_html_with_styles(&html)?;

        // Step 2b: Resolve @import rules in stylesheets (if base_path is set)
        let stylesheets: Vec<String> = if let Some(ref base) = self.base_path {
            result
                .stylesheets
                .iter()
                .map(|css| parser::css::resolve_imports(css, base, 0))
                .collect()
        } else {
            result.stylesheets
        };

        // Step 3: Parse @page rules first (they affect page dimensions for media queries)
        let mut page_rules = Vec::new();
        let mut font_face_rules = Vec::new();
        for css in &stylesheets {
            page_rules.extend(parser::css::parse_page_rules(css));
            font_face_rules.extend(parser::css::parse_font_face_rules(css));
        }

        // Step 3b: Apply @page rules to override page size and margins
        let mut effective_page_size = self.page_size;
        let mut effective_margin = self.margin;
        for pr in &page_rules {
            if let (Some(w), Some(h)) = (pr.width, pr.height) {
                effective_page_size = PageSize {
                    width: w,
                    height: h,
                };
            }
            if let Some(v) = pr.margin_top {
                effective_margin.top = v;
            }
            if let Some(v) = pr.margin_right {
                effective_margin.right = v;
            }
            if let Some(v) = pr.margin_bottom {
                effective_margin.bottom = v;
            }
            if let Some(v) = pr.margin_left {
                effective_margin.left = v;
            }
        }

        // Step 3c: Parse stylesheets with page-aware media query context
        let media_ctx = parser::css::MediaContext {
            width: effective_page_size.width,
            height: effective_page_size.height,
        };
        let mut rules = Vec::new();
        for css in &stylesheets {
            rules.extend(parser::css::parse_stylesheet_with_context(
                css,
                Some(media_ctx),
            ));
        }

        // Step 4: Parse custom fonts (API-registered + @font-face from CSS)
        let mut parsed_fonts = self.parse_custom_fonts();

        // Step 4b: Load fonts from @font-face rules (local files + remote URLs)
        for ff_rule in &font_face_rules {
            let is_remote =
                ff_rule.src_path.starts_with("http://") || ff_rule.src_path.starts_with("https://");

            let ttf_data = if is_remote {
                fetch_remote_bytes(&ff_rule.src_path)
            } else if let Some(ref base) = self.base_path {
                let font_path = base.join(&ff_rule.src_path);
                if !parser::css::is_path_within(&font_path, base) {
                    continue;
                }
                std::fs::read(&font_path).ok()
            } else {
                None
            };

            if let Some(data) = ttf_data {
                if let Ok(font) = parser::ttf::parse_ttf(data) {
                    parsed_fonts.insert(ff_rule.font_family.to_ascii_lowercase(), font);
                }
            }
        }

        system_fonts::load_requested_system_fonts(&result.nodes, &rules, &mut parsed_fonts);
        system_fonts::load_unicode_fallback_font(&mut parsed_fonts);
        system_fonts::load_emoji_fallback_font(&mut parsed_fonts);

        // Step 5: Layout
        let pages = layout::engine::layout_with_rules_and_fonts(
            &result.nodes,
            effective_page_size,
            effective_margin,
            &rules,
            &parsed_fonts,
        );

        // Step 6: Render PDF
        let decoration = if self.header.is_some() || self.footer.is_some() {
            Some(render::pdf::PageDecoration {
                header: self.header.clone(),
                footer: self.footer.clone(),
            })
        } else {
            None
        };

        render::pdf::render_pdf_to_writer_full(
            &pages,
            effective_page_size,
            effective_margin,
            writer,
            &parsed_fonts,
            decoration.as_ref(),
        )
    }

    /// Convert a Markdown string to PDF, writing directly to any `std::io::Write` implementation.
    ///
    /// Streaming variant of [`convert_markdown`](HtmlConverter::convert_markdown).
    pub fn convert_markdown_to_writer<W: std::io::Write>(
        &self,
        md: &str,
        writer: &mut W,
    ) -> Result<(), IronpressError> {
        let html = parser::markdown::markdown_to_html(md);
        self.convert_to_writer(&html, writer)
    }

    /// Parse all registered custom fonts into TtfFont structs.
    fn parse_custom_fonts(&self) -> std::collections::HashMap<String, parser::ttf::TtfFont> {
        let mut fonts = std::collections::HashMap::new();
        for (name, data) in &self.custom_fonts {
            if let Ok(font) = parser::ttf::parse_ttf(data.clone()) {
                fonts.insert(name.clone(), font);
            }
        }
        fonts
    }
}

impl Default for HtmlConverter {
    fn default() -> Self {
        Self::new()
    }
}

impl HtmlConverter {
    /// Async version of [`HtmlConverter::convert`] for file-based conversion.
    /// Requires the `async` feature.
    ///
    /// Reads the input HTML file asynchronously, performs the CPU-bound conversion
    /// in a blocking task, then writes the output PDF asynchronously.
    #[cfg(feature = "async")]
    pub async fn convert_file_async(
        &self,
        input: &str,
        output: &str,
    ) -> Result<(), IronpressError> {
        let html = tokio::fs::read_to_string(input).await?;
        let page_size = self.page_size;
        let margin = self.margin;
        let sanitize = self.sanitize;
        let pdf = tokio::task::spawn_blocking(move || {
            HtmlConverter::new()
                .page_size(page_size)
                .margin(margin)
                .sanitize(sanitize)
                .convert(&html)
        })
        .await
        .map_err(|e| IronpressError::RenderError(format!("task join error: {e}")))?;
        let pdf = pdf?;
        tokio::fs::write(output, pdf).await?;
        Ok(())
    }
}

// --- WebAssembly bindings ---

/// WASM bindings for browser-side PDF generation.
///
/// Enable with `cargo build --features wasm --target wasm32-unknown-unknown`.
#[cfg(feature = "wasm")]
pub mod wasm {
    use wasm_bindgen::prelude::*;

    /// Convert HTML to PDF bytes.
    ///
    /// Returns a `Uint8Array` containing the PDF document.
    #[wasm_bindgen(js_name = "htmlToPdf")]
    pub fn html_to_pdf(html: &str) -> Result<js_sys::Uint8Array, JsError> {
        let bytes = crate::html_to_pdf(html).map_err(|e| JsError::new(&e.to_string()))?;
        Ok(js_sys::Uint8Array::from(bytes.as_slice()))
    }

    /// Convert Markdown to PDF bytes.
    ///
    /// Returns a `Uint8Array` containing the PDF document.
    #[wasm_bindgen(js_name = "markdownToPdf")]
    pub fn markdown_to_pdf(md: &str) -> Result<js_sys::Uint8Array, JsError> {
        let bytes = crate::markdown_to_pdf(md).map_err(|e| JsError::new(&e.to_string()))?;
        Ok(js_sys::Uint8Array::from(bytes.as_slice()))
    }

    /// Convert HTML to PDF with custom page size and margins.
    ///
    /// `page_width` and `page_height` are in points (1 inch = 72 points).
    /// `margin_top`, `margin_right`, `margin_bottom`, `margin_left` are in points.
    #[wasm_bindgen(js_name = "htmlToPdfCustom")]
    pub fn html_to_pdf_custom(
        html: &str,
        page_width: f32,
        page_height: f32,
        margin_top: f32,
        margin_right: f32,
        margin_bottom: f32,
        margin_left: f32,
    ) -> Result<js_sys::Uint8Array, JsError> {
        let bytes = crate::HtmlConverter::new()
            .page_size(crate::PageSize::new(page_width, page_height))
            .margin(crate::Margin {
                top: margin_top,
                right: margin_right,
                bottom: margin_bottom,
                left: margin_left,
            })
            .convert(html)
            .map_err(|e| JsError::new(&e.to_string()))?;
        Ok(js_sys::Uint8Array::from(bytes.as_slice()))
    }
}

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

    #[test]
    fn html_to_pdf_basic() {
        let pdf = html_to_pdf("<h1>Hello</h1><p>World</p>").unwrap();
        assert!(pdf.starts_with(b"%PDF-1.4"));
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("%%EOF"));
    }

    #[test]
    fn html_to_pdf_with_styles() {
        let html = r#"<h1 style="color: red; text-align: center">Title</h1>
                      <p style="font-size: 14pt">Some text here.</p>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn html_to_pdf_with_formatting() {
        let html = "<p>Normal <strong>bold</strong> <em>italic</em> <u>underline</u></p>";
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("Helvetica-Bold"));
        assert!(content.contains("Helvetica-Oblique"));
    }

    #[test]
    fn html_to_pdf_empty() {
        let pdf = html_to_pdf("").unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn html_to_pdf_sanitizes_script() {
        let html = "<p>Safe</p><script>alert('xss')</script>";
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(!content.contains("alert"));
        assert!(content.contains("Safe"));
    }

    #[test]
    fn converter_builder() {
        let pdf = HtmlConverter::new()
            .page_size(PageSize::LETTER)
            .margin(Margin::uniform(54.0))
            .convert("<p>Test</p>")
            .unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn converter_no_sanitize() {
        let pdf = HtmlConverter::new()
            .sanitize(false)
            .convert("<p>Test</p>")
            .unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn html_to_pdf_headings() {
        let html = "<h1>H1</h1><h2>H2</h2><h3>H3</h3><h4>H4</h4><h5>H5</h5><h6>H6</h6>";
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn html_to_pdf_horizontal_rule() {
        let pdf = html_to_pdf("<p>Above</p><hr><p>Below</p>").unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn html_to_pdf_line_break() {
        let pdf = html_to_pdf("<p>Line one<br>Line two</p>").unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn convert_file_roundtrip() {
        let dir = std::env::temp_dir();
        let input = dir.join("ironpress_test_input.html");
        let output = dir.join("ironpress_test_output.pdf");
        std::fs::write(&input, "<h1>Test</h1><p>Hello</p>").unwrap();
        convert_file(input.to_str().unwrap(), output.to_str().unwrap()).unwrap();
        let pdf = std::fs::read(&output).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
        std::fs::remove_file(&input).ok();
        std::fs::remove_file(&output).ok();
    }

    #[test]
    fn converter_default_impl() {
        let converter = HtmlConverter::default();
        let pdf = converter.convert("<p>Default</p>").unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn markdown_to_pdf_roundtrip() {
        // Exercises markdown_to_pdf() (line 64-67)
        let pdf = markdown_to_pdf("# Test\n\nHello **world**").unwrap();
        assert!(pdf.starts_with(b"%PDF"));
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("Test"));
        assert!(content.contains("world"));
    }

    #[test]
    fn convert_markdown_file_roundtrip() {
        // Exercises convert_markdown_file() (lines 76-80)
        let dir = std::env::temp_dir();
        let input = dir.join("ironpress_test_md_input.md");
        let output = dir.join("ironpress_test_md_output.pdf");
        std::fs::write(&input, "# Hello\n\nWorld").unwrap();
        convert_markdown_file(input.to_str().unwrap(), output.to_str().unwrap()).unwrap();
        let pdf = std::fs::read(&output).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("Hello"));
        std::fs::remove_file(&input).ok();
        std::fs::remove_file(&output).ok();
    }

    #[test]
    fn convert_markdown_file_missing_input() {
        let result = convert_markdown_file("/nonexistent/file.md", "/tmp/out.pdf");
        assert!(result.is_err());
    }

    #[test]
    fn html_to_pdf_unordered_list() {
        let html = "<ul><li>Item one</li><li>Item two</li><li>Item three</li></ul>";
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("-"));
        assert!(content.contains("Item"));
    }

    #[test]
    fn html_to_pdf_ordered_list() {
        let html = "<ol><li>First</li><li>Second</li><li>Third</li></ol>";
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("1."));
        assert!(content.contains("2."));
        assert!(content.contains("3."));
    }

    #[test]
    fn html_to_pdf_table() {
        let html = r#"
            <table>
                <tr><th>Name</th><th>Age</th></tr>
                <tr><td>Alice</td><td>30</td></tr>
                <tr><td>Bob</td><td>25</td></tr>
            </table>
        "#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("Name"));
        assert!(content.contains("Alice"));
        assert!(content.contains("Bob"));
        // No default cell borders — only CSS-specified borders produce strokes
    }

    #[test]
    fn html_to_pdf_table_with_sections() {
        let html = r#"
            <table>
                <thead><tr><th>Header</th></tr></thead>
                <tbody><tr><td>Body</td></tr></tbody>
                <tfoot><tr><td>Footer</td></tr></tfoot>
            </table>
        "#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("Header"));
        assert!(content.contains("Body"));
        assert!(content.contains("Footer"));
    }

    #[test]
    fn html_to_pdf_with_style_block() {
        let html = r#"
            <html>
            <head><style>p { color: red } .highlight { font-weight: bold }</style></head>
            <body>
                <p>Red text</p>
                <p class="highlight">Bold red text</p>
            </body>
            </html>
        "#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("1 0 0 rg")); // red color
        assert!(content.contains("Helvetica-Bold")); // bold from .highlight
    }

    #[test]
    fn html_to_pdf_style_block_in_body() {
        let html = r#"
            <style>h1 { color: blue }</style>
            <h1>Blue Title</h1>
        "#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("0 0 1 rg")); // blue color
    }

    #[test]
    fn html_to_pdf_definition_list() {
        let html = "<dl><dt>Term</dt><dd>Definition here</dd></dl>";
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("Term"));
        assert!(content.contains("Definition"));
    }

    #[test]
    fn markdown_to_pdf_basic() {
        let pdf = markdown_to_pdf("# Hello\n\nWorld").unwrap();
        assert!(pdf.starts_with(b"%PDF"));
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("Hello"));
        assert!(content.contains("World"));
    }

    #[test]
    fn markdown_to_pdf_formatting() {
        let pdf = markdown_to_pdf("**bold** and *italic*").unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("Helvetica-Bold"));
        assert!(content.contains("Helvetica-Oblique"));
    }

    #[test]
    fn markdown_to_pdf_list() {
        let pdf = markdown_to_pdf("- one\n- two\n- three").unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("one"));
        assert!(content.contains("two"));
    }

    #[test]
    fn markdown_to_pdf_code_block() {
        let md = "# Code\n\n```\nfn main() {}\n```";
        let pdf = markdown_to_pdf(md).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn markdown_to_pdf_full() {
        let md = r#"# Project Title

Some **bold** and *italic* text with `inline code`.

## Features

- Item one
- Item two
- Item three

1. First
2. Second

> A wise quote

---

```
fn main() {
    println!("hello");
}
```

[Link](https://example.com)
"#;
        let pdf = markdown_to_pdf(md).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("Project"));
        assert!(content.contains("Title"));
    }

    #[test]
    fn converter_markdown() {
        let pdf = HtmlConverter::new()
            .page_size(PageSize::LETTER)
            .convert_markdown("# Hello")
            .unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn html_to_pdf_full_document() {
        let html = r#"
            <html>
            <head><title>Test</title></head>
            <body>
                <h1>Document Title</h1>
                <p>This is a <strong>bold</strong> and <em>italic</em> paragraph.</p>
                <hr>
                <p style="color: blue; text-align: center">Centered blue text.</p>
            </body>
            </html>
        "#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("Document"));
        assert!(content.contains("Title"));
    }

    #[test]
    fn html_to_pdf_display_none_hides_element() {
        let html = r#"<p>Visible</p><p style="display: none">Secret</p><p>Remaining</p>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("Visible"));
        assert!(!content.contains("Secret"));
        assert!(content.contains("Remaining"));
    }

    #[test]
    fn html_to_pdf_display_block_on_span() {
        let html = r#"<p><span style="display: block">Blocked</span></p>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("Blocked"));
    }

    #[test]
    fn html_to_pdf_media_print_applied() {
        let html = r#"
            <html>
            <head><style>
                @media print { p { color: red } }
            </style></head>
            <body><p>Print styled</p></body>
            </html>
        "#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("1 0 0 rg")); // red color applied
    }

    #[test]
    fn html_to_pdf_media_screen_ignored() {
        let html = r#"
            <html>
            <head><style>
                @media screen { p { color: red } }
            </style></head>
            <body><p>Not red</p></body>
            </html>
        "#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        // Should NOT have red color since screen media is ignored
        assert!(!content.contains("1 0 0 rg"));
    }

    #[test]
    fn html_to_pdf_strikethrough() {
        let html = "<p><del>deleted</del> and <s>struck</s></p>";
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("deleted"));
        assert!(content.contains("struck"));
    }

    #[test]
    fn html_to_pdf_page_break() {
        let html = r#"<p style="page-break-after: always">Page one</p><p>Page two</p>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn html_to_pdf_border() {
        let html = r#"<div style="border: 2px solid blue">Bordered content</div>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("Bordered"));
    }

    #[test]
    fn html_to_pdf_font_families() {
        let html = r#"
            <p style="font-family: serif">Serif text</p>
            <p style="font-family: monospace">Mono text</p>
        "#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("Times-Roman"));
        assert!(content.contains("Courier"));
    }

    #[test]
    fn html_to_pdf_table_colspan() {
        let html = r#"
            <table>
                <tr><td colspan="2">Wide</td></tr>
                <tr><td>A</td><td>B</td></tr>
            </table>
        "#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("Wide"));
    }

    #[test]
    fn html_to_pdf_style_border_color_and_width() {
        let html = r#"
            <html>
            <head><style>div { border-width: 2pt; border-color: red }</style></head>
            <body><div>Bordered</div></body>
            </html>
        "#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn sanitizer_malformed_style_tag() {
        // Style tag without closing tag
        let html = "<style>p { color: red }";
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn sanitizer_event_handler_with_spaces() {
        let html = r#"<p onclick = "alert('xss')">Safe text</p>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(!content.contains("alert"));
        assert!(content.contains("Safe"));
    }

    // --- Streaming output tests ---

    #[test]
    fn streaming_produces_same_output_as_non_streaming() {
        let html = "<h1>Hello</h1><p>World</p>";
        let pdf_vec = html_to_pdf(html).unwrap();
        let mut streamed = Vec::new();
        html_to_pdf_writer(html, &mut streamed).unwrap();
        assert_eq!(pdf_vec, streamed);
    }

    #[test]
    fn streaming_markdown_produces_same_output() {
        let md = "# Title\n\nSome **bold** text.";
        let pdf_vec = markdown_to_pdf(md).unwrap();
        let mut streamed = Vec::new();
        markdown_to_pdf_writer(md, &mut streamed).unwrap();
        assert_eq!(pdf_vec, streamed);
    }

    #[test]
    fn streaming_to_file() {
        let dir = std::env::temp_dir();
        let output = dir.join("ironpress_stream_test.pdf");
        let mut file = std::fs::File::create(&output).unwrap();
        html_to_pdf_writer("<p>Streamed</p>", &mut file).unwrap();
        drop(file);
        let pdf = std::fs::read(&output).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("Streamed"));
        std::fs::remove_file(&output).ok();
    }

    #[test]
    fn converter_convert_to_writer() {
        let html = "<p>Builder streaming</p>";
        let pdf_vec = HtmlConverter::new().convert(html).unwrap();
        let mut streamed = Vec::new();
        HtmlConverter::new()
            .convert_to_writer(html, &mut streamed)
            .unwrap();
        assert_eq!(pdf_vec, streamed);
    }

    #[test]
    fn converter_convert_markdown_to_writer() {
        let md = "# Markdown streaming";
        let pdf_vec = HtmlConverter::new().convert_markdown(md).unwrap();
        let mut streamed = Vec::new();
        HtmlConverter::new()
            .convert_markdown_to_writer(md, &mut streamed)
            .unwrap();
        assert_eq!(pdf_vec, streamed);
    }

    #[test]
    fn url_image_ignored_without_remote_feature() {
        // Without the "remote" feature, remote URLs produce no image
        let html = r#"<img src="https://example.com/image.png" width="100" height="100">"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn fetch_remote_bytes_returns_none_without_feature() {
        #[cfg(not(feature = "remote"))]
        assert!(fetch_remote_bytes("https://example.com/test").is_none());
    }

    #[test]
    fn remote_image_produces_valid_pdf() {
        // Remote images are silently ignored without the "remote" feature
        let html =
            r#"<img src="https://example.com/test.png" width="100" height="100"><p>Text</p>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("Text"));
    }

    #[test]
    fn remote_font_face_produces_valid_pdf() {
        // Remote font-face URLs are parsed but font loading is skipped without "remote" feature
        let html = r#"
            <style>
                @font-face { font-family: "RemoteFont"; src: url("https://example.com/font.ttf"); }
                p { font-family: RemoteFont; }
            </style>
            <p>Fallback to Helvetica</p>
        "#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn header_footer_with_special_chars() {
        let pdf = HtmlConverter::new()
            .header("Report (Draft)")
            .footer("Page {page} / {pages}")
            .convert("<p>Content</p>")
            .unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn multi_column_full_pipeline() {
        let html = r#"
            <style>.cols { column-count: 2; column-gap: 10pt; }</style>
            <div class="cols"><div>Left</div><div>Right</div></div>
        "#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn grid_repeat_full_pipeline() {
        let html = r#"
            <style>.g { display: grid; grid-template-columns: repeat(3, 1fr); gap: 5pt; }</style>
            <div class="g"><div>A</div><div>B</div><div>C</div></div>
        "#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn grid_minmax_full_pipeline() {
        let html = r#"
            <style>.g { display: grid; grid-template-columns: minmax(50px, 1fr) 2fr; }</style>
            <div class="g"><div>A</div><div>B</div></div>
        "#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    // --- Async tests (feature-gated) ---

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn async_convert_file_roundtrip() {
        let dir = std::env::temp_dir();
        let input = dir.join("ironpress_async_test_input.html");
        let output = dir.join("ironpress_async_test_output.pdf");
        tokio::fs::write(&input, "<h1>Async</h1><p>Test</p>")
            .await
            .unwrap();
        convert_file_async(input.to_str().unwrap(), output.to_str().unwrap())
            .await
            .unwrap();
        let pdf = tokio::fs::read(&output).await.unwrap();
        assert!(pdf.starts_with(b"%PDF"));
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("Async"));
        tokio::fs::remove_file(&input).await.ok();
        tokio::fs::remove_file(&output).await.ok();
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn async_convert_markdown_file_roundtrip() {
        let dir = std::env::temp_dir();
        let input = dir.join("ironpress_async_md_test.md");
        let output = dir.join("ironpress_async_md_test.pdf");
        tokio::fs::write(&input, "# Async MD\n\nHello")
            .await
            .unwrap();
        convert_markdown_file_async(input.to_str().unwrap(), output.to_str().unwrap())
            .await
            .unwrap();
        let pdf = tokio::fs::read(&output).await.unwrap();
        assert!(pdf.starts_with(b"%PDF"));
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("Async"));
        tokio::fs::remove_file(&input).await.ok();
        tokio::fs::remove_file(&output).await.ok();
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn async_converter_convert_file() {
        let dir = std::env::temp_dir();
        let input = dir.join("ironpress_async_builder_input.html");
        let output = dir.join("ironpress_async_builder_output.pdf");
        tokio::fs::write(&input, "<p>Builder async</p>")
            .await
            .unwrap();
        HtmlConverter::new()
            .page_size(PageSize::LETTER)
            .convert_file_async(input.to_str().unwrap(), output.to_str().unwrap())
            .await
            .unwrap();
        let pdf = tokio::fs::read(&output).await.unwrap();
        assert!(pdf.starts_with(b"%PDF"));
        tokio::fs::remove_file(&input).await.ok();
        tokio::fs::remove_file(&output).await.ok();
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn async_convert_file_missing_input() {
        let result = convert_file_async("/nonexistent/file.html", "/tmp/out.pdf").await;
        assert!(result.is_err());
    }

    #[test]
    fn html_to_pdf_with_width() {
        let html = r#"<div style="width: 200pt">Constrained width</div>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn html_to_pdf_with_max_width() {
        let html = r#"<div style="max-width: 300pt">Max width block</div>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn html_to_pdf_with_height() {
        let html = r#"<div style="height: 100pt">Fixed height</div>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn html_to_pdf_with_opacity() {
        let html = r#"<div style="opacity: 0.5">Semi-transparent</div>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("/ExtGState"));
        assert!(content.contains("/ca 0.5"));
    }

    // --- Integration tests for float / clear / position / box-shadow ---

    #[test]
    fn html_to_pdf_with_float_left() {
        let html = r#"<div style="float: left; width: 100pt">Floated</div><div>Normal</div>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn html_to_pdf_with_clear_both() {
        let html = r#"
            <div style="float: left">Floated</div>
            <div style="clear: both">Cleared</div>
        "#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn html_to_pdf_with_position_relative() {
        let html = r#"<div style="position: relative; top: 10pt; left: 5pt">Offset content</div>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn html_to_pdf_with_position_absolute() {
        let html = r#"<div style="position: absolute; top: 100pt; left: 50pt">Absolute</div>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn html_to_pdf_with_box_shadow() {
        let html = r#"<div style="box-shadow: 3px 3px black">Shadowed</div>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
        // The PDF should contain the shadow rectangle (a filled rect with black color)
        let content = String::from_utf8_lossy(&pdf);
        assert!(
            content.contains("re\nf"),
            "Box shadow should produce a filled rectangle"
        );
    }

    #[test]
    fn html_to_pdf_float_and_clear_combined() {
        let html = r#"
            <div style="float: left; width: 150pt">Left sidebar</div>
            <div style="float: right; width: 150pt">Right sidebar</div>
            <div style="clear: both">Footer content below floats</div>
        "#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn html_to_pdf_box_shadow_with_blur() {
        let html = r#"<div style="box-shadow: 2px 2px 4px red">Shadow with blur</div>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    /// Build a minimal valid TTF for integration testing.
    fn build_integration_test_ttf() -> Vec<u8> {
        let mut buf = Vec::new();
        let num_tables: u16 = 6;
        buf.extend_from_slice(&[0, 1, 0, 0]);
        buf.extend_from_slice(&num_tables.to_be_bytes());
        buf.extend_from_slice(&0u16.to_be_bytes());
        buf.extend_from_slice(&0u16.to_be_bytes());
        buf.extend_from_slice(&0u16.to_be_bytes());
        let dir_start = buf.len();
        buf.resize(dir_start + num_tables as usize * 16, 0);

        // head table (54 bytes)
        let head_offset = buf.len();
        buf.extend_from_slice(&[0, 1, 0, 0]);
        buf.extend_from_slice(&[0; 4]);
        buf.extend_from_slice(&[0; 4]);
        buf.extend_from_slice(&[0x5F, 0x0F, 0x3C, 0xF5]);
        buf.extend_from_slice(&0x000Bu16.to_be_bytes());
        buf.extend_from_slice(&1000u16.to_be_bytes()); // unitsPerEm
        buf.extend_from_slice(&[0; 16]); // created + modified
        buf.extend_from_slice(&(-100i16).to_be_bytes());
        buf.extend_from_slice(&(-200i16).to_be_bytes());
        buf.extend_from_slice(&800i16.to_be_bytes());
        buf.extend_from_slice(&900i16.to_be_bytes());
        buf.extend_from_slice(&[0; 8]); // macStyle..glyphDataFormat
        let head_len = buf.len() - head_offset;

        // hhea table (36 bytes)
        let hhea_offset = buf.len();
        buf.extend_from_slice(&[0, 1, 0, 0]);
        buf.extend_from_slice(&800i16.to_be_bytes());
        buf.extend_from_slice(&(-200i16).to_be_bytes());
        buf.extend_from_slice(&[0; 24]); // remaining fields
        buf.extend_from_slice(&3u16.to_be_bytes()); // numOfLongHorMetrics
        let hhea_len = buf.len() - hhea_offset;

        // maxp table
        let maxp_offset = buf.len();
        buf.extend_from_slice(&[0, 0, 0x50, 0]);
        buf.extend_from_slice(&3u16.to_be_bytes());
        let maxp_len = buf.len() - maxp_offset;

        // hmtx table (3 glyphs)
        let hmtx_offset = buf.len();
        for w in [500u16, 250, 700] {
            buf.extend_from_slice(&w.to_be_bytes());
            buf.extend_from_slice(&0i16.to_be_bytes());
        }
        let hmtx_len = buf.len() - hmtx_offset;

        // cmap table (format 4): char 32->glyph 1, char 65->glyph 2
        let cmap_offset = buf.len();
        buf.extend_from_slice(&0u16.to_be_bytes());
        buf.extend_from_slice(&1u16.to_be_bytes());
        buf.extend_from_slice(&3u16.to_be_bytes());
        buf.extend_from_slice(&1u16.to_be_bytes());
        buf.extend_from_slice(&12u32.to_be_bytes());
        let subtable_start = buf.len();
        buf.extend_from_slice(&4u16.to_be_bytes());
        let len_pos = buf.len();
        buf.extend_from_slice(&0u16.to_be_bytes());
        buf.extend_from_slice(&0u16.to_be_bytes());
        buf.extend_from_slice(&6u16.to_be_bytes()); // segCountX2 = 3*2
        buf.extend_from_slice(&4u16.to_be_bytes());
        buf.extend_from_slice(&1u16.to_be_bytes());
        buf.extend_from_slice(&2u16.to_be_bytes());
        // endCode
        for v in [32u16, 65, 0xFFFF] {
            buf.extend_from_slice(&v.to_be_bytes());
        }
        buf.extend_from_slice(&0u16.to_be_bytes()); // reservedPad
        // startCode
        for v in [32u16, 65, 0xFFFF] {
            buf.extend_from_slice(&v.to_be_bytes());
        }
        // idDelta
        for v in [-31i16, -63, 1] {
            buf.extend_from_slice(&v.to_be_bytes());
        }
        // idRangeOffset
        for _ in 0..3 {
            buf.extend_from_slice(&0u16.to_be_bytes());
        }
        let subtable_len = (buf.len() - subtable_start) as u16;
        buf[len_pos] = (subtable_len >> 8) as u8;
        buf[len_pos + 1] = subtable_len as u8;
        let cmap_len = buf.len() - cmap_offset;

        // name table
        let name_offset = buf.len();
        buf.extend_from_slice(&0u16.to_be_bytes());
        buf.extend_from_slice(&1u16.to_be_bytes());
        buf.extend_from_slice(&18u16.to_be_bytes());
        let font_name_str = b"TestFont";
        buf.extend_from_slice(&1u16.to_be_bytes());
        buf.extend_from_slice(&0u16.to_be_bytes());
        buf.extend_from_slice(&0u16.to_be_bytes());
        buf.extend_from_slice(&1u16.to_be_bytes());
        buf.extend_from_slice(&(font_name_str.len() as u16).to_be_bytes());
        buf.extend_from_slice(&0u16.to_be_bytes());
        buf.extend_from_slice(font_name_str);
        let name_len = buf.len() - name_offset;

        // Fill in table directory
        let tables_info: [(&[u8; 4], usize, usize); 6] = [
            (b"head", head_offset, head_len),
            (b"hhea", hhea_offset, hhea_len),
            (b"maxp", maxp_offset, maxp_len),
            (b"hmtx", hmtx_offset, hmtx_len),
            (b"cmap", cmap_offset, cmap_len),
            (b"name", name_offset, name_len),
        ];
        for (i, (tag, offset, length)) in tables_info.iter().enumerate() {
            let dir_off = dir_start + i * 16;
            buf[dir_off..dir_off + 4].copy_from_slice(*tag);
            buf[dir_off + 4..dir_off + 8].copy_from_slice(&0u32.to_be_bytes());
            buf[dir_off + 8..dir_off + 12].copy_from_slice(&(*offset as u32).to_be_bytes());
            buf[dir_off + 12..dir_off + 16].copy_from_slice(&(*length as u32).to_be_bytes());
        }
        buf
    }

    #[test]
    fn add_font_embeds_truetype_in_pdf() {
        let ttf_data = build_integration_test_ttf();
        let pdf = HtmlConverter::new()
            .add_font("testfont", ttf_data)
            .convert(r#"<p style="font-family: testfont">Hello A</p>"#)
            .unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(
            content.contains("/Subtype /Type0"),
            "PDF should contain a Type0 custom font wrapper"
        );
        assert!(
            content.contains("/Subtype /CIDFontType2"),
            "PDF should contain a CIDFontType2 descendant font"
        );
        assert!(
            content.contains("/testfont "),
            "PDF should keep the custom font resource key"
        );
        assert!(
            content.contains("/BaseFont /TestFont") || content.contains("+TestFont"),
            "Custom fonts should preserve the embedded face name, with a subset tag when available"
        );
        assert!(
            content.contains("/FontDescriptor"),
            "PDF should contain FontDescriptor"
        );
        assert!(
            content.contains("/FontFile2"),
            "FontDescriptor should reference embedded font file"
        );
        assert!(
            content.contains("/Filter /FlateDecode"),
            "Embedded custom font streams should be compressed"
        );
        assert!(
            content.contains("/W [0 ["),
            "Descendant font should contain CID widths"
        );
        assert!(
            content.contains("/Encoding /Identity-H"),
            "Font should use Identity-H"
        );
        assert!(
            content.contains("/ToUnicode"),
            "Custom fonts should emit a ToUnicode CMap"
        );
    }

    #[test]
    fn add_font_uses_custom_font_in_content_stream() {
        let ttf_data = build_integration_test_ttf();
        let pdf = HtmlConverter::new()
            .add_font("testfont", ttf_data)
            .convert(r#"<p style="font-family: testfont">Hello</p>"#)
            .unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(
            content.contains("/testfont"),
            "Content stream should reference custom font"
        );
    }

    #[test]
    fn custom_font_falls_back_to_helvetica_when_not_registered() {
        let pdf = html_to_pdf(r#"<p style="font-family: 'UnknownFont'">Text</p>"#).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(
            content.contains("/Helvetica"),
            "Should fall back to Helvetica for unregistered custom font"
        );
    }

    #[test]
    fn missing_system_font_in_stack_falls_back_to_later_family() {
        let pdf = html_to_pdf(r#"<p style="font-family: MissingFont, serif">Text</p>"#).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(
            !content.contains("/missingfont"),
            "Missing primary families should not bind to an unrelated fallback as a custom font"
        );
        assert!(
            content.contains("/Times-Roman"),
            "Missing primary families should fall back to later CSS families"
        );
    }

    #[test]
    fn add_font_font_descriptor_has_metrics() {
        let ttf_data = build_integration_test_ttf();
        let pdf = HtmlConverter::new()
            .add_font("testfont", ttf_data)
            .convert(r#"<p style="font-family: testfont">A</p>"#)
            .unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(
            content.contains("/Ascent"),
            "FontDescriptor should have Ascent"
        );
        assert!(
            content.contains("/Descent"),
            "FontDescriptor should have Descent"
        );
        assert!(
            content.contains("/FontBBox"),
            "FontDescriptor should have FontBBox"
        );
        assert!(
            content.contains("/Flags"),
            "FontDescriptor should have Flags"
        );
    }

    #[test]
    fn add_font_standard_fonts_still_work() {
        let ttf_data = build_integration_test_ttf();
        let pdf = HtmlConverter::new()
            .add_font("testfont", ttf_data)
            .convert(
                r#"<p style="font-family: testfont">Custom</p>
                   <p style="font-family: serif">Serif</p>
                   <p>Default</p>"#,
            )
            .unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("/testfont"));
        assert!(content.contains("/Times-Roman"));
        assert!(content.contains("/Helvetica"));
    }

    #[test]
    fn add_font_multiple_custom_fonts() {
        let ttf1 = build_integration_test_ttf();
        let ttf2 = build_integration_test_ttf();
        let pdf = HtmlConverter::new()
            .add_font("fontone", ttf1)
            .add_font("fonttwo", ttf2)
            .convert(
                r#"<p style="font-family: fontone">First</p>
                   <p style="font-family: fonttwo">Second</p>"#,
            )
            .unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("/fontone"));
        assert!(content.contains("/fonttwo"));
    }

    #[test]
    fn add_font_case_insensitive_matching() {
        let ttf_data = build_integration_test_ttf();
        let pdf = HtmlConverter::new()
            .add_font("MyFont", ttf_data)
            .convert(r#"<p style="font-family: MyFont">Text</p>"#)
            .unwrap();
        let content = String::from_utf8_lossy(&pdf);
        // Font name is lowercased internally
        assert!(content.contains("/myfont") || content.contains("/MyFont"));
    }

    #[test]
    fn add_font_in_table_cell() {
        let ttf_data = build_integration_test_ttf();
        let pdf = HtmlConverter::new()
            .add_font("testfont", ttf_data)
            .convert(r#"<table><tr><td style="font-family: testfont">Cell</td></tr></table>"#)
            .unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("/testfont"));
    }

    #[test]
    fn add_font_with_bold_text() {
        let ttf_data = build_integration_test_ttf();
        let pdf = HtmlConverter::new()
            .add_font("testfont", ttf_data)
            .convert(r#"<p style="font-family: testfont"><b>Bold custom</b></p>"#)
            .unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn add_font_with_italic_text() {
        let ttf_data = build_integration_test_ttf();
        let pdf = HtmlConverter::new()
            .add_font("testfont", ttf_data)
            .convert(r#"<p style="font-family: testfont"><i>Italic custom</i></p>"#)
            .unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn add_font_empty_text_no_crash() {
        let ttf_data = build_integration_test_ttf();
        let pdf = HtmlConverter::new()
            .add_font("testfont", ttf_data)
            .convert(r#"<p style="font-family: testfont"></p>"#)
            .unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn add_font_with_inline_style_inheritance() {
        let ttf_data = build_integration_test_ttf();
        let pdf = HtmlConverter::new()
            .add_font("testfont", ttf_data)
            .convert(
                r#"<div style="font-family: testfont"><p>Inherited</p><p>Also inherited</p></div>"#,
            )
            .unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("/testfont"));
    }

    #[test]
    fn add_font_with_stylesheet() {
        let ttf_data = build_integration_test_ttf();
        let pdf = HtmlConverter::new()
            .add_font("testfont", ttf_data)
            .convert(
                r#"<html><head><style>.custom { font-family: testfont; }</style></head>
                   <body><p class="custom">Styled</p></body></html>"#,
            )
            .unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("/testfont"));
    }

    #[test]
    fn add_font_invalid_ttf_data_gracefully_degrades() {
        let pdf = HtmlConverter::new()
            .add_font("badfont", vec![0, 1, 2, 3])
            .convert(r#"<p style="font-family: badfont">Text</p>"#)
            .unwrap();
        let content = String::from_utf8_lossy(&pdf);
        // Should fall back to Helvetica since the font couldn't be parsed
        assert!(content.contains("/Helvetica"));
    }

    #[test]
    fn add_font_preserves_page_size_and_margin() {
        let ttf_data = build_integration_test_ttf();
        let pdf = HtmlConverter::new()
            .page_size(PageSize {
                width: 612.0,
                height: 792.0,
            })
            .margin(Margin::uniform(36.0))
            .add_font("testfont", ttf_data)
            .convert(r#"<p style="font-family: testfont">Custom</p>"#)
            .unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn custom_font_in_list_item() {
        let ttf_data = build_integration_test_ttf();
        let pdf = HtmlConverter::new()
            .add_font("testfont", ttf_data)
            .convert(r#"<ul style="font-family: testfont"><li>Item 1</li><li>Item 2</li></ul>"#)
            .unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn custom_font_in_nested_elements() {
        let ttf_data = build_integration_test_ttf();
        let pdf = HtmlConverter::new()
            .add_font("testfont", ttf_data)
            .convert(
                r#"<div style="font-family: testfont"><p><span>Nested <b>bold</b></span></p></div>"#,
            )
            .unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn custom_font_with_long_text_wrapping() {
        let ttf_data = build_integration_test_ttf();
        let long_text = "A ".repeat(500);
        let html = format!(r#"<p style="font-family: testfont">{long_text}</p>"#,);
        let pdf = HtmlConverter::new()
            .add_font("testfont", ttf_data)
            .convert(&html)
            .unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn custom_font_mixed_with_standard_in_same_paragraph() {
        let ttf_data = build_integration_test_ttf();
        let pdf = HtmlConverter::new()
            .add_font("testfont", ttf_data)
            .convert(
                r#"<p><span style="font-family: testfont">Custom</span> and <span style="font-family: serif">Serif</span></p>"#,
            )
            .unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("/testfont"));
        assert!(content.contains("/Times-Roman"));
    }

    #[test]
    fn custom_font_with_opacity() {
        let ttf_data = build_integration_test_ttf();
        let pdf = HtmlConverter::new()
            .add_font("testfont", ttf_data)
            .convert(r#"<p style="font-family: testfont; opacity: 0.5">Transparent custom</p>"#)
            .unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn custom_font_with_width_and_background() {
        let ttf_data = build_integration_test_ttf();
        let pdf = HtmlConverter::new()
            .add_font("testfont", ttf_data)
            .convert(
                r#"<div style="font-family: testfont; width: 200px; background-color: yellow">Boxed custom</div>"#,
            )
            .unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn custom_font_markdown_conversion() {
        let ttf_data = build_integration_test_ttf();
        let pdf = HtmlConverter::new()
            .add_font("testfont", ttf_data)
            .convert_markdown("# Hello World\n\nSome text here.")
            .unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn linear_gradient_produces_pdf() {
        let html = r#"<div style="background: linear-gradient(to right, red, blue); height: 50pt; width: 200pt">Gradient</div>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
        let content = String::from_utf8_lossy(&pdf);
        // Should contain colored rectangles (gradient strips)
        assert!(content.contains("rg"));
    }

    #[test]
    fn radial_gradient_produces_pdf() {
        let html = r#"<div style="background: radial-gradient(red, blue); height: 100pt; width: 100pt">Radial</div>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn page_rule_changes_page_size() {
        let html = r#"<style>@page { size: letter; }</style><p>Hello</p>"#;
        let pdf = HtmlConverter::new().convert(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
        let content = String::from_utf8_lossy(&pdf);
        // Letter size is 612x792, should appear in MediaBox
        assert!(content.contains("612"));
        assert!(content.contains("792"));
    }

    #[test]
    fn page_rule_changes_margins() {
        let html = r#"<style>@page { margin: 0.5in; }</style><p>Hello</p>"#;
        let pdf = HtmlConverter::new().convert(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn page_rule_a4_landscape() {
        let html = r#"<style>@page { size: a4 landscape; }</style><p>Hello</p>"#;
        let pdf = HtmlConverter::new().convert(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
        let content = String::from_utf8_lossy(&pdf);
        // Landscape A4: 841.89 x 595.28
        assert!(content.contains("841.89"));
        assert!(content.contains("595.28"));
    }

    #[test]
    fn linear_gradient_with_multiple_stops() {
        let html = r#"<div style="background: linear-gradient(to right, red 0%, white 50%, blue 100%); height: 50pt; width: 200pt">Multi-stop</div>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn gradient_via_background_image_property() {
        let html = r#"<div style="background-image: linear-gradient(45deg, #ff0000, #0000ff); height: 50pt; width: 200pt">Angled</div>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn svg_background_image_from_data_uri() {
        let html = r#"<html><head><style>
body { background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='100' height='100'%3E%3Crect width='100' height='100' fill='%23eee'/%3E%3Ccircle cx='50' cy='50' r='30' fill='%23ccc'/%3E%3C/svg%3E"); background-size: cover; }
</style></head><body>
<h1>Background Test</h1>
<p>This page should have an SVG pattern background.</p>
</body></html>"#;
        let pdf = HtmlConverter::new().sanitize(false).convert(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("Background Test"));
    }

    #[test]
    fn svg_background_image_base64() {
        let html = r#"<html><head><style>
body { background: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHdpZHRoPSc1MCcgaGVpZ2h0PSc1MCc+PHJlY3Qgd2lkdGg9JzUwJyBoZWlnaHQ9JzUwJyBmaWxsPSdibHVlJy8+PC9zdmc+"); }
</style></head><body><p>Base64 SVG BG</p></body></html>"#;
        let pdf = HtmlConverter::new().sanitize(false).convert(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn html_to_pdf_border_radius() {
        let html = r#"<div style="border: 1px solid black; border-radius: 10pt; background-color: yellow; padding: 10pt">Rounded corners</div>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
        let content = String::from_utf8_lossy(&pdf);
        // Rounded rect uses Bezier curves (c operator)
        assert!(content.contains(" c\n"));
    }

    #[test]
    fn html_to_pdf_outline() {
        let html = r#"<div style="outline: 3px solid blue; width: 200pt">With outline</div>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
        let content = String::from_utf8_lossy(&pdf);
        // Outline draws a stroke
        assert!(content.contains("S\n"));
    }

    #[test]
    fn html_to_pdf_box_sizing_border_box() {
        let html = r#"<div style="box-sizing: border-box; width: 200pt; padding: 20pt; border: 2px solid black; background-color: green">Border box</div>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn html_to_pdf_combined_features() {
        let html = r#"<div style="border: 2px solid black; border-radius: 15pt; outline: 3px solid red; box-sizing: border-box; width: 300pt; padding: 20pt; background-color: #eee">All features combined</div>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains(" c\n")); // Bezier curves from border-radius
    }

    // --- Coverage tests for pdf.rs and engine.rs uncovered lines ---

    #[test]
    fn pdf_float_right_positions_block() {
        // Covers pdf.rs line 119: Float::Right block_x calculation
        let html = r#"<p style="float: right; width: 100pt">FloatRight</p>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("FloatRight"));
    }

    #[test]
    fn pdf_visibility_hidden_skips_rendering() {
        // Covers pdf.rs line 110: visibility hidden skips rendering
        let html = r#"<p style="visibility: hidden">HiddenStuff</p><p>VisibleStuff</p>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("VisibleStuff"));
        assert!(!content.contains("(HiddenStuff)"));
    }

    #[test]
    fn pdf_overflow_hidden_clips_content() {
        // Covers pdf.rs lines 155-172: clip_rect with overflow: hidden
        let html = r#"<p style="overflow: hidden; width: 100pt; height: 50pt">ClippedHere</p>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("W n\n"));
    }

    #[test]
    fn pdf_overflow_hidden_with_border_radius() {
        // Covers pdf.rs lines 161-169: clip_rect with border-radius uses rounded path + W n
        let html = r#"<p style="overflow: hidden; border-radius: 10pt; width: 100pt; height: 50pt">RoundedClip</p>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("W n\n"));
        assert!(content.contains(" c\n"));
    }

    #[test]
    fn pdf_opacity_sets_ext_gstate() {
        // Covers pdf.rs lines 176-181: opacity < 1.0 creates ExtGState
        let html = r#"<p style="opacity: 0.5">Translucent</p>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("gs\n"));
    }

    #[test]
    fn pdf_box_shadow_renders_rect() {
        // Covers pdf.rs lines 184-213: box-shadow rendering
        let html =
            r#"<p style="box-shadow: 5pt 5pt black; width: 100pt; padding: 10pt">ShadowBox</p>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("f\n"));
    }

    #[test]
    fn pdf_box_shadow_with_explicit_height() {
        // Covers pdf.rs line 188: box-shadow with block_height Some(h) path
        let html = r#"<p style="box-shadow: 3pt 3pt black; width: 100pt; height: 80pt; padding: 10pt">ShadowH</p>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("f\n"));
    }

    #[test]
    fn pdf_box_shadow_with_border_radius() {
        // Covers pdf.rs lines 195-202: box-shadow with border-radius uses rounded rect
        let html = r#"<p style="box-shadow: 3pt 3pt black; border-radius: 10pt; width: 100pt; padding: 10pt">RoundShadow</p>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains(" c\n"));
        assert!(content.contains("f\n"));
    }

    #[test]
    fn pdf_background_with_explicit_height() {
        // Covers pdf.rs line 220: background_color with block_height Some(h) path
        let html =
            r#"<p style="background-color: #ff0000; width: 100pt; height: 80pt">BGHeight</p>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("1 0 0 rg"));
        assert!(content.contains("f\n"));
    }

    #[test]
    fn pdf_linear_gradient_renders_strips() {
        // Linear gradient uses native PDF shading dictionaries
        let html = r#"<p style="background: linear-gradient(to right, red, blue); width: 200pt; height: 50pt; padding: 10pt">Gradient</p>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("sh\n"));
        assert!(content.contains("/ShadingType 2"));
    }

    #[test]
    fn pdf_linear_gradient_vertical() {
        // Vertical gradient (to bottom) uses shading dictionary
        let html = r#"<p style="background: linear-gradient(to bottom, red, blue); width: 200pt; height: 50pt; padding: 10pt">VertGrad</p>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("sh\n"));
        assert!(content.contains("/ShadingType 2"));
    }

    #[test]
    fn pdf_linear_gradient_with_block_height() {
        // Gradient with block_height uses shading dictionary
        let html = r#"<p style="background: linear-gradient(to right, red, blue); width: 200pt; height: 100pt; padding: 10pt">GradHeight</p>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("sh\n"));
        assert!(content.contains("/ShadingType 2"));
    }

    #[test]
    fn pdf_linear_gradient_diagonal() {
        // Diagonal gradient uses shading dictionary
        let html = r#"<p style="background: linear-gradient(45deg, red, blue); width: 200pt; height: 50pt; padding: 10pt">DiagGrad</p>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("sh\n"));
        assert!(content.contains("/ShadingType 2"));
    }

    #[test]
    fn pdf_radial_gradient_renders_circles() {
        // Radial gradient uses native PDF shading dictionary (Type 3)
        let html = r#"<p style="background: radial-gradient(red, blue); width: 200pt; height: 100pt; padding: 10pt">Radial</p>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("sh\n"));
        assert!(content.contains("/ShadingType 3"));
    }

    #[test]
    fn pdf_radial_gradient_with_block_height() {
        // Radial gradient with block_height uses shading dictionary
        let html = r#"<p style="background: radial-gradient(red, blue); width: 200pt; height: 120pt; padding: 10pt">RadialH</p>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("sh\n"));
        assert!(content.contains("/ShadingType 3"));
    }

    #[test]
    fn pdf_border_with_block_height() {
        // Covers pdf.rs line 288: border with block_height Some(h) path
        let html = r#"<p style="border: 2pt solid black; width: 100pt; height: 80pt">BorderH</p>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("RG\n"));
        assert!(content.contains("S\n"));
    }

    #[test]
    fn pdf_outline_with_block_height() {
        // Covers pdf.rs line 320: outline with block_height Some(h) path
        let html = r#"<p style="outline: 3pt solid red; width: 100pt; height: 80pt">OutlineH</p>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("RG\n"));
        assert!(content.contains("S\n"));
    }

    #[test]
    fn pdf_transform_rotate() {
        // Covers pdf.rs lines 132-152: transform rendering
        let html = r#"<p style="transform: rotate(45deg)">Rotated</p>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("cm\n"));
        assert!(content.contains("q\n"));
        assert!(content.contains("Q\n"));
    }

    #[test]
    fn pdf_transform_scale() {
        // Covers pdf.rs line 147: scale transform
        let html = r#"<p style="transform: scale(2)">Scaled</p>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("cm\n"));
    }

    #[test]
    fn pdf_transform_translate() {
        // Covers pdf.rs lines 149-150: translate transform
        let html = r#"<p style="transform: translate(10pt, 20pt)">Translated</p>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("1 0 0 1"));
        assert!(content.contains("cm\n"));
    }

    #[test]
    fn pdf_text_justify_alignment() {
        // Covers pdf.rs lines 363-374: text-align: justify with word spacing
        let html = r#"<p style="text-align: justify; width: 200pt">This is a long sentence with many words that should be justified across the width of the container for proper testing purposes here.</p>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("Tw\n"));
    }

    #[test]
    fn pdf_page_break_element() {
        // Covers pdf.rs line 616: PageBreak element
        // Also covers engine.rs line 602: page-break-after
        let html = r#"<p style="page-break-after: always">PageOne</p><p>PageTwo</p>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("PageOne"));
        assert!(content.contains("PageTwo"));
    }

    #[test]
    fn pdf_grid_row_renders_cells() {
        // Covers pdf.rs lines 535-573: GridRow rendering
        // Covers engine.rs lines 607-622: grid container handling
        let html = r#"<html><body>
            <div style="display: grid; grid-template-columns: 1fr 1fr">
                <div>CellAlpha</div>
                <div>CellBeta</div>
            </div>
        </body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("CellAlpha"));
        assert!(content.contains("CellBeta"));
    }

    #[test]
    fn pdf_grid_row_with_background() {
        // Covers pdf.rs lines 550-557: grid cell background rendering
        let html = r#"<html><body>
            <div style="display: grid; grid-template-columns: 1fr 1fr">
                <div style="background-color: red">RedCell</div>
                <div style="background-color: blue">BlueCell</div>
            </div>
        </body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("rg\n"));
        assert!(content.contains("re\nf\n"));
    }

    #[test]
    fn pdf_grid_with_three_columns() {
        // Covers pdf.rs line 546: fallback col_widths for extra cells
        let html = r#"<html><body>
            <div style="display: grid; grid-template-columns: 1fr 1fr 1fr">
                <div>A</div><div>B</div><div>C</div><div>D</div>
            </div>
        </body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn pdf_grid_with_page_break_after() {
        // Covers engine.rs lines 619-620: page_break_after for grid container
        let html = r#"<html><body>
            <div style="display: grid; grid-template-columns: 1fr; page-break-after: always">
                <div>GridPageOne</div>
            </div>
            <p>AfterGrid</p>
        </body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("GridPageOne"));
        assert!(content.contains("AfterGrid"));
    }

    #[test]
    fn engine_flex_container_with_background() {
        // Covers engine.rs lines 1059-1097: flex container bg/border/shadow emit
        let html = r#"<html><body>
            <div style="display: flex; background-color: #eee; border: 1pt solid black; padding: 10pt">
                <div style="width: 100pt">FlexChild</div>
            </div>
        </body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("FlexChild"));
    }

    #[test]
    fn engine_flex_wrap_wraps_items() {
        // Covers engine.rs lines 979-989: flex-wrap: wrap wrapping behavior
        let html = r#"<html><body>
            <div style="display: flex; flex-wrap: wrap; width: 200pt">
                <div style="width: 120pt">ItemOne</div>
                <div style="width: 120pt">ItemTwo</div>
            </div>
        </body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("ItemOne"));
        assert!(content.contains("ItemTwo"));
    }

    #[test]
    fn engine_flex_justify_space_between() {
        // Covers engine.rs lines 1122-1127: justify-content: space-between
        let html = r#"<html><body>
            <div style="display: flex; justify-content: space-between; width: 300pt">
                <div style="width: 50pt">LeftSide</div>
                <div style="width: 50pt">RightSide</div>
            </div>
        </body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("LeftSide"));
        assert!(content.contains("RightSide"));
    }

    #[test]
    fn engine_flex_justify_space_between_single() {
        // Covers engine.rs line 1126: space-between with single item (0 gap)
        let html = r#"<html><body>
            <div style="display: flex; justify-content: space-between; width: 300pt">
                <div style="width: 50pt">OnlyItem</div>
            </div>
        </body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("OnlyItem"));
    }

    #[test]
    fn engine_flex_justify_space_around() {
        // Covers engine.rs lines 1129-1132: justify-content: space-around
        let html = r#"<html><body>
            <div style="display: flex; justify-content: space-around; width: 300pt">
                <div style="width: 50pt">ItemX</div>
                <div style="width: 50pt">ItemY</div>
            </div>
        </body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("ItemX"));
        assert!(content.contains("ItemY"));
    }

    #[test]
    fn engine_flex_justify_center() {
        // Covers engine.rs line 1121: justify-content: center
        let html = r#"<html><body>
            <div style="display: flex; justify-content: center; width: 300pt">
                <div style="width: 50pt">CenteredItem</div>
            </div>
        </body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("CenteredItem"));
    }

    #[test]
    fn engine_flex_justify_flex_end() {
        // Covers engine.rs line 1120: justify-content: flex-end
        let html = r#"<html><body>
            <div style="display: flex; justify-content: flex-end; width: 300pt">
                <div style="width: 50pt">EndItem</div>
            </div>
        </body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("EndItem"));
    }

    #[test]
    fn engine_flex_align_items_center() {
        // Covers engine.rs line 1144: align-items: center
        let html = r#"<html><body>
            <div style="display: flex; align-items: center; width: 300pt">
                <div style="width: 100pt">TallItem</div>
                <div style="width: 100pt">ShortItem</div>
            </div>
        </body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("TallItem"));
        assert!(content.contains("ShortItem"));
    }

    #[test]
    fn engine_flex_align_items_flex_end() {
        // Covers engine.rs line 1143: align-items: flex-end
        let html = r#"<html><body>
            <div style="display: flex; align-items: flex-end; width: 300pt">
                <div style="width: 100pt">BottomItem</div>
                <div style="width: 100pt">AlsoBottom</div>
            </div>
        </body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("BottomItem"));
        assert!(content.contains("AlsoBottom"));
    }

    #[test]
    fn engine_flex_direction_column() {
        // Covers engine.rs lines 1002-1021, 1230-1335: flex-direction: column
        let html = r#"<html><body>
            <div style="display: flex; flex-direction: column; width: 200pt">
                <div style="width: 100pt">RowAlpha</div>
                <div style="width: 100pt">RowBeta</div>
            </div>
        </body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("RowAlpha"));
        assert!(content.contains("RowBeta"));
    }

    #[test]
    fn engine_flex_column_align_center() {
        // Covers engine.rs lines 1247-1249: column flex align-items: center (x_offset)
        let html = r#"<html><body>
            <div style="display: flex; flex-direction: column; align-items: center; width: 300pt">
                <div style="width: 100pt">ColCenter</div>
            </div>
        </body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("ColCenter"));
    }

    #[test]
    fn engine_flex_column_align_flex_end() {
        // Covers engine.rs lines 1248: column flex align-items: flex-end
        let html = r#"<html><body>
            <div style="display: flex; flex-direction: column; align-items: flex-end; width: 300pt">
                <div style="width: 100pt">ColEnd</div>
            </div>
        </body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("ColEnd"));
    }

    #[test]
    fn engine_flex_container_with_margin() {
        // Covers engine.rs lines 1342-1378: flex trailing margin
        let html = r#"<html><body>
            <div style="display: flex; margin: 20pt; background-color: #ccc; width: 200pt">
                <div style="width: 100pt">MarginedFlex</div>
            </div>
            <p>AfterFlex</p>
        </body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("MarginedFlex"));
        assert!(content.contains("AfterFlex"));
    }

    #[test]
    fn engine_flex_with_overflow_hidden() {
        // Covers engine.rs lines 1082-1085: overflow: hidden in flex container
        let html = r#"<html><body>
            <div style="display: flex; overflow: hidden; width: 200pt; background-color: #eee">
                <div style="width: 100pt">ClippedFlex</div>
            </div>
        </body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("ClippedFlex"));
    }

    #[test]
    fn engine_flex_with_transform() {
        // Covers engine.rs line 1087: transform in flex container
        let html = r#"<html><body>
            <div style="display: flex; transform: rotate(5deg); background-color: #eee; width: 200pt">
                <div style="width: 100pt">TransFlex</div>
            </div>
        </body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("TransFlex"));
    }

    #[test]
    fn engine_flex_with_box_shadow() {
        // Covers engine.rs lines 1059, 1080: box-shadow in flex container
        let html = r#"<html><body>
            <div style="display: flex; box-shadow: 3pt 3pt black; width: 200pt">
                <div style="width: 100pt">ShadowFlex</div>
            </div>
        </body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("ShadowFlex"));
    }

    #[test]
    fn engine_flex_height_constrains_container() {
        // Covers engine.rs line 1049: flex height with Some(h) path
        let html = r#"<html><body>
            <div style="display: flex; height: 200pt; background-color: #eee; width: 300pt">
                <div style="width: 100pt">TallFlexContent</div>
            </div>
        </body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("TallFlexContent"));
    }

    #[test]
    fn engine_flex_child_box_sizing_border_box() {
        // Covers engine.rs lines 865-869: box-sizing: border-box in flex child
        let html = r#"<html><body>
            <div style="display: flex; width: 300pt">
                <div style="width: 150pt; box-sizing: border-box; padding: 10pt; border: 2pt solid black">BorderBoxChild</div>
            </div>
        </body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("BorderBoxChild"));
    }

    #[test]
    fn engine_flex_with_max_width() {
        // Covers engine.rs lines 800, 803: flex container width/max-width
        let html = r#"<html><body>
            <div style="display: flex; width: 300pt; max-width: 250pt; background-color: #eee">
                <div style="width: 100pt">MaxWidthFlex</div>
            </div>
        </body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("MaxWidthFlex"));
    }

    #[test]
    fn engine_flex_child_display_none() {
        // Covers engine.rs line 856: child with display: none is skipped
        let html = r#"<html><body>
            <div style="display: flex; width: 300pt">
                <div style="display: none; width: 100pt">HiddenFlex</div>
                <div style="width: 100pt">VisibleFlex</div>
            </div>
        </body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(!content.contains("(HiddenFlex)"));
        assert!(content.contains("VisibleFlex"));
    }

    #[test]
    fn engine_flex_page_break_after() {
        // Covers engine.rs lines 601-602: page-break-after for flex container
        let html = r#"<html><body>
            <div style="display: flex; page-break-after: always">
                <div style="width: 100pt">FlexPageOne</div>
            </div>
            <p>FlexPageTwo</p>
        </body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("FlexPageOne"));
        assert!(content.contains("FlexPageTwo"));
    }

    #[test]
    fn engine_grid_with_gap() {
        // Covers engine.rs line 1390: grid column gap
        let html = r#"<html><body>
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10pt">
                <div>GridAlpha</div>
                <div>GridBeta</div>
            </div>
        </body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("GridAlpha"));
        assert!(content.contains("GridBeta"));
    }

    #[test]
    fn engine_grid_fixed_columns() {
        // Covers engine.rs line 1414: fixed + fr grid tracks
        let html = r#"<html><body>
            <div style="display: grid; grid-template-columns: 100pt 1fr">
                <div>FixedCol</div>
                <div>FlexCol</div>
            </div>
        </body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("FixedCol"));
        assert!(content.contains("FlexCol"));
    }

    #[test]
    fn engine_table_with_colspan() {
        // Covers engine.rs line 1602: colspan counting in table
        let html = r#"
            <table>
                <tr><td colspan="2">Spanning</td></tr>
                <tr><td>CellA</td><td>CellB</td></tr>
            </table>
        "#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("Spanning"));
        assert!(content.contains("CellA"));
        assert!(content.contains("CellB"));
    }

    #[test]
    fn engine_table_with_rowspan() {
        // Covers pdf.rs lines 490-504, engine.rs rowspan handling
        let html = r#"
            <table>
                <tr><td rowspan="2">TallCell</td><td>TopCell</td></tr>
                <tr><td>BottomCell</td></tr>
            </table>
        "#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("TallCell"));
        assert!(content.contains("TopCell"));
        assert!(content.contains("BottomCell"));
    }

    #[test]
    fn engine_table_with_thead_tbody_tfoot_coverage() {
        // Covers engine.rs lines 1565, 1575: table section traversal
        let html = r#"
            <table>
                <thead><tr><th>HeadCol</th></tr></thead>
                <tbody><tr><td>BodyRow</td></tr></tbody>
                <tfoot><tr><td>FootRow</td></tr></tfoot>
            </table>
        "#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("HeadCol"));
        assert!(content.contains("BodyRow"));
        assert!(content.contains("FootRow"));
    }

    #[test]
    fn engine_table_non_tr_children_ignored() {
        // Covers engine.rs line 1575: non-tr/thead/tbody/tfoot children
        let html = r#"
            <table>
                <tr><td>ValidCell</td></tr>
            </table>
        "#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("ValidCell"));
    }

    #[test]
    fn engine_table_non_td_children_in_row() {
        // Covers engine.rs line 1687: non-td/th elements in a row are skipped
        let html = r#"
            <table>
                <tr><td>GoodCell</td></tr>
            </table>
        "#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("GoodCell"));
    }

    #[test]
    fn engine_ordered_list_indent() {
        // Covers engine.rs lines 486, 491: ordered list indent
        let html = r#"<ol><li>First</li><li>Second</li></ol>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("1."));
        assert!(content.contains("2."));
    }

    #[test]
    fn engine_clear_right() {
        // Covers engine.rs lines 2003-2006: clear: right
        let html = r#"<p style="float: right; width: 100pt">FloatedRight</p><p style="clear: right">ClearedRight</p>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("FloatedRight"));
        assert!(content.contains("ClearedRight"));
    }

    #[test]
    fn engine_clear_both() {
        // Covers engine.rs lines 1995-2001: clear: both
        let html = r#"<p style="float: left; width: 100pt">FloatLeft</p><p style="float: right; width: 100pt">FloatRight</p><p style="clear: both">ClearedBoth</p>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("FloatLeft"));
        assert!(content.contains("FloatRight"));
        assert!(content.contains("ClearedBoth"));
    }

    #[test]
    fn engine_image_with_only_width_attr() {
        // Covers engine.rs line 2173: image with width only (falls back to square)
        let html = r#"<img width="100" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==">"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("Do\n"));
    }

    #[test]
    fn engine_image_with_only_height_attr() {
        // Covers engine.rs line 2174: image with height only
        let html = r#"<img height="80" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==">"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("Do\n"));
    }

    #[test]
    fn engine_image_unsupported_format_ignored() {
        // Covers engine.rs line 2225: non-PNG, non-JPEG data returns None
        let html = r#"<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7">"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn engine_image_remote_url_blocked() {
        // Covers engine.rs lines 2204-2206: remote URLs are blocked
        let html = r#"<img src="https://example.com/image.png">"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn engine_image_local_file_not_found() {
        // Covers engine.rs line 2209: local file path that doesn't exist
        let html = r#"<img src="/nonexistent/path/to/image.png">"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn pdf_linear_gradient_to_left() {
        // Reversed horizontal gradient uses shading dictionary
        let html = r#"<p style="background: linear-gradient(to left, red, blue); width: 200pt; height: 50pt; padding: 10pt">ToLeft</p>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("sh\n"));
        assert!(content.contains("/ShadingType 2"));
    }

    #[test]
    fn pdf_linear_gradient_to_top_vertical() {
        // Vertical gradient to top uses shading dictionary
        let html = r#"<p style="background: linear-gradient(to top, red, blue); width: 200pt; height: 50pt; padding: 10pt">ToTop</p>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("sh\n"));
        assert!(content.contains("/ShadingType 2"));
    }

    #[test]
    fn pdf_gradient_three_stops() {
        // Three-stop gradient uses stitching function (Type 3)
        let html = r#"<p style="background: linear-gradient(to right, red 0%, white 50%, blue 100%); width: 200pt; height: 50pt; padding: 10pt">ThreeStops</p>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("sh\n"));
        assert!(content.contains("/FunctionType 3"));
    }

    #[test]
    fn engine_flex_column_non_stretch_width() {
        // Covers engine.rs line 1256: non-stretch width in column flex
        let html = r#"<html><body>
            <div style="display: flex; flex-direction: column; align-items: flex-start; width: 300pt">
                <div style="width: 100pt">NarrowChild</div>
            </div>
        </body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("NarrowChild"));
    }

    #[test]
    fn engine_flex_column_with_position_relative() {
        // Covers engine.rs line 1311: column flex with x_offset > 0 sets Position::Relative
        let html = r#"<html><body>
            <div style="display: flex; flex-direction: column; align-items: center; width: 300pt">
                <div style="width: 100pt">ColCentered</div>
            </div>
        </body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("ColCentered"));
    }

    #[test]
    fn engine_flex_with_gap() {
        // Covers engine.rs lines 976, 992, 1012: gap in flex layout
        let html = r#"<html><body>
            <div style="display: flex; gap: 10pt; width: 300pt">
                <div style="width: 80pt">GapA</div>
                <div style="width: 80pt">GapB</div>
                <div style="width: 80pt">GapC</div>
            </div>
        </body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("GapA"));
        assert!(content.contains("GapB"));
        assert!(content.contains("GapC"));
    }

    #[test]
    fn engine_grid_incomplete_row_fills_empty_cells() {
        // Covers engine.rs lines 1517-1529: incomplete grid row fills with empty cells
        let html = r#"<html><body>
            <div style="display: grid; grid-template-columns: 1fr 1fr 1fr">
                <div>OnlyOne</div>
            </div>
        </body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("OnlyOne"));
    }

    #[test]
    fn engine_table_cell_background() {
        // Covers pdf.rs lines 510-518: table cell background rendering
        let html = r#"
            <table>
                <tr><td style="background-color: yellow">YellowCell</td><td>PlainCell</td></tr>
            </table>
        "#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("YellowCell"));
        assert!(content.contains("rg\n"));
    }

    #[test]
    fn engine_flex_empty_children_skipped() {
        // Covers engine.rs line 943-944: items.is_empty() check
        let html = r#"<html><body>
            <div style="display: flex; width: 200pt">
                <div style="display: none">HiddenOne</div>
                <div style="display: none">HiddenTwo</div>
            </div>
        </body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn engine_flex_no_children() {
        // Covers engine.rs line 822-823: flex with no element children
        let html = r#"<html><body><div style="display: flex; width: 200pt"></div></body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn engine_grid_text_nodes_filtered() {
        // Covers engine.rs line 1456: text nodes are filtered in grid
        let html = r#"<html><body>
            <div style="display: grid; grid-template-columns: 1fr 1fr">
                <div>GridChild</div>
                <div>AnotherChild</div>
            </div>
        </body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("GridChild"));
        assert!(content.contains("AnotherChild"));
    }

    #[test]
    fn font_face_rules_parsed_from_stylesheet() {
        // @font-face rules should be extracted from embedded stylesheets
        let html = r#"<html><head><style>
            @font-face {
                font-family: "TestFont";
                src: url("test.ttf");
            }
            body { color: black; }
        </style></head><body><p>Hello</p></body></html>"#;
        // Even without base_path, the conversion should succeed
        // (font file won't be found, but no error)
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn import_rules_ignored_without_base_path() {
        // @import rules should be ignored when no base_path is set
        let html = r#"<html><head><style>
            @import "nonexistent.css";
            body { color: red; }
        </style></head><body><p>Hello</p></body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn base_path_setter() {
        use std::path::Path;
        let converter = HtmlConverter::new().base_path(Path::new("/tmp/test"));
        // Verify base_path is set
        assert_eq!(converter.base_path.as_deref(), Some(Path::new("/tmp/test")));
    }

    #[test]
    fn font_face_remote_url_rejected() {
        // Remote URLs in @font-face should be silently ignored
        let html = r#"<html><head><style>
            @font-face {
                font-family: "RemoteFont";
                src: url("https://example.com/font.ttf");
            }
        </style></head><body><p>Hello</p></body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn import_with_base_path_missing_file() {
        use std::path::Path;
        // When file doesn't exist, @import is silently skipped
        let html = r#"<html><head><style>
            @import "nonexistent.css";
            p { color: blue; }
        </style></head><body><p>Styled</p></body></html>"#;
        let pdf = HtmlConverter::new()
            .base_path(Path::new("/tmp/ironpress_test_nonexistent"))
            .convert(html)
            .unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn import_with_real_file() {
        // Create a temporary directory with a CSS file
        let tmp_dir = std::env::temp_dir().join("ironpress_import_test");
        let _ = std::fs::create_dir_all(&tmp_dir);
        std::fs::write(tmp_dir.join("imported.css"), "p { color: red; }").unwrap();

        let html = r#"<html><head><style>
            @import "imported.css";
        </style></head><body><p>Hello</p></body></html>"#;

        let pdf = HtmlConverter::new()
            .base_path(&tmp_dir)
            .convert(html)
            .unwrap();
        assert!(pdf.starts_with(b"%PDF"));

        // Cleanup
        let _ = std::fs::remove_dir_all(&tmp_dir);
    }

    #[test]
    fn import_recursive_with_depth_limit() {
        // Create files that import each other (circular)
        let tmp_dir = std::env::temp_dir().join("ironpress_recursive_test");
        let _ = std::fs::create_dir_all(&tmp_dir);
        std::fs::write(
            tmp_dir.join("a.css"),
            r#"@import "b.css"; .a { color: red; }"#,
        )
        .unwrap();
        std::fs::write(
            tmp_dir.join("b.css"),
            r#"@import "a.css"; .b { color: blue; }"#,
        )
        .unwrap();

        let html = r#"<html><head><style>
            @import "a.css";
        </style></head><body><p>Hello</p></body></html>"#;

        // Should not infinite loop due to depth limit
        let pdf = HtmlConverter::new()
            .base_path(&tmp_dir)
            .convert(html)
            .unwrap();
        assert!(pdf.starts_with(b"%PDF"));

        // Cleanup
        let _ = std::fs::remove_dir_all(&tmp_dir);
    }

    #[test]
    fn font_face_with_base_path_missing_font() {
        use std::path::Path;
        // When font file doesn't exist, it's silently skipped
        let html = r#"<html><head><style>
            @font-face {
                font-family: "MissingFont";
                src: url("missing.ttf");
            }
            p { font-family: MissingFont; }
        </style></head><body><p>Hello</p></body></html>"#;

        let pdf = HtmlConverter::new()
            .base_path(Path::new("/tmp/ironpress_test_nonexistent"))
            .convert(html)
            .unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn import_remote_url_rejected() {
        use std::path::Path;
        // Remote import URLs should be silently rejected
        let html = r#"<html><head><style>
            @import url("https://example.com/styles.css");
            p { color: green; }
        </style></head><body><p>Hello</p></body></html>"#;

        let pdf = HtmlConverter::new()
            .base_path(Path::new("/tmp"))
            .convert(html)
            .unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn multiple_font_face_rules_in_stylesheet() {
        let html = r#"<html><head><style>
            @font-face {
                font-family: "Font1";
                src: url("font1.ttf");
            }
            @font-face {
                font-family: "Font2";
                src: url("font2.ttf");
            }
        </style></head><body><p>Hello</p></body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    // --- Coverage tests for engine.rs and pdf.rs uncovered lines ---

    #[test]
    fn html_to_pdf_ordered_list_lower_alpha() {
        // Covers engine.rs lines 664,668 (list marker formatting with style types)
        let html = r#"<html><head><style>
            ol { list-style-type: lower-alpha; }
        </style></head><body>
        <ol><li>First</li><li>Second</li><li>Third</li></ol>
        </body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("a."));
        assert!(content.contains("b."));
    }

    #[test]
    fn html_to_pdf_ordered_list_upper_roman() {
        // Covers engine.rs line 120 (to_roman_lower/upper for zero edge case)
        let html = r#"<html><head><style>
            ol { list-style-type: upper-roman; }
        </style></head><body>
        <ol><li>First</li><li>Second</li><li>Third</li></ol>
        </body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("I."));
        assert!(content.contains("II."));
    }

    #[test]
    fn html_to_pdf_list_style_none() {
        // Covers engine.rs list_style_type None branch
        let html = r#"<html><head><style>
            ul { list-style-type: none; }
        </style></head><body>
        <ul><li>Nomarker</li></ul>
        </body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("Nomarker"));
    }

    #[test]
    fn html_to_pdf_list_style_inside() {
        // Covers engine.rs lines 670-671: list-style-position: inside
        let html = r#"<html><head><style>
            ul { list-style-position: inside; }
        </style></head><body>
        <ul><li>InsideItem</li></ul>
        </body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("InsideItem"));
    }

    #[test]
    fn html_to_pdf_flexbox_layout() {
        // Covers engine.rs lines 1067,1113,1133,1395: flex layout
        let html = r#"
        <div style="display: flex; width: 400pt;">
            <div style="width: 200pt;">FlexLeft</div>
            <div style="width: 200pt;">FlexRight</div>
        </div>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn html_to_pdf_flexbox_no_explicit_width() {
        // Covers engine.rs line 1113: flex items without explicit width
        let html = r#"
        <div style="display: flex;">
            <div>AutoA</div>
            <div>AutoB</div>
            <div>AutoC</div>
        </div>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn html_to_pdf_grid_layout() {
        // Covers engine.rs lines 1670,1712: grid track sizing and layout
        let html = r#"
        <div style="display: grid; grid-template-columns: 1fr 1fr;">
            <div>GridA</div>
            <div>GridB</div>
        </div>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn html_to_pdf_table_colspan_exceeds_columns() {
        // Covers engine.rs line 2003: colspan spanning beyond available columns
        let html = r#"
        <table>
            <tr><td colspan="5">WideCellContent</td></tr>
            <tr><td>A</td><td>B</td></tr>
        </table>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn html_to_pdf_table_with_non_tr_children() {
        // Covers engine.rs line 1831: table children that are not tr/thead/tbody/tfoot
        let html = r#"
        <table>
            <caption>Caption</caption>
            <tr><td>Cell</td></tr>
        </table>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn html_to_pdf_text_overflow_ellipsis() {
        // Covers engine.rs lines 2221,2227,2242: nowrap + text-overflow: ellipsis
        let html = r#"
        <div style="width: 50pt; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
            This is a very long text that should be truncated with an ellipsis marker
        </div>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn html_to_pdf_clear_right() {
        // Covers engine.rs line 2312: clear right float
        let html = r#"
        <div style="float: right; width: 100pt;">RightFloated</div>
        <div style="clear: right;">ClearedRight</div>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn html_to_pdf_inline_base64_image() {
        // Covers engine.rs lines 2562,2574: base64 decode
        // A tiny 1x1 red PNG as base64
        let html = r#"<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==" width="10" height="10">"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn html_to_pdf_text_justify() {
        // Covers pdf.rs lines 372,393: text-align: justify with word spacing
        let html = r#"<p style="text-align: justify; width: 300pt;">
            This is a paragraph with justified text alignment that has multiple words
            and should produce word spacing adjustments in the PDF output stream.
        </p>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("Tw") || content.contains("This"));
    }

    #[test]
    fn html_to_pdf_table_border_collapse() {
        // Covers pdf.rs lines 467,472-473,476: border-collapse on table
        let html = r#"<html><head><style>
            table { border-collapse: collapse; }
            td { border: 1pt solid black; }
        </style></head><body>
        <table>
            <tr><td>A</td><td>B</td></tr>
            <tr><td>C</td><td>D</td></tr>
        </table>
        </body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("A"));
        assert!(content.contains("D"));
    }

    #[test]
    fn html_to_pdf_table_rowspan() {
        // Covers pdf.rs lines 513,515: rowspan handling in table rendering
        let html = r#"
        <table>
            <tr><td rowspan="2">Tall</td><td>Top</td></tr>
            <tr><td>Bottom</td></tr>
        </table>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("Tall"));
        assert!(content.contains("Top"));
        assert!(content.contains("Bottom"));
    }

    #[test]
    fn html_to_pdf_grid_row_rendering() {
        // Covers pdf.rs lines 553,555,564: GridRow rendering in PDF
        let html = r#"<html><head><style>
            .grid { display: grid; grid-template-columns: 1fr 1fr 1fr; }
            .grid > div { background-color: #eee; padding: 5pt; }
        </style></head><body>
        <div class="grid">
            <div>GridCell1</div>
            <div>GridCell2</div>
            <div>GridCell3</div>
        </div>
        </body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn html_to_pdf_explicit_page_break_element() {
        // Covers pdf.rs line 634: LayoutElement::PageBreak
        let html = r#"
        <p>PageOneContent</p>
        <div style="page-break-before: always;"></div>
        <p>PageTwoContent</p>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn html_to_pdf_linear_gradient() {
        // Covers pdf.rs lines 253,783,799,802,812: linear gradient rendering
        let html = r#"
        <div style="background: linear-gradient(to right, red, blue); width: 200pt; height: 50pt;">
            Gradient text
        </div>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn html_to_pdf_radial_gradient() {
        // Covers pdf.rs lines 272,905: radial gradient rendering
        let html = r#"
        <div style="background: radial-gradient(circle, red, blue); width: 200pt; height: 50pt;">
            Radial text
        </div>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn html_to_pdf_visibility_hidden() {
        // Covers pdf.rs lines 109-110,112-113: visibility: hidden skips rendering
        let html = r#"<p style="visibility: hidden">Hidden</p><p>VisibleAfterHidden</p>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn html_to_pdf_float_right_rendering() {
        // Covers pdf.rs line 121: Float::Right block_x computation
        let html = r#"
        <div style="float: right; width: 100pt;">RightFloat</div>
        <p>NormalAfterFloat</p>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn html_to_pdf_custom_font_bold_italic_variants() {
        // Covers pdf.rs lines 718-720: Custom font with bold+italic falls back
        let ttf_data = build_integration_test_ttf();
        let pdf = HtmlConverter::new()
            .add_font("testfont", ttf_data)
            .convert(
                r#"<p style="font-family: testfont; font-weight: bold; font-style: italic;">BoldItalic</p>"#,
            )
            .unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn html_to_pdf_table_cell_text_rendering() {
        // Covers pdf.rs lines 675,681: cell text rendering with empty and non-empty runs
        let html = r#"
        <table>
            <tr>
                <td style="padding: 5pt;">CellPadded</td>
                <td></td>
            </tr>
        </table>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn html_to_pdf_grid_with_gap() {
        // Covers pdf.rs lines 593,599: grid gap/spacing calculation
        let html = r#"<html><head><style>
            .grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10pt; }
        </style></head><body>
        <div class="grid">
            <div>GapA</div>
            <div>GapB</div>
        </div>
        </body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn html_to_pdf_li_outside_list() {
        // Covers engine.rs lines 668,676: li without list context
        let html = "<li>OrphanItem</li>";
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn html_to_pdf_flexbox_display_none_child() {
        // Covers engine.rs line 1106-1107: flex child with display:none
        let html = r#"
        <div style="display: flex;">
            <div>FlexVisible</div>
            <div style="display: none;">FlexHidden</div>
            <div>FlexAlso</div>
        </div>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn html_to_pdf_table_border_spacing() {
        // Covers pdf.rs lines 472-473,476: border-spacing in separate mode
        let html = r#"<html><head><style>
            table { border-collapse: separate; border-spacing: 5pt; }
            td { border: 1pt solid black; }
        </style></head><body>
        <table>
            <tr><td>SpacedX</td><td>SpacedY</td></tr>
        </table>
        </body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn font_face_path_traversal_blocked() {
        // A @font-face src with path traversal should be silently skipped
        let dir = std::env::temp_dir().join("ironpress_font_traversal_test");
        std::fs::create_dir_all(&dir).unwrap();

        let html = r#"<html><head><style>
            @font-face { font-family: "Evil"; src: url("../../etc/passwd"); }
            body { font-family: "Evil"; }
        </style></head><body>Hello</body></html>"#;

        let converter = HtmlConverter::new().base_path(&dir);
        let mut buf = Vec::new();
        // Should succeed without loading the traversal path
        let result = converter.convert_to_writer(html, &mut buf);
        assert!(
            result.is_ok(),
            "converter should not fail on traversal font path"
        );
        assert!(buf.starts_with(b"%PDF"));

        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn html_to_pdf_letter_spacing() {
        let html = r#"<p style="letter-spacing: 2pt">Spaced letters</p>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(
            content.contains("Tc"),
            "PDF should contain Tc operator for letter-spacing"
        );
    }

    #[test]
    fn html_to_pdf_word_spacing() {
        let html = r#"<p style="word-spacing: 5pt">Spaced words here</p>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(
            content.contains("Tw"),
            "PDF should contain Tw operator for word-spacing"
        );
    }

    #[test]
    fn html_to_pdf_letter_and_word_spacing_combined() {
        let html =
            r#"<p style="letter-spacing: 2pt; word-spacing: 5pt">Spaced letters and words</p>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(
            content.contains("Tc"),
            "PDF should contain Tc operator for letter-spacing"
        );
        assert!(
            content.contains("Tw"),
            "PDF should contain Tw operator for word-spacing"
        );
    }

    #[test]
    fn html_to_pdf_long_word_hyphenated() {
        // A very long word preceded by short content in a narrow div should be
        // hyphenated in the PDF output (hyphenation triggers when the line
        // already has content and the next word doesn't fit).
        let html = r#"<div style="width: 80pt"><p>Hi Supercalifragilisticexpialidocious</p></div>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        // The PDF text streams should contain a hyphen from the hyphenation
        assert!(
            content.contains('-'),
            "PDF should contain a hyphen from hyphenated long word"
        );
    }

    #[test]
    fn html_to_pdf_inline_svg_rect() {
        let html = r#"<svg width="100" height="100"><rect x="10" y="10" width="80" height="80" fill="red"/></svg>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("re")); // rect operator
    }

    #[test]
    fn html_to_pdf_inline_svg_circle() {
        let html =
            r#"<svg width="100" height="100"><circle cx="50" cy="50" r="40" fill="blue"/></svg>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn html_to_pdf_inline_svg_path() {
        let html = r#"<svg width="100" height="100"><path d="M 10 10 L 90 10 L 90 90 Z" fill="green"/></svg>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn html_to_pdf_inline_svg_with_viewbox() {
        let html = r#"<svg width="200" height="200" viewBox="0 0 100 100"><rect x="0" y="0" width="100" height="100" fill="red"/></svg>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn html_to_pdf_svg_script_stripped() {
        // Script inside SVG should not cause issues (html5ever strips it or ignores it)
        let html = r#"<svg width="100" height="100"><script>alert(1)</script><rect x="10" y="10" width="80" height="80" fill="red"/></svg>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn html_to_pdf_svg_among_html() {
        let html = r#"<h1>Title</h1><svg width="100" height="50"><rect x="0" y="0" width="100" height="50" fill="blue"/></svg><p>World</p>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("Title"));
        assert!(content.contains("World"));
    }

    #[test]
    fn html_to_pdf_justify_single_word_no_spaces() {
        // Covers pdf.rs line 374: justify text with no spaces yields 0.0 word spacing
        let html =
            r#"<p style="text-align: justify; width: 200pt;">Superlongwordwithoutanyspaces</p>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("Superlongword"));
    }

    #[test]
    fn html_to_pdf_radial_gradient_no_block_height() {
        // Covers pdf.rs line 274: radial gradient on block without explicit height
        let html = r#"<html><head><style>
            .grad { background: radial-gradient(circle, red, blue); padding: 10pt; }
        </style></head><body>
        <div class="grad">Radial no height</div>
        </body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn html_to_pdf_linear_gradient_no_block_height() {
        // Covers pdf.rs line 255: linear gradient on block without explicit height
        let html = r#"<html><head><style>
            .grad { background: linear-gradient(to right, red, blue); padding: 10pt; }
        </style></head><body>
        <div class="grad">Linear no height</div>
        </body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn html_to_pdf_table_rowspan_future_row_lookup() {
        // Covers pdf.rs lines 526, 528: rowspan > 1 iterates future rows
        let html = r#"
        <table>
            <tr><td rowspan="3">Spanning</td><td>R1</td></tr>
            <tr><td>R2</td></tr>
            <tr><td>R3</td></tr>
        </table>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("Spanning"));
        assert!(content.contains("R1"));
        assert!(content.contains("R3"));
    }

    #[test]
    fn html_to_pdf_grid_more_cells_than_columns() {
        // Covers pdf.rs line 577: grid cell index exceeding col_widths falls back to 0.0
        let html = r#"<html><head><style>
            .grid { display: grid; grid-template-columns: 100pt; }
        </style></head><body>
        <div class="grid">
            <div>Cell1</div>
            <div>Cell2</div>
            <div>Cell3</div>
        </div>
        </body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn html_to_pdf_empty_paragraph_text_block() {
        // Exercises empty text run/line skipping in pdf.rs lines 401, 718, 724
        let html = r#"<p></p><p>Visible</p>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("Visible"));
    }

    #[test]
    fn html_to_pdf_table_empty_cells() {
        // Covers pdf.rs lines 718, 724: empty cell text/run skipping in render_cell_text
        let html = r#"
        <table>
            <tr><td></td><td>Data</td></tr>
            <tr><td></td><td></td></tr>
        </table>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("Data"));
    }

    #[test]
    fn html_to_pdf_position_relative_offset() {
        // Covers pdf.rs line 121: Position::Relative with offset_left
        let html = r#"<div style="position: relative; left: 20pt;">Shifted</div>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("Shifted"));
    }

    #[test]
    fn html_to_pdf_multiple_page_breaks() {
        // Covers pdf.rs line 677: PageBreak match arm
        let html = r#"
        <p>Page1</p>
        <div style="page-break-before: always;"></div>
        <p>Page2</p>
        <div style="page-break-before: always;"></div>
        <p>Page3</p>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("Page1"));
        assert!(content.contains("Page3"));
    }

    #[test]
    fn html_to_pdf_svg_ellipse_and_line() {
        // Exercise SVG element destructuring (lines 638, 642-643) with different SVG content
        let html = r#"<svg width="200" height="200">
            <ellipse cx="100" cy="100" rx="80" ry="50" fill="green"/>
            <line x1="0" y1="0" x2="200" y2="200" stroke="black"/>
        </svg>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn html_to_pdf_justify_long_word_then_short() {
        // Covers pdf.rs line 374: justify with a non-last line that has no spaces.
        let long_word = "A".repeat(200);
        let html = format!(
            r#"<p style="text-align: justify; width: 100pt;">{long_word} short words here</p>"#,
        );
        let pdf = html_to_pdf(&html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn html_to_pdf_table_with_empty_and_content_cells() {
        // Covers pdf.rs lines 718, 724: render_cell_text with empty lines/runs
        let html = r#"
        <table>
            <tr><td></td><td>A</td><td></td></tr>
            <tr><td>B</td><td></td><td>C</td></tr>
        </table>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("A"));
        assert!(content.contains("B"));
        assert!(content.contains("C"));
    }

    #[test]
    fn html_to_pdf_float_right_without_explicit_width() {
        // Covers pdf.rs line 123: Float::Right without block_width
        let html = r#"<div style="float: right;">FloatedRight</div><p>Normal</p>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("FloatedRight"));
    }

    #[test]
    fn html_to_pdf_position_absolute_offset() {
        // Covers pdf.rs line 120: Position::Absolute with offset_left
        let html = r#"<div style="position: absolute; left: 50pt;">AbsPos</div>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("AbsPos"));
    }

    #[test]
    fn html_to_pdf_inline_image_base64_png() {
        // Covers pdf.rs lines 606, 612: Image element with PNG format
        let html = r#"<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==" width="1" height="1"/>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn html_to_pdf_grid_with_background_and_many_cells() {
        // Covers pdf.rs lines 566, 568, 577: GridRow with cells exceeding columns
        let html = r#"<html><head><style>
            .g { display: grid; grid-template-columns: 50pt 50pt; }
            .g > div { background: #ff0000; padding: 5pt; }
        </style></head><body>
        <div class="g">
            <div>G1</div>
            <div>G2</div>
            <div>G3</div>
            <div>G4</div>
            <div>G5</div>
        </div>
        </body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn html_to_pdf_page_break_empty_arm() {
        // Covers pdf.rs line 677: PageBreak empty match arm
        let html = r#"
        <p>Before</p>
        <div style="page-break-after: always;"></div>
        <p>After</p>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("Before"));
        assert!(content.contains("After"));
    }

    #[test]
    fn html_to_pdf_svg_with_polyline_polygon() {
        // Exercise SVG rendering paths
        let html = r#"<svg width="100" height="100">
            <polyline points="10,10 50,50 90,10" fill="none" stroke="red"/>
            <polygon points="10,80 50,90 90,80" fill="blue"/>
        </svg>"#;
        let pdf = html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn flex_children_with_block_elements_render_content() {
        // Flex children containing block elements (h1, h2, p) should produce text
        let html = r#"<html><body>
        <div style="display: flex; justify-content: space-between;">
            <div>
                <h1>ironpress</h1>
                <h2>Pure Rust PDF Engine</h2>
            </div>
            <div>
                <p>Invoice #INV-2026-0042</p>
            </div>
        </div>
        </body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(
            content.contains("ironpress"),
            "flex child h1 text should appear in PDF"
        );
        // Words may be in separate PDF text objects due to word-by-word rendering
        assert!(
            content.contains("Pure"),
            "flex child h2 word 'Pure' should appear in PDF"
        );
        assert!(
            content.contains("Rust"),
            "flex child h2 word 'Rust' should appear in PDF"
        );
        assert!(
            content.contains("Engine"),
            "flex child h2 word 'Engine' should appear in PDF"
        );
        assert!(
            content.contains("INV-2026"),
            "flex child p text should appear in PDF"
        );
    }

    #[test]
    fn flex_children_simple_divs_render_both() {
        // Basic flex with two simple div children
        let html = r#"<div style="display: flex;"><div>Left</div><div>Right</div></div>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("Left"), "flex child 'Left' should appear");
        assert!(
            content.contains("Right"),
            "flex child 'Right' should appear"
        );
    }

    #[test]
    fn stylesheet_color_applies_to_text() {
        // Colors from <style> blocks should produce color operators in PDF
        let html = r#"<html><head><style>
            h1 { color: red; }
        </style></head><body><h1>Crimson</h1></body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("Crimson"), "text should appear in PDF");
        // red = (1, 0, 0) in PDF color space → "1 0 0 rg"
        assert!(
            content.contains("1 0 0 rg"),
            "red color operator should appear in PDF stream"
        );
    }

    #[test]
    fn stylesheet_background_color_applies_to_table_header() {
        // background-color from <style> block should apply to th elements
        let html = r#"<html><head><style>
            th { background-color: #2c3e50; color: white; }
        </style></head><body>
        <table>
            <tr><th>Header</th></tr>
            <tr><td>Data</td></tr>
        </table>
        </body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("Header"), "th text should appear in PDF");
        // #2c3e50 = (44/255, 62/255, 80/255) ≈ (0.172549, 0.243137, 0.313725)
        // Check for any non-zero background color operator (not 0 0 0)
        assert!(
            content.contains("0.17254902 0.24313726 0.3137255 rg"),
            "background color from stylesheet should produce rg operator"
        );
    }

    #[test]
    fn stylesheet_class_color_applies() {
        // Colors applied via class selectors from <style> blocks
        let html = r#"<html><head><style>
            .badge { background-color: #27ae60; color: white; }
        </style></head><body>
        <div class="badge">Paid</div>
        </body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("Paid"), "badge text should appear");
        // white text = (1, 1, 1) → "1 1 1 rg"
        assert!(
            content.contains("1 1 1 rg"),
            "white color from stylesheet class should be applied"
        );
    }

    #[test]
    fn stylesheet_color_on_inline_element() {
        // Colors from <style> on inline elements like <span> inside <p>
        let html = r#"<html><head><style>
            span { color: blue; }
        </style></head><body>
        <p>Normal <span>Azul</span></p>
        </body></html>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("Azul"), "span text should appear");
        // blue = (0, 0, 1) → "0 0 1 rg"
        assert!(
            content.contains("0 0 1 rg"),
            "blue color from stylesheet should be applied to inline span"
        );
    }

    #[test]
    fn inline_span_background_color() {
        let html = r#"<p><span style="background-color: green; color: white; padding: 2pt 8pt;">BADGE</span></p>"#;
        let pdf = html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        // Should contain fill color operator for the background rectangle
        assert!(
            content.contains("rg") && content.contains("re\nf"),
            "inline span background should produce a filled rectangle (re + f operators)"
        );
    }

    #[test]
    fn fuzz_css_crash_null_bytes() {
        // Reproducer from fuzz_css crash-0a719b393ce35ba946cd6e5cb968203aef229e18
        let data: &[u8] = &[
            0, 0, 0, 0, 0, 13, 64, 0, 12, 64, 60, 47, 115, 116, 121, 108, 101, 62, 4, 4, 4, 64, 12,
            64, 0, 47, 60, 115, 116, 121, 108, 101,
        ];
        if let Ok(s) = std::str::from_utf8(data) {
            let html = format!("<style>{s}</style><p>test</p>");
            let _ = html_to_pdf(&html);
        }
    }
}