ironpress 1.1.2

Pure Rust HTML/CSS/Markdown to PDF converter with layout engine, 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
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
use crate::error::IronpressError;
use crate::layout::engine::{
    ImageFormat, LayoutElement, Page, PngMetadata, TableCell, TextLine, TextRun,
};
use crate::parser::ttf::TtfFont;
use crate::style::computed::{
    BorderCollapse, Float, FontFamily, LinearGradient, Position, RadialGradient, TextAlign,
};
use crate::types::{Margin, PageSize};
use std::collections::HashMap;

/// A PDF shading dictionary entry for native gradient rendering.
struct ShadingEntry {
    name: String,
    shading_type: u8, // 2 = axial (linear), 3 = radial
    coords: [f32; 6],
    stops: Vec<(f32, (f32, f32, f32))>,
}

/// A link annotation to be placed on a PDF page.
struct LinkAnnotation {
    x1: f32,
    y1: f32,
    x2: f32,
    y2: f32,
    url: String,
}

/// A bookmark entry for PDF outline (table of contents).
#[allow(dead_code)]
struct BookmarkEntry {
    title: String,
    level: u8,
    page_index: usize,
    y_pos: f32,
}

/// Render laid-out pages into a PDF byte buffer.
///
/// Uses the PDF built-in Helvetica font family (one of the 14 standard fonts)
/// so no font embedding is needed for the MVP.
#[allow(dead_code)]
pub fn render_pdf(
    pages: &[Page],
    page_size: PageSize,
    margin: Margin,
) -> Result<Vec<u8>, IronpressError> {
    render_pdf_with_fonts(pages, page_size, margin, &HashMap::new())
}

/// Render laid-out pages into a PDF byte buffer, with custom font embedding.
pub fn render_pdf_with_fonts(
    pages: &[Page],
    page_size: PageSize,
    margin: Margin,
    custom_fonts: &HashMap<String, TtfFont>,
) -> Result<Vec<u8>, IronpressError> {
    let mut buf = Vec::new();
    render_pdf_to_writer_with_fonts(pages, page_size, margin, &mut buf, custom_fonts)?;
    Ok(buf)
}

/// Header and footer text for page decoration.
pub struct PageDecoration {
    /// Header text rendered top-center of each page.
    pub header: Option<String>,
    /// Footer text rendered bottom-center of each page.
    /// `{page}` and `{pages}` are replaced with page number and total count.
    pub footer: Option<String>,
}

/// Render laid-out pages as PDF, writing directly to any `std::io::Write` implementation.
///
/// This is the streaming variant of [`render_pdf`]. It writes PDF content incrementally
/// to the provided writer instead of building an in-memory buffer.
#[allow(dead_code)]
pub fn render_pdf_to_writer<W: std::io::Write>(
    pages: &[Page],
    page_size: PageSize,
    margin: Margin,
    writer: &mut W,
) -> Result<(), IronpressError> {
    render_pdf_to_writer_with_fonts(pages, page_size, margin, writer, &HashMap::new())
}

/// Render laid-out pages as PDF with custom fonts, writing directly to any `std::io::Write` implementation.
fn render_pdf_to_writer_with_fonts<W: std::io::Write>(
    pages: &[Page],
    page_size: PageSize,
    margin: Margin,
    writer: &mut W,
    custom_fonts: &HashMap<String, TtfFont>,
) -> Result<(), IronpressError> {
    render_pdf_to_writer_full(pages, page_size, margin, writer, custom_fonts, None)
}

/// Full render function with optional page decoration (headers/footers).
pub(crate) fn render_pdf_to_writer_full<W: std::io::Write>(
    pages: &[Page],
    page_size: PageSize,
    margin: Margin,
    writer: &mut W,
    custom_fonts: &HashMap<String, TtfFont>,
    decoration: Option<&PageDecoration>,
) -> Result<(), IronpressError> {
    let mut pdf_writer = PdfWriter::new();
    let available_width = page_size.width - margin.left - margin.right;
    let mut bookmarks: Vec<BookmarkEntry> = Vec::new();

    // Register custom TrueType fonts
    for (name, ttf) in custom_fonts {
        pdf_writer.add_ttf_font(name, ttf);
    }

    for (page_idx, page) in pages.iter().enumerate() {
        let mut content = String::new();
        let mut annotations: Vec<LinkAnnotation> = Vec::new();
        let mut page_images: Vec<ImageRef> = Vec::new();
        let mut page_ext_gstates: Vec<(String, f32)> = Vec::new();
        let mut page_shadings: Vec<ShadingEntry> = Vec::new();
        let mut shading_counter: usize = 0;

        for (elem_idx, (y_pos, element)) in page.elements.iter().enumerate() {
            match element {
                LayoutElement::TextBlock {
                    lines,
                    text_align,
                    background_color,
                    padding_top,
                    padding_bottom,
                    padding_left,
                    padding_right,
                    border,
                    block_width,
                    block_height,
                    opacity,
                    float,
                    position,
                    offset_left,
                    box_shadow,
                    visible,
                    clip_rect,
                    transform,
                    background_gradient,
                    background_radial_gradient,
                    border_radius,
                    outline_width,
                    outline_color,
                    letter_spacing,
                    word_spacing: css_word_spacing,
                    heading_level,
                    ..
                } => {
                    // Skip rendering if visibility: hidden (but space is preserved)
                    if !visible {
                        continue;
                    }

                    // Collect heading bookmark for PDF outlines
                    if let Some(level) = heading_level {
                        let title: String = lines
                            .iter()
                            .flat_map(|l| l.runs.iter().map(|r| r.text.as_str()))
                            .collect::<Vec<_>>()
                            .join("");
                        if !title.trim().is_empty() {
                            bookmarks.push(BookmarkEntry {
                                title: title.trim().to_string(),
                                level: *level,
                                page_index: page_idx,
                                y_pos: *y_pos,
                            });
                        }
                    }

                    // Compute block_x with float/position offsets
                    let block_x = match position {
                        Position::Absolute => margin.left + offset_left,
                        Position::Relative => margin.left + offset_left,
                        Position::Static => match float {
                            Float::Right => {
                                let render_w = block_width.unwrap_or(available_width);
                                margin.left + available_width - render_w
                            }
                            _ => margin.left,
                        },
                    };
                    // PDF y-axis is bottom-up
                    let block_y = page_size.height - margin.top - y_pos;

                    // Use explicit block_width if set, otherwise available_width
                    let render_width = block_width.unwrap_or(available_width);

                    // Apply transform if set (wrap in q/Q)
                    let needs_transform = transform.is_some();
                    if let Some(t) = transform {
                        content.push_str("q\n");
                        match t {
                            crate::style::computed::Transform::Rotate(deg) => {
                                let rad = deg * std::f32::consts::PI / 180.0;
                                let cos_v = rad.cos();
                                let sin_v = rad.sin();
                                content.push_str(&format!(
                                    "{cos_v} {sin_v} {neg_sin} {cos_v} 0 0 cm\n",
                                    neg_sin = -sin_v,
                                ));
                            }
                            crate::style::computed::Transform::Scale(sx, sy) => {
                                content.push_str(&format!("{sx} 0 0 {sy} 0 0 cm\n",));
                            }
                            crate::style::computed::Transform::Translate(tx, ty) => {
                                content.push_str(&format!("1 0 0 1 {tx} {ty} cm\n",));
                            }
                        }
                    }

                    // Apply clipping rect if overflow: hidden
                    let needs_clip = clip_rect.is_some();
                    if let Some((cx, cy, cw, ch)) = clip_rect {
                        let clip_x = block_x + cx;
                        let clip_y = block_y - ch - cy;
                        content.push_str("q\n");
                        if *border_radius > 0.0 {
                            content.push_str(&rounded_rect_path(
                                clip_x,
                                clip_y,
                                *cw,
                                *ch,
                                *border_radius,
                            ));
                            content.push_str("W n\n");
                        } else {
                            content.push_str(&format!("{clip_x} {clip_y} {cw} {ch} re W n\n",));
                        }
                    }

                    // Apply opacity via ExtGState if < 1.0
                    let needs_opacity = *opacity < 1.0;
                    if needs_opacity {
                        let gs_name = format!("GS{elem_idx}");
                        page_ext_gstates.push((gs_name.clone(), *opacity));
                        content.push_str(&format!("/{gs_name} gs\n"));
                    }

                    // Draw box-shadow if specified (rendered as offset filled rect behind element)
                    if let Some(shadow) = box_shadow {
                        let text_height: f32 = lines.iter().map(|l| l.height).sum();
                        let content_h = padding_top + text_height + padding_bottom;
                        let total_h = match block_height {
                            Some(h) => content_h.max(*h),
                            None => content_h,
                        };
                        let (sr, sg, sb) = shadow.color.to_f32_rgb();
                        let shadow_x = block_x + shadow.offset_x;
                        let shadow_y = block_y - total_h + shadow.offset_y;
                        content.push_str(&format!("{sr} {sg} {sb} rg\n"));
                        if *border_radius > 0.0 {
                            content.push_str(&rounded_rect_path(
                                shadow_x,
                                shadow_y,
                                render_width,
                                total_h,
                                *border_radius,
                            ));
                        } else {
                            content.push_str(&format!(
                                "{x} {y} {w} {h} re\n",
                                x = shadow_x,
                                y = shadow_y,
                                w = render_width,
                                h = total_h,
                            ));
                        }
                        content.push_str("f\n");
                    }

                    // Draw background if specified
                    if let Some((r, g, b)) = background_color {
                        let text_height: f32 = lines.iter().map(|l| l.height).sum();
                        let content_h = padding_top + text_height + padding_bottom;
                        let total_h = match block_height {
                            Some(h) => content_h.max(*h),
                            None => content_h,
                        };
                        let bg_y = block_y - total_h;
                        content.push_str(&format!("{r} {g} {b} rg\n"));
                        if *border_radius > 0.0 {
                            content.push_str(&rounded_rect_path(
                                block_x,
                                bg_y,
                                render_width,
                                total_h,
                                *border_radius,
                            ));
                        } else {
                            content.push_str(&format!(
                                "{x} {y} {w} {h} re\n",
                                x = block_x,
                                y = bg_y,
                                w = render_width,
                                h = total_h,
                            ));
                        }
                        content.push_str("f\n");
                    }

                    // Draw linear gradient if specified
                    if let Some(gradient) = background_gradient {
                        let text_height: f32 = lines.iter().map(|l| l.height).sum();
                        let content_h = padding_top + text_height + padding_bottom;
                        let total_h = match block_height {
                            Some(h) => content_h.max(*h),
                            None => content_h,
                        };
                        let bg_y = block_y - total_h;
                        // Clip to rounded rect if border-radius is set
                        if *border_radius > 0.0 {
                            content.push_str("q\n");
                            content.push_str(&rounded_rect_path(
                                block_x,
                                bg_y,
                                render_width,
                                total_h,
                                *border_radius,
                            ));
                            content.push_str("W n\n");
                        }
                        render_linear_gradient(
                            &mut content,
                            gradient,
                            block_x,
                            bg_y,
                            render_width,
                            total_h,
                            &mut page_shadings,
                            &mut shading_counter,
                        );
                        if *border_radius > 0.0 {
                            content.push_str("Q\n");
                        }
                    }

                    // Draw radial gradient if specified
                    if let Some(gradient) = background_radial_gradient {
                        let text_height: f32 = lines.iter().map(|l| l.height).sum();
                        let content_h = padding_top + text_height + padding_bottom;
                        let total_h = match block_height {
                            Some(h) => content_h.max(*h),
                            None => content_h,
                        };
                        let bg_y = block_y - total_h;
                        if *border_radius > 0.0 {
                            content.push_str("q\n");
                            content.push_str(&rounded_rect_path(
                                block_x,
                                bg_y,
                                render_width,
                                total_h,
                                *border_radius,
                            ));
                            content.push_str("W n\n");
                        }
                        render_radial_gradient(
                            &mut content,
                            gradient,
                            block_x,
                            bg_y,
                            render_width,
                            total_h,
                            &mut page_shadings,
                            &mut shading_counter,
                        );
                        if *border_radius > 0.0 {
                            content.push_str("Q\n");
                        }
                    }

                    // Draw border if specified
                    if border.has_any() {
                        let text_height: f32 = lines.iter().map(|l| l.height).sum();
                        let content_h = padding_top + text_height + padding_bottom;
                        let total_h = match block_height {
                            Some(h) => content_h.max(*h),
                            None => content_h,
                        };
                        let border_y = block_y - total_h;
                        // Check if all sides are uniform (same width & color)
                        let uniform = border.top.width == border.right.width
                            && border.top.width == border.bottom.width
                            && border.top.width == border.left.width
                            && border.top.color == border.right.color
                            && border.top.color == border.bottom.color
                            && border.top.color == border.left.color;
                        if uniform && *border_radius > 0.0 {
                            let (br, bg, bb) = border.top.color;
                            content.push_str(&format!(
                                "{br} {bg} {bb} RG\n{bw} w\n",
                                bw = border.top.width
                            ));
                            content.push_str(&rounded_rect_path(
                                block_x,
                                border_y,
                                render_width,
                                total_h,
                                *border_radius,
                            ));
                            content.push_str("S\n");
                        } else if uniform {
                            let (br, bg, bb) = border.top.color;
                            content.push_str(&format!(
                                "{br} {bg} {bb} RG\n{bw} w\n",
                                bw = border.top.width
                            ));
                            content.push_str(&format!(
                                "{x} {y} {w} {h} re\n",
                                x = block_x,
                                y = border_y,
                                w = render_width,
                                h = total_h,
                            ));
                            content.push_str("S\n");
                        } else {
                            let x1 = block_x;
                            let x2 = block_x + render_width;
                            // Offset borders by half their width so the inner edge
                            // aligns with the padding boundary (CSS box model).
                            let y_top = block_y + border.top.width / 2.0;
                            let y_bottom = border_y - border.bottom.width / 2.0;
                            let x_left = block_x - border.left.width / 2.0;
                            let x_right = block_x + render_width + border.right.width / 2.0;
                            // Top border
                            if border.top.width > 0.0 {
                                let (r, g, b) = border.top.color;
                                content
                                    .push_str(&format!("{r} {g} {b} RG\n{} w\n", border.top.width));
                                content.push_str(&format!("{x1} {y_top} m {x2} {y_top} l S\n"));
                            }
                            // Right border
                            if border.right.width > 0.0 {
                                let (r, g, b) = border.right.color;
                                content.push_str(&format!(
                                    "{r} {g} {b} RG\n{} w\n",
                                    border.right.width
                                ));
                                content.push_str(&format!(
                                    "{x_right} {y_top} m {x_right} {y_bottom} l S\n"
                                ));
                            }
                            // Bottom border
                            if border.bottom.width > 0.0 {
                                let (r, g, b) = border.bottom.color;
                                content.push_str(&format!(
                                    "{r} {g} {b} RG\n{} w\n",
                                    border.bottom.width
                                ));
                                content
                                    .push_str(&format!("{x1} {y_bottom} m {x2} {y_bottom} l S\n"));
                            }
                            // Left border
                            if border.left.width > 0.0 {
                                let (r, g, b) = border.left.color;
                                content.push_str(&format!(
                                    "{r} {g} {b} RG\n{} w\n",
                                    border.left.width
                                ));
                                content.push_str(&format!(
                                    "{x_left} {y_top} m {x_left} {y_bottom} l S\n"
                                ));
                            }
                        }
                    }

                    // Draw outline if specified (outside the element box)
                    if *outline_width > 0.0 {
                        let text_height: f32 = lines.iter().map(|l| l.height).sum();
                        let content_h = padding_top + text_height + padding_bottom;
                        let total_h = match block_height {
                            Some(h) => content_h.max(*h),
                            None => content_h,
                        };
                        let offset = *outline_width / 2.0;
                        let outline_x = block_x - offset;
                        let outline_y = block_y - total_h - offset;
                        let outline_w = render_width + *outline_width;
                        let outline_h = total_h + *outline_width;
                        let (or, og, ob) = outline_color.unwrap_or((0.0, 0.0, 0.0));
                        content
                            .push_str(&format!("{or} {og} {ob} RG\n{ow} w\n", ow = outline_width,));
                        if *border_radius > 0.0 {
                            let outline_r = *border_radius + offset;
                            content.push_str(&rounded_rect_path(
                                outline_x, outline_y, outline_w, outline_h, outline_r,
                            ));
                        } else {
                            content.push_str(&format!(
                                "{x} {y} {w} {h} re\n",
                                x = outline_x,
                                y = outline_y,
                                w = outline_w,
                                h = outline_h,
                            ));
                        }
                        content.push_str("S\n");
                    }

                    let mut text_y = block_y - padding_top;

                    let line_count = lines.len();
                    for (line_idx, line) in lines.iter().enumerate() {
                        // Half-leading model: distribute excess leading equally
                        // above and below so text sits at the CSS baseline position.
                        let line_font_size =
                            line.runs.iter().map(|r| r.font_size).fold(0.0f32, f32::max);
                        let half_leading = (line.height - line_font_size) / 2.0;
                        text_y -= line_font_size + half_leading;

                        let line_text = line_text_content(line);
                        if line_text.is_empty() {
                            continue;
                        }

                        let line_width = estimate_line_width_with_fonts(line, custom_fonts);
                        let is_last_line = line_idx == line_count - 1;

                        // Calculate word spacing for justified text
                        let justify_ws = if *text_align == TextAlign::Justify && !is_last_line {
                            let content_width = render_width - padding_left - padding_right;
                            let remaining = content_width - line_width;
                            let space_count = line_text.matches(' ').count();
                            if space_count > 0 && remaining > 0.0 {
                                remaining / space_count as f32
                            } else {
                                0.0
                            }
                        } else {
                            0.0
                        };
                        let total_ws = justify_ws + *css_word_spacing;

                        let text_x = match text_align {
                            TextAlign::Left | TextAlign::Justify => block_x + padding_left,
                            TextAlign::Center => {
                                let first_pad = line.runs.first().map_or(0.0, |r| r.padding.0);
                                block_x + (render_width - line_width) / 2.0 + first_pad
                            }
                            TextAlign::Right => {
                                // Account for inline padding: text_x is where the
                                // text characters start, but line_width includes the
                                // full visual width (with left+right padding of inline
                                // spans).  Offset by the first run's left padding so
                                // the visual right edge aligns with the right boundary.
                                let first_pad = line.runs.first().map_or(0.0, |r| r.padding.0);
                                block_x + render_width - padding_right - line_width + first_pad
                            }
                        };

                        // Set letter spacing (CSS letter-spacing)
                        if *letter_spacing > 0.0 {
                            content.push_str(&format!("{letter_spacing} Tc\n"));
                        }

                        // Set word spacing (justify + CSS word-spacing)
                        if total_ws > 0.0 {
                            content.push_str(&format!("{total_ws} Tw\n"));
                        }

                        // Merge consecutive runs with the same style so
                        // spaces between words stay in a single PDF text
                        // string, preventing viewers from dropping them.
                        let merged = merge_runs(&line.runs);
                        let mut x = text_x;
                        for run in &merged {
                            if run.text.is_empty() {
                                continue;
                            }

                            let font_name = resolve_font_name(run, custom_fonts);
                            let (r, g, b) = run.color;
                            let run_width = estimate_run_width_with_fonts(run, custom_fonts);

                            // Draw background rectangle for inline spans
                            if let Some((br, bg, bb)) = run.background_color {
                                let (pad_h, pad_v) = run.padding;
                                let rect_x = x - pad_h;
                                let rect_y = text_y - 2.0 - pad_v;
                                let rect_w = run_width + pad_h * 2.0;
                                let rect_h = run.font_size + 2.0 + pad_v * 2.0;
                                content.push_str(&format!("{br} {bg} {bb} rg\n"));
                                if run.border_radius > 0.0 {
                                    content.push_str(&rounded_rect_path(
                                        rect_x,
                                        rect_y,
                                        rect_w,
                                        rect_h,
                                        run.border_radius,
                                    ));
                                    content.push_str("\nf\n");
                                } else {
                                    content.push_str(&format!(
                                        "{rect_x} {rect_y} {rect_w} {rect_h} re\nf\n"
                                    ));
                                }
                            }

                            content.push_str(&format!("{r} {g} {b} rg\n"));
                            content.push_str("BT\n");
                            content.push_str(&format!(
                                "/{font_name} {size} Tf\n",
                                size = run.font_size,
                            ));
                            content.push_str(&format!("{x} {y} Td\n", y = text_y));
                            {
                                let encoded = encode_pdf_text(&run.text);
                                content.push_str(&format!("({encoded}) Tj\n"));
                            }
                            content.push_str("ET\n");

                            // Draw underline (font-size-relative position and thickness)
                            if run.underline {
                                let desc =
                                    crate::fonts::descender_ratio(&run.font_family) * run.font_size;
                                let uy = text_y - desc * 0.6;
                                let thickness = (run.font_size * 0.07).max(0.5);
                                content.push_str(&format!(
                                    "{r} {g} {b} RG\n{thickness} w\n{x} {uy} m {x2} {uy} l\nS\n",
                                    x2 = x + run_width,
                                ));
                            }

                            // Draw strikethrough (line-through)
                            if run.line_through {
                                let sy = text_y + run.font_size * 0.3;
                                let thickness = (run.font_size * 0.07).max(0.5);
                                content.push_str(&format!(
                                    "{r} {g} {b} RG\n{thickness} w\n{x} {sy} m {x2} {sy} l\nS\n",
                                    x2 = x + run_width,
                                ));
                            }

                            // Track link annotation
                            if let Some(url) = &run.link_url {
                                annotations.push(LinkAnnotation {
                                    x1: x,
                                    y1: text_y - 2.0,
                                    x2: x + run_width,
                                    y2: text_y + run.font_size,
                                    url: url.clone(),
                                });
                            }

                            x += run_width;
                        }

                        // Reset letter spacing after line
                        if *letter_spacing > 0.0 {
                            content.push_str("0 Tc\n");
                        }

                        // Reset word spacing after line
                        if total_ws > 0.0 {
                            content.push_str("0 Tw\n");
                        }
                    }

                    // Reset opacity if it was changed
                    if needs_opacity {
                        content.push_str("/GSDefault gs\n");
                    }

                    // Restore clipping state
                    if needs_clip {
                        content.push_str("Q\n");
                    }

                    // Restore transform state
                    if needs_transform {
                        content.push_str("Q\n");
                    }
                }
                LayoutElement::TableRow {
                    cells,
                    col_widths,
                    border_collapse,
                    border_spacing,
                    ..
                } => {
                    let row_y = page_size.height - margin.top - y_pos;
                    let spacing = if *border_collapse == BorderCollapse::Collapse {
                        0.0
                    } else {
                        *border_spacing
                    };

                    // Compute row height (max cell height, excluding rowspan > 1 cells)
                    let row_height = compute_row_height(cells);

                    // Track column position accounting for colspan
                    let mut col_pos: usize = 0;
                    for cell in cells.iter() {
                        // Skip phantom cells (rowspan = 0); they are placeholders
                        // for cells spanning from previous rows.
                        if cell.rowspan == 0 {
                            col_pos += cell.colspan;
                            continue;
                        }

                        let cell_x = margin.left
                            + col_widths.iter().take(col_pos).sum::<f32>()
                            + spacing * col_pos as f32;
                        let cell_w: f32 = (0..cell.colspan)
                            .map(|i| col_widths.get(col_pos + i).copied().unwrap_or(0.0))
                            .sum::<f32>()
                            + if cell.colspan > 1 {
                                spacing * (cell.colspan - 1) as f32
                            } else {
                                0.0
                            };

                        // For cells with rowspan > 1, compute the total height
                        // spanning multiple rows.
                        let cell_height = if cell.rowspan > 1 {
                            let mut total_h = row_height;
                            for offset in 1..cell.rowspan {
                                let future_idx = elem_idx + offset;
                                if future_idx < page.elements.len() {
                                    if let LayoutElement::TableRow {
                                        cells: future_cells,
                                        ..
                                    } = &page.elements[future_idx].1
                                    {
                                        total_h += compute_row_height(future_cells);
                                    }
                                }
                            }
                            total_h
                        } else {
                            row_height
                        };

                        // Draw cell background
                        if let Some((r, g, b)) = cell.background_color {
                            content.push_str(&format!(
                                "{r} {g} {b} rg\n{x} {y} {w} {h} re\nf\n",
                                x = cell_x,
                                y = row_y - cell_height,
                                w = cell_w,
                                h = cell_height,
                            ));
                        }

                        // Draw cell borders when CSS specifies them.
                        if cell.border.has_any() {
                            let x1 = cell_x;
                            let x2 = cell_x + cell_w;
                            let y_top = row_y;
                            let y_bottom = row_y - cell_height;
                            if cell.border.top.width > 0.0 {
                                let (r, g, b) = cell.border.top.color;
                                content.push_str(&format!(
                                    "{r} {g} {b} RG\n{} w\n{x1} {y_top} m {x2} {y_top} l S\n",
                                    cell.border.top.width
                                ));
                            }
                            if cell.border.right.width > 0.0 {
                                let (r, g, b) = cell.border.right.color;
                                content.push_str(&format!(
                                    "{r} {g} {b} RG\n{} w\n{x2} {y_top} m {x2} {y_bottom} l S\n",
                                    cell.border.right.width
                                ));
                            }
                            if cell.border.bottom.width > 0.0 {
                                let (r, g, b) = cell.border.bottom.color;
                                content.push_str(&format!(
                                    "{r} {g} {b} RG\n{} w\n{x1} {y_bottom} m {x2} {y_bottom} l S\n",
                                    cell.border.bottom.width
                                ));
                            }
                            if cell.border.left.width > 0.0 {
                                let (r, g, b) = cell.border.left.color;
                                content.push_str(&format!(
                                    "{r} {g} {b} RG\n{} w\n{x1} {y_top} m {x1} {y_bottom} l S\n",
                                    cell.border.left.width
                                ));
                            }
                        }

                        // Render cell text at the first row's y position
                        render_cell_text(
                            &mut content,
                            cell,
                            cell_x,
                            row_y,
                            cell_w,
                            row_height,
                            custom_fonts,
                        );

                        col_pos += cell.colspan;
                    }
                }
                LayoutElement::GridRow {
                    cells, col_widths, ..
                } => {
                    let row_y = page_size.height - margin.top - y_pos;
                    let row_height = compute_row_height(cells);

                    let mut cell_x = margin.left;
                    for (i, cell) in cells.iter().enumerate() {
                        let cell_w = if i < col_widths.len() {
                            col_widths[i]
                        } else {
                            0.0
                        };

                        // Draw cell background
                        if let Some((r, g, b)) = cell.background_color {
                            content.push_str(&format!(
                                "{r} {g} {b} rg\n{x} {y} {w} {h} re\nf\n",
                                x = cell_x,
                                y = row_y - row_height,
                                w = cell_w,
                                h = row_height,
                            ));
                        }

                        // Render cell text
                        render_cell_text(
                            &mut content,
                            cell,
                            cell_x,
                            row_y,
                            cell_w,
                            row_height,
                            custom_fonts,
                        );

                        cell_x += cell_w;
                        // Add gap between columns
                        if i + 1 < col_widths.len() {
                            let total_col_width: f32 = col_widths.iter().sum();
                            let total_gap = available_width - total_col_width;
                            let num_gaps = col_widths.len().saturating_sub(1);
                            if num_gaps > 0 {
                                cell_x += total_gap / num_gaps as f32;
                            }
                        }
                    }
                }
                LayoutElement::FlexRow {
                    cells,
                    row_height,
                    background_color,
                    container_width,
                    padding_top,
                    padding_bottom,
                    padding_left,
                    padding_right: _,
                    border,
                    border_radius,
                    box_shadow,
                    background_gradient,
                    background_radial_gradient,
                    ..
                } => {
                    let row_y = page_size.height - margin.top - y_pos;
                    let full_height =
                        padding_top + row_height + padding_bottom + border.vertical_width();

                    // Draw box shadow if present
                    if let Some(shadow) = box_shadow {
                        let sx = margin.left + shadow.offset_x;
                        let sy = row_y - full_height - shadow.offset_y;
                        let (sr, sg, sb) = shadow.color.to_f32_rgb();
                        content.push_str(&format!(
                            "{sr} {sg} {sb} rg\n{sx} {sy} {w} {h} re\nf\n",
                            w = container_width,
                            h = full_height,
                        ));
                    }

                    // Draw container background
                    if let Some((r, g, b)) = background_color {
                        let bg_x = margin.left;
                        let bg_y = row_y - full_height;
                        content.push_str(&format!("{r} {g} {b} rg\n"));
                        if *border_radius > 0.0 {
                            content.push_str(&rounded_rect_path(
                                bg_x,
                                bg_y,
                                *container_width,
                                full_height,
                                *border_radius,
                            ));
                            content.push_str("f\n");
                        } else {
                            content.push_str(&format!(
                                "{x} {y} {w} {h} re\nf\n",
                                x = bg_x,
                                y = bg_y,
                                w = container_width,
                                h = full_height,
                            ));
                        }
                    }

                    // Draw container linear gradient
                    if let Some(gradient) = background_gradient {
                        let bg_x = margin.left;
                        let bg_y = row_y - full_height;
                        if *border_radius > 0.0 {
                            content.push_str("q\n");
                            content.push_str(&rounded_rect_path(
                                bg_x,
                                bg_y,
                                *container_width,
                                full_height,
                                *border_radius,
                            ));
                            content.push_str("W n\n");
                        }
                        render_linear_gradient(
                            &mut content,
                            gradient,
                            bg_x,
                            bg_y,
                            *container_width,
                            full_height,
                            &mut page_shadings,
                            &mut shading_counter,
                        );
                        if *border_radius > 0.0 {
                            content.push_str("Q\n");
                        }
                    }

                    // Draw container radial gradient
                    if let Some(gradient) = background_radial_gradient {
                        let bg_x = margin.left;
                        let bg_y = row_y - full_height;
                        if *border_radius > 0.0 {
                            content.push_str("q\n");
                            content.push_str(&rounded_rect_path(
                                bg_x,
                                bg_y,
                                *container_width,
                                full_height,
                                *border_radius,
                            ));
                            content.push_str("W n\n");
                        }
                        render_radial_gradient(
                            &mut content,
                            gradient,
                            bg_x,
                            bg_y,
                            *container_width,
                            full_height,
                            &mut page_shadings,
                            &mut shading_counter,
                        );
                        if *border_radius > 0.0 {
                            content.push_str("Q\n");
                        }
                    }

                    // Draw border
                    if border.has_any() {
                        let bx = margin.left;
                        let by = row_y - full_height;
                        let uniform = border.top.width == border.right.width
                            && border.top.width == border.bottom.width
                            && border.top.width == border.left.width
                            && border.top.color == border.right.color
                            && border.top.color == border.bottom.color
                            && border.top.color == border.left.color;
                        if uniform && *border_radius > 0.0 {
                            let (r, g, b) = border.top.color;
                            content.push_str(&format!(
                                "{r} {g} {b} RG\n{bw} w\n",
                                bw = border.top.width
                            ));
                            content.push_str(&rounded_rect_path(
                                bx,
                                by,
                                *container_width,
                                full_height,
                                *border_radius,
                            ));
                            content.push_str("S\n");
                        } else if uniform {
                            let (r, g, b) = border.top.color;
                            content.push_str(&format!(
                                "{r} {g} {b} RG\n{bw} w\n{bx} {by} {w} {h} re\nS\n",
                                bw = border.top.width,
                                w = container_width,
                                h = full_height,
                            ));
                        } else {
                            let x1 = bx;
                            let x2 = bx + container_width;
                            let y_top = row_y;
                            let y_bottom = by;
                            if border.top.width > 0.0 {
                                let (r, g, b) = border.top.color;
                                content.push_str(&format!(
                                    "{r} {g} {b} RG\n{} w\n{x1} {y_top} m {x2} {y_top} l S\n",
                                    border.top.width
                                ));
                            }
                            if border.right.width > 0.0 {
                                let (r, g, b) = border.right.color;
                                content.push_str(&format!(
                                    "{r} {g} {b} RG\n{} w\n{x2} {y_top} m {x2} {y_bottom} l S\n",
                                    border.right.width
                                ));
                            }
                            if border.bottom.width > 0.0 {
                                let (r, g, b) = border.bottom.color;
                                content.push_str(&format!(
                                    "{r} {g} {b} RG\n{} w\n{x1} {y_bottom} m {x2} {y_bottom} l S\n",
                                    border.bottom.width
                                ));
                            }
                            if border.left.width > 0.0 {
                                let (r, g, b) = border.left.color;
                                content.push_str(&format!(
                                    "{r} {g} {b} RG\n{} w\n{x1} {y_top} m {x1} {y_bottom} l S\n",
                                    border.left.width
                                ));
                            }
                        }
                    }

                    // Render each flex cell at its computed x-offset
                    let text_area_top = row_y - border.top.width - padding_top;
                    for cell in cells {
                        let cell_x = margin.left + padding_left + cell.x_offset;
                        let cell_inner_w = cell.width - cell.padding_left - cell.padding_right;

                        // Draw cell background
                        if let Some((r, g, b)) = cell.background_color {
                            let bg_x = margin.left + padding_left + cell.x_offset;
                            let bg_y = text_area_top - row_height;
                            content.push_str(&format!("{r} {g} {b} rg\n"));
                            if cell.border_radius > 0.0 {
                                content.push_str(&rounded_rect_path(
                                    bg_x,
                                    bg_y,
                                    cell.width,
                                    *row_height,
                                    cell.border_radius,
                                ));
                                content.push_str("f\n");
                            } else {
                                content.push_str(&format!(
                                    "{bg_x} {bg_y} {w} {h} re\nf\n",
                                    w = cell.width,
                                    h = *row_height,
                                ));
                            }
                        }

                        // Draw cell linear gradient
                        if let Some(gradient) = &cell.background_gradient {
                            let bg_x = margin.left + padding_left + cell.x_offset;
                            let bg_y = text_area_top - row_height;
                            if cell.border_radius > 0.0 {
                                content.push_str("q\n");
                                content.push_str(&rounded_rect_path(
                                    bg_x,
                                    bg_y,
                                    cell.width,
                                    *row_height,
                                    cell.border_radius,
                                ));
                                content.push_str("W n\n");
                            }
                            render_linear_gradient(
                                &mut content,
                                gradient,
                                bg_x,
                                bg_y,
                                cell.width,
                                *row_height,
                                &mut page_shadings,
                                &mut shading_counter,
                            );
                            if cell.border_radius > 0.0 {
                                content.push_str("Q\n");
                            }
                        }

                        // Draw cell radial gradient
                        if let Some(gradient) = &cell.background_radial_gradient {
                            let bg_x = margin.left + padding_left + cell.x_offset;
                            let bg_y = text_area_top - row_height;
                            if cell.border_radius > 0.0 {
                                content.push_str("q\n");
                                content.push_str(&rounded_rect_path(
                                    bg_x,
                                    bg_y,
                                    cell.width,
                                    *row_height,
                                    cell.border_radius,
                                ));
                                content.push_str("W n\n");
                            }
                            render_radial_gradient(
                                &mut content,
                                gradient,
                                bg_x,
                                bg_y,
                                cell.width,
                                *row_height,
                                &mut page_shadings,
                                &mut shading_counter,
                            );
                            if cell.border_radius > 0.0 {
                                content.push_str("Q\n");
                            }
                        }

                        // Render cell text
                        let mut text_y = text_area_top - cell.padding_top;
                        for line in &cell.lines {
                            let line_font_size =
                                line.runs.iter().map(|r| r.font_size).fold(0.0f32, f32::max);
                            let half_leading = (line.height - line_font_size) / 2.0;
                            text_y -= line_font_size + half_leading;
                            let text_content: String =
                                line.runs.iter().map(|r| r.text.as_str()).collect();
                            if text_content.is_empty() {
                                continue;
                            }
                            let merged = merge_runs(&line.runs);
                            // Calculate line width for text-align
                            let line_width: f32 = merged
                                .iter()
                                .map(|r| {
                                    let w = estimate_run_width_with_fonts(r, custom_fonts);
                                    w + r.padding.0 * 2.0
                                })
                                .sum();
                            let first_pad = line.runs.first().map_or(0.0, |r| r.padding.0);
                            let text_x = match cell.text_align {
                                TextAlign::Right => {
                                    cell_x
                                        + cell.padding_left
                                        + (cell_inner_w - line_width).max(0.0)
                                        + first_pad
                                }
                                TextAlign::Center => {
                                    cell_x
                                        + cell.padding_left
                                        + ((cell_inner_w - line_width) / 2.0).max(0.0)
                                        + first_pad
                                }
                                _ => cell_x + cell.padding_left,
                            };
                            let mut x = text_x;
                            for run in &merged {
                                if run.text.is_empty() {
                                    continue;
                                }
                                let font_name = resolve_font_name(run, custom_fonts);
                                let (r, g, b) = run.color;
                                let rw = estimate_run_width_with_fonts(run, custom_fonts);

                                // Draw background rectangle for inline spans
                                if let Some((br, bgc, bb)) = run.background_color {
                                    let (pad_h, pad_v) = run.padding;
                                    let rx = x - pad_h;
                                    let ry = text_y - 2.0 - pad_v;
                                    let rw2 = rw + pad_h * 2.0;
                                    let rh = run.font_size + 2.0 + pad_v * 2.0;
                                    content.push_str(&format!("{br} {bgc} {bb} rg\n"));
                                    if run.border_radius > 0.0 {
                                        content.push_str(&rounded_rect_path(
                                            rx,
                                            ry,
                                            rw2,
                                            rh,
                                            run.border_radius,
                                        ));
                                        content.push_str("\nf\n");
                                    } else {
                                        content.push_str(&format!("{rx} {ry} {rw2} {rh} re\nf\n"));
                                    }
                                }

                                content.push_str(&format!("{r} {g} {b} rg\n"));
                                content.push_str("BT\n");
                                content.push_str(&format!("/{font_name} {} Tf\n", run.font_size));
                                content.push_str(&format!("{x} {y} Td\n", y = text_y));
                                {
                                    let encoded = encode_pdf_text(&run.text);
                                    content.push_str(&format!("({encoded}) Tj\n"));
                                }
                                content.push_str("ET\n");

                                // Draw underline (font-size-relative)
                                if run.underline {
                                    let desc = crate::fonts::descender_ratio(&run.font_family)
                                        * run.font_size;
                                    let uy = text_y - desc * 0.6;
                                    let thickness = (run.font_size * 0.07).max(0.5);
                                    content.push_str(&format!(
                                        "{r} {g} {b} RG\n{thickness} w\n{x} {uy} m {x2} {uy} l\nS\n",
                                        x2 = x + rw,
                                    ));
                                }

                                // Draw strikethrough (line-through)
                                if run.line_through {
                                    let sy = text_y + run.font_size * 0.3;
                                    let thickness = (run.font_size * 0.07).max(0.5);
                                    content.push_str(&format!(
                                        "{r} {g} {b} RG\n{thickness} w\n{x} {sy} m {x2} {sy} l\nS\n",
                                        x2 = x + rw,
                                    ));
                                }

                                x += rw;
                            }
                        }
                    }
                }
                LayoutElement::Image {
                    data,
                    width,
                    height,
                    format,
                    png_metadata,
                    ..
                } => {
                    let img_x = margin.left;
                    // PDF y-axis is bottom-up; y_pos is top of margin, image draws from bottom-left
                    let img_y = page_size.height - margin.top - y_pos - height;
                    let img_obj_id = pdf_writer.add_image_object(
                        data,
                        *width as u32,
                        *height as u32,
                        *format,
                        png_metadata.as_ref(),
                    );
                    let img_name = format!("Im{img_obj_id}");
                    content.push_str(&format!(
                        "q\n{w} 0 0 {h} {x} {y} cm\n/{name} Do\nQ\n",
                        w = width,
                        h = height,
                        x = img_x,
                        y = img_y,
                        name = img_name,
                    ));
                    page_images.push(ImageRef {
                        name: img_name,
                        obj_id: img_obj_id,
                    });
                }
                LayoutElement::Svg {
                    tree,
                    width,
                    height,
                    ..
                } => {
                    let svg_x = margin.left;
                    // PDF y-axis is bottom-up, SVG is top-down
                    let svg_y = page_size.height - margin.top - y_pos - height;

                    content.push_str("q\n");
                    // Position on page and flip y-axis for SVG coordinates
                    content.push_str(&format!("1 0 0 -1 {} {} cm\n", svg_x, svg_y + height));

                    // Apply viewBox scaling if present
                    if let Some(ref vb) = tree.view_box {
                        if vb.width > 0.0 && vb.height > 0.0 {
                            let sx = width / vb.width;
                            let sy = height / vb.height;
                            content.push_str(&format!(
                                "{sx} 0 0 {sy} {} {} cm\n",
                                -vb.min_x * sx,
                                -vb.min_y * sy
                            ));
                        }
                    }

                    crate::render::svg_to_pdf::render_svg_tree(tree, &mut content);
                    content.push_str("Q\n");
                }
                LayoutElement::HorizontalRule { .. } => {
                    let rule_y = page_size.height - margin.top - y_pos;
                    content.push_str(&format!(
                        "0.5 w\n0 0 0 RG\n{x1} {y} m {x2} {y} l\nS\n",
                        x1 = margin.left,
                        x2 = page_size.width - margin.right,
                        y = rule_y,
                    ));
                }
                LayoutElement::ProgressBar {
                    fraction,
                    width,
                    height,
                    fill_color,
                    track_color,
                    ..
                } => {
                    let bar_x = margin.left;
                    let bar_y = page_size.height - margin.top - y_pos - height;

                    // Draw track background
                    content.push_str(&format!(
                        "{r} {g} {b} rg\n{x} {y} {w} {h} re\nf\n",
                        r = track_color.0,
                        g = track_color.1,
                        b = track_color.2,
                        x = bar_x,
                        y = bar_y,
                        w = width,
                        h = height,
                    ));

                    // Draw filled portion
                    if *fraction > 0.0 {
                        let fill_w = width * fraction;
                        content.push_str(&format!(
                            "{r} {g} {b} rg\n{x} {y} {w} {h} re\nf\n",
                            r = fill_color.0,
                            g = fill_color.1,
                            b = fill_color.2,
                            x = bar_x,
                            y = bar_y,
                            w = fill_w,
                            h = height,
                        ));
                    }

                    // Draw border
                    content.push_str(&format!(
                        "0.5 w\n0.6 0.6 0.6 RG\n{x} {y} {w} {h} re\nS\n",
                        x = bar_x,
                        y = bar_y,
                        w = width,
                        h = height,
                    ));
                }
                LayoutElement::PageBreak => {}
            }
        }

        // Render page header/footer in margin area
        if let Some(dec) = decoration {
            let total_pages = pages.len();
            let page_num = page_idx + 1;
            let center_x = page_size.width / 2.0;

            if let Some(ref header_text) = dec.header {
                let text = header_text
                    .replace("{page}", &page_num.to_string())
                    .replace("{pages}", &total_pages.to_string());
                let encoded = encode_pdf_text(&text);
                let header_y = page_size.height - margin.top / 2.0;
                content.push_str("BT\n");
                content.push_str("/Helvetica 9 Tf\n");
                content.push_str("0.4 0.4 0.4 rg\n");
                content.push_str(&format!("{center_x} {header_y} Td\n"));
                content.push_str(&format!("({encoded}) Tj\n"));
                content.push_str("ET\n");
            }

            if let Some(ref footer_text) = dec.footer {
                let text = footer_text
                    .replace("{page}", &page_num.to_string())
                    .replace("{pages}", &total_pages.to_string());
                let encoded = encode_pdf_text(&text);
                let footer_y = margin.bottom / 2.0;
                content.push_str("BT\n");
                content.push_str("/Helvetica 9 Tf\n");
                content.push_str("0.4 0.4 0.4 rg\n");
                content.push_str(&format!("{center_x} {footer_y} Td\n"));
                content.push_str(&format!("({encoded}) Tj\n"));
                content.push_str("ET\n");
            }
        }

        pdf_writer.add_page(
            page_size.width,
            page_size.height,
            &content,
            annotations,
            page_images,
            page_ext_gstates,
            page_shadings,
        );
    }

    pdf_writer.finish_to_writer(writer, &bookmarks)
}

/// Compute the height of a table row from its cells.
fn compute_row_height(cells: &[TableCell]) -> f32 {
    cells
        .iter()
        .map(|cell| {
            let text_h: f32 = cell.lines.iter().map(|l| l.height).sum();
            cell.padding_top + text_h + cell.padding_bottom
        })
        .fold(0.0f32, f32::max)
}

fn render_cell_text(
    content: &mut String,
    cell: &TableCell,
    cell_x: f32,
    row_y: f32,
    col_width: f32,
    row_height: f32,
    custom_fonts: &HashMap<String, TtfFont>,
) {
    let cell_inner_w = col_width - cell.padding_left - cell.padding_right;
    // Vertical centering: place text block so its visual center aligns with
    // the row's vertical center.  In PDF, the baseline is where we position
    // text — glyphs extend upward by ascender and downward by descender.
    let text_h: f32 = cell.lines.iter().map(|l| l.height).sum();

    // Top of the text block, centered in the row
    let text_block_top = row_y - (row_height - text_h) / 2.0;
    let mut text_y = text_block_top;
    for line in &cell.lines {
        let line_font_size = line.runs.iter().map(|r| r.font_size).fold(0.0f32, f32::max);
        let line_family = line
            .runs
            .first()
            .map_or(FontFamily::Helvetica, |r| r.font_family.clone());
        let line_ascender = crate::fonts::ascender_ratio(&line_family) * line_font_size;
        let half_leading = (line.height - line_font_size) / 2.0;
        // Baseline sits at: top of line - half_leading - ascender
        text_y -= half_leading + line_ascender;
        let text_content: String = line.runs.iter().map(|r| r.text.as_str()).collect();
        if text_content.is_empty() {
            continue;
        }
        let merged = merge_runs(&line.runs);
        let line_width: f32 = merged
            .iter()
            .map(|r| estimate_run_width_with_fonts(r, custom_fonts))
            .sum();
        let text_x = match cell.text_align {
            TextAlign::Right => cell_x + cell.padding_left + (cell_inner_w - line_width).max(0.0),
            TextAlign::Center => {
                cell_x + cell.padding_left + ((cell_inner_w - line_width) / 2.0).max(0.0)
            }
            _ => cell_x + cell.padding_left,
        };
        let mut x = text_x;
        for run in &merged {
            if run.text.is_empty() {
                continue;
            }
            let font_name = resolve_font_name(run, custom_fonts);
            let (r, g, b) = run.color;
            let rw = estimate_run_width_with_fonts(run, custom_fonts);

            // Draw background rectangle for inline spans
            if let Some((br, bgc, bb)) = run.background_color {
                let (pad_h, pad_v) = run.padding;
                let rx = x - pad_h;
                let ry = text_y - 2.0 - pad_v;
                let rw2 = rw + pad_h * 2.0;
                let rh = run.font_size + 2.0 + pad_v * 2.0;
                content.push_str(&format!("{br} {bgc} {bb} rg\n"));
                if run.border_radius > 0.0 {
                    content.push_str(&rounded_rect_path(rx, ry, rw2, rh, run.border_radius));
                    content.push_str("\nf\n");
                } else {
                    content.push_str(&format!("{rx} {ry} {rw2} {rh} re\nf\n"));
                }
            }

            content.push_str(&format!("{r} {g} {b} rg\n"));
            content.push_str("BT\n");
            content.push_str(&format!("/{font_name} {} Tf\n", run.font_size));
            content.push_str(&format!("{x} {y} Td\n", y = text_y));
            {
                let encoded = encode_pdf_text(&run.text);
                content.push_str(&format!("({encoded}) Tj\n"));
            }
            content.push_str("ET\n");

            // Draw underline (font-size-relative)
            if run.underline {
                let desc = crate::fonts::descender_ratio(&run.font_family) * run.font_size;
                let uy = text_y - desc * 0.6;
                let thickness = (run.font_size * 0.07).max(0.5);
                content.push_str(&format!(
                    "{r} {g} {b} RG\n{thickness} w\n{x} {uy} m {x2} {uy} l\nS\n",
                    x2 = x + rw,
                ));
            }

            // Draw strikethrough (line-through)
            if run.line_through {
                let sy = text_y + run.font_size * 0.3;
                let thickness = (run.font_size * 0.07).max(0.5);
                content.push_str(&format!(
                    "{r} {g} {b} RG\n{thickness} w\n{x} {sy} m {x2} {sy} l\nS\n",
                    x2 = x + rw,
                ));
            }

            x += rw;
        }
        // Move past the rest of the line (descender + bottom half-leading)
        text_y -= line.height - half_leading - line_ascender;
    }
}

fn font_name_for_run(run: &TextRun) -> &str {
    match (&run.font_family, run.bold, run.italic) {
        // Helvetica (sans-serif)
        (FontFamily::Helvetica, true, true) => "Helvetica-BoldOblique",
        (FontFamily::Helvetica, true, false) => "Helvetica-Bold",
        (FontFamily::Helvetica, false, true) => "Helvetica-Oblique",
        (FontFamily::Helvetica, false, false) => "Helvetica",
        // Times Roman (serif)
        (FontFamily::TimesRoman, true, true) => "Times-BoldItalic",
        (FontFamily::TimesRoman, true, false) => "Times-Bold",
        (FontFamily::TimesRoman, false, true) => "Times-Italic",
        (FontFamily::TimesRoman, false, false) => "Times-Roman",
        // Courier (monospace)
        (FontFamily::Courier, true, true) => "Courier-BoldOblique",
        (FontFamily::Courier, true, false) => "Courier-Bold",
        (FontFamily::Courier, false, true) => "Courier-Oblique",
        (FontFamily::Courier, false, false) => "Courier",
        // Custom fonts — fall back to Helvetica variant for rendering name;
        // the actual font reference is handled separately by the renderer.
        (FontFamily::Custom(_), true, true) => "Helvetica-BoldOblique",
        (FontFamily::Custom(_), true, false) => "Helvetica-Bold",
        (FontFamily::Custom(_), false, true) => "Helvetica-Oblique",
        (FontFamily::Custom(_), false, false) => "Helvetica",
    }
}

fn estimate_run_width(run: &TextRun) -> f32 {
    crate::fonts::str_width(&run.text, run.font_size, &run.font_family, run.bold)
}

/// Resolve the PDF font resource name for a text run, using custom fonts if available.
fn resolve_font_name(run: &TextRun, custom_fonts: &HashMap<String, TtfFont>) -> String {
    if let FontFamily::Custom(name) = &run.font_family {
        if custom_fonts.contains_key(name) {
            return sanitize_pdf_name(name);
        }
    }
    font_name_for_run(run).to_string()
}

/// Estimate run width using TTF metrics for custom fonts, falling back to fixed estimation.
fn estimate_run_width_with_fonts(run: &TextRun, custom_fonts: &HashMap<String, TtfFont>) -> f32 {
    if let FontFamily::Custom(name) = &run.font_family {
        if let Some(ttf) = custom_fonts.get(name) {
            return run
                .text
                .chars()
                .map(|c| ttf.char_width_scaled(c as u16, run.font_size))
                .sum();
        }
    }
    estimate_run_width(run)
}

/// Estimate line width using TTF metrics for custom fonts.
fn estimate_line_width_with_fonts(line: &TextLine, custom_fonts: &HashMap<String, TtfFont>) -> f32 {
    line.runs
        .iter()
        .map(|r| {
            let text_w = estimate_run_width_with_fonts(r, custom_fonts);
            // Include inline padding (e.g. badge spans with horizontal padding)
            let (pad_h, _pad_v) = r.padding;
            text_w + pad_h * 2.0
        })
        .sum()
}

/// Sanitize a font name for use as a PDF name object (remove spaces, special chars).
fn sanitize_pdf_name(name: &str) -> String {
    name.chars()
        .filter(|c| c.is_alphanumeric() || *c == '-' || *c == '_')
        .collect()
}

fn line_text_content(line: &TextLine) -> String {
    line.runs.iter().map(|r| r.text.as_str()).collect()
}

/// Merge consecutive text runs that share the same visual properties (font,
/// size, bold, italic, color, underline, line-through, link) into a single
/// run.  This produces cleaner PDF output and ensures that spaces between
/// words are part of one contiguous text string, preventing PDF viewers from
/// dropping inter-word spaces during text extraction.
fn merge_runs(runs: &[TextRun]) -> Vec<TextRun> {
    let mut merged: Vec<TextRun> = Vec::new();
    for run in runs {
        if run.text.is_empty() {
            continue;
        }
        let can_merge = if let Some(prev) = merged.last() {
            prev.font_size == run.font_size
                && prev.bold == run.bold
                && prev.italic == run.italic
                && prev.underline == run.underline
                && prev.line_through == run.line_through
                && prev.color == run.color
                && prev.link_url == run.link_url
                && prev.font_family == run.font_family
                && prev.background_color == run.background_color
                && prev.padding == run.padding
                && prev.border_radius == run.border_radius
        } else {
            false
        };
        if can_merge {
            merged.last_mut().unwrap().text.push_str(&run.text);
        } else {
            merged.push(run.clone());
        }
    }
    merged
}

/// Render a linear gradient using a native PDF Shading Dictionary reference.
///
/// Instead of drawing 200 thin rectangles (which produces banding), this emits
/// a `sh` operator referencing a shading dictionary that the PDF viewer will
/// interpolate smoothly. The shading entry is collected and later written as a
/// PDF object in `finish_to_writer`.
#[allow(clippy::too_many_arguments)]
fn render_linear_gradient(
    content: &mut String,
    gradient: &LinearGradient,
    x: f32,
    y: f32,
    width: f32,
    height: f32,
    shadings: &mut Vec<ShadingEntry>,
    shading_counter: &mut usize,
) {
    let name = format!("SH{}", *shading_counter);
    *shading_counter += 1;

    // CSS angle convention: 0° = to top (bottom-to-top), 90° = to right, 180° = to bottom
    // In PDF coordinate space, y-axis is bottom-up, so:
    //   CSS 0° (to top) => PDF line from bottom center to top center
    //   CSS 90° (to right) => PDF line from left center to right center
    //   CSS 180° (to bottom) => PDF line from top center to bottom center
    let angle_rad = gradient.angle * std::f32::consts::PI / 180.0;
    let sin_a = angle_rad.sin();
    let cos_a = angle_rad.cos();

    // Gradient line: start and end points
    // CSS: 0deg = to top, so direction vector is (sin(angle), -cos(angle)) in CSS coords
    // In PDF coords (y flipped): direction is (sin(angle), cos(angle))
    let cx = x + width / 2.0;
    let cy = y + height / 2.0;
    // Half-length of the gradient line along the direction
    let half_len = (width * sin_a.abs() + height * cos_a.abs()) / 2.0;
    let dx = sin_a * half_len;
    let dy = cos_a * half_len;

    let x0 = cx - dx;
    let y0 = cy - dy;
    let x1 = cx + dx;
    let y1 = cy + dy;

    let stops: Vec<(f32, (f32, f32, f32))> = gradient
        .stops
        .iter()
        .map(|s| (s.position, s.color.to_f32_rgb()))
        .collect();

    shadings.push(ShadingEntry {
        name: name.clone(),
        shading_type: 2, // Axial
        coords: [x0, y0, x1, y1, 0.0, 0.0],
        stops,
    });

    // Clip to the gradient area and paint with shading
    content.push_str("q\n");
    content.push_str(&format!("{x} {y} {width} {height} re W n\n"));
    content.push_str(&format!("/{name} sh\n"));
    content.push_str("Q\n");
}

/// Render a radial gradient using a native PDF Shading Dictionary reference.
#[allow(clippy::too_many_arguments)]
fn render_radial_gradient(
    content: &mut String,
    gradient: &RadialGradient,
    x: f32,
    y: f32,
    width: f32,
    height: f32,
    shadings: &mut Vec<ShadingEntry>,
    shading_counter: &mut usize,
) {
    let name = format!("SH{}", *shading_counter);
    *shading_counter += 1;

    let cx = x + width / 2.0;
    let cy = y + height / 2.0;
    let max_radius = width.max(height) / 2.0;

    let stops: Vec<(f32, (f32, f32, f32))> = gradient
        .stops
        .iter()
        .map(|s| (s.position, s.color.to_f32_rgb()))
        .collect();

    shadings.push(ShadingEntry {
        name: name.clone(),
        shading_type: 3, // Radial
        coords: [cx, cy, 0.0, cx, cy, max_radius],
        stops,
    });

    // Clip to the gradient area and paint with shading
    content.push_str("q\n");
    content.push_str(&format!("{x} {y} {width} {height} re W n\n"));
    content.push_str(&format!("/{name} sh\n"));
    content.push_str("Q\n");
}

/// Build an inline PDF Function dictionary string for a gradient's color stops.
///
/// For 2 stops, returns a Type 2 (exponential interpolation) function.
/// For 3+ stops, returns a Type 3 (stitching) function that chains Type 2 sub-functions.
fn build_shading_function(stops: &[(f32, (f32, f32, f32))]) -> String {
    if stops.len() < 2 {
        // Fallback: single color
        let (r, g, b) = stops.first().map(|s| s.1).unwrap_or((0.0, 0.0, 0.0));
        return format!(
            "<< /FunctionType 2 /Domain [0 1] /C0 [{r} {g} {b}] /C1 [{r} {g} {b}] /N 1 >>"
        );
    }

    if stops.len() == 2 {
        let (r0, g0, b0) = stops[0].1;
        let (r1, g1, b1) = stops[1].1;
        return format!(
            "<< /FunctionType 2 /Domain [0 1] /C0 [{r0} {g0} {b0}] /C1 [{r1} {g1} {b1}] /N 1 >>"
        );
    }

    // Type 3 stitching function for 3+ stops
    let mut functions = Vec::new();
    let mut bounds = Vec::new();
    let mut encode = Vec::new();

    for i in 0..stops.len() - 1 {
        let (r0, g0, b0) = stops[i].1;
        let (r1, g1, b1) = stops[i + 1].1;
        functions.push(format!(
            "<< /FunctionType 2 /Domain [0 1] /C0 [{r0} {g0} {b0}] /C1 [{r1} {g1} {b1}] /N 1 >>"
        ));
        if i < stops.len() - 2 {
            bounds.push(format!("{}", stops[i + 1].0));
        }
        encode.push("0 1".to_string());
    }

    let functions_str = functions.join(" ");
    let bounds_str = bounds.join(" ");
    let encode_str = encode.join(" ");

    format!(
        "<< /FunctionType 3 /Domain [0 1] /Functions [{functions_str}] /Bounds [{bounds_str}] /Encode [{encode_str}] >>"
    )
}

/// Generate a PDF path for a rounded rectangle.
///
/// Uses cubic Bezier curves to approximate circular arcs at each corner.
/// The magic number k = r * 0.5522847498 gives the best circular approximation.
fn rounded_rect_path(x: f32, y: f32, w: f32, h: f32, r: f32) -> String {
    let r = r.min(w / 2.0).min(h / 2.0); // Clamp radius to half the smallest dimension
    let k = r * 0.552_284_8;
    format!(
        "{x0} {y0} m\n\
         {x1} {y0} l {x2} {y0} {x3} {y3} {x3} {y4} c\n\
         {x3} {y5} l {x3} {y6} {x2} {y7} {x1} {y7} c\n\
         {x0} {y7} l {x8} {y7} {x9} {y6} {x9} {y5} c\n\
         {x9} {y4} l {x9} {y3} {x8} {y0} {x0} {y0} c\n\
         h\n",
        x0 = x + r,
        x1 = x + w - r,
        x2 = x + w - r + k,
        x3 = x + w,
        x8 = x + r - k,
        x9 = x,
        y0 = y + h, // top
        y3 = y + h - r + k,
        y4 = y + h - r,
        y5 = y + r,
        y6 = y + r - k,
        y7 = y, // bottom
    )
}

/// Convert a UTF-8 string to WinAnsi (Windows-1252) encoded bytes.
///
/// Standard PDF fonts (Helvetica, Times-Roman, Courier) use WinAnsi encoding,
/// not UTF-8. Writing raw UTF-8 bytes causes multi-byte characters like em dash
/// to appear as mojibake. This function maps Unicode code points to their
/// WinAnsi byte equivalents.
fn utf8_to_winansi(text: &str) -> Vec<u8> {
    let mut result = Vec::with_capacity(text.len());
    for ch in text.chars() {
        let code = ch as u32;
        match code {
            // ASCII range maps directly
            0x0000..=0x007F => result.push(code as u8),
            // Non-breaking space
            0x00A0 => result.push(0xA0),
            // Latin-1 supplement U+00A1..U+00FF map directly
            0x00A1..=0x00FF => result.push(code as u8),
            // WinAnsi special mappings from the Windows-1252 range 0x80..0x9F
            0x20AC => result.push(0x80), // Euro sign
            0x201A => result.push(0x82), // Single low-9 quotation mark
            0x0192 => result.push(0x83), // Latin small letter f with hook
            0x201E => result.push(0x84), // Double low-9 quotation mark
            0x2026 => result.push(0x85), // Horizontal ellipsis
            0x2020 => result.push(0x86), // Dagger
            0x2021 => result.push(0x87), // Double dagger
            0x02C6 => result.push(0x88), // Modifier letter circumflex accent
            0x2030 => result.push(0x89), // Per mille sign
            0x0160 => result.push(0x8A), // Latin capital letter S with caron
            0x2039 => result.push(0x8B), // Single left-pointing angle quotation mark
            0x0152 => result.push(0x8C), // Latin capital ligature OE
            0x017D => result.push(0x8E), // Latin capital letter Z with caron
            0x2018 => result.push(0x91), // Left single quotation mark
            0x2019 => result.push(0x92), // Right single quotation mark
            0x201C => result.push(0x93), // Left double quotation mark
            0x201D => result.push(0x94), // Right double quotation mark
            0x2022 => result.push(0x95), // Bullet
            0x2013 => result.push(0x96), // En dash
            0x2014 => result.push(0x97), // Em dash
            0x02DC => result.push(0x98), // Small tilde
            0x2122 => result.push(0x99), // Trade mark sign
            0x0161 => result.push(0x9A), // Latin small letter s with caron
            0x203A => result.push(0x9B), // Single right-pointing angle quotation mark
            0x0153 => result.push(0x9C), // Latin small ligature oe
            0x017E => result.push(0x9E), // Latin small letter z with caron
            0x0178 => result.push(0x9F), // Latin capital letter Y with diaeresis
            // Anything else is not representable in WinAnsi — replace with '?'
            _ => result.push(b'?'),
        }
    }
    result
}

/// Encode a UTF-8 string for use in a PDF text operator (Tj).
///
/// Converts to WinAnsi encoding, then produces a `String` where:
/// - ASCII printable bytes (0x20..=0x7E), except `\`, `(`, `)`, are kept as-is
/// - `\`, `(`, `)` are escaped as `\\`, `\(`, `\)`
/// - All other bytes (0x00..=0x1F, 0x7F..=0xFF) are written as octal escapes `\NNN`
///
/// The returned string is safe to embed in a PDF content stream as `(encoded) Tj`.
fn encode_pdf_text(text: &str) -> String {
    let winansi = utf8_to_winansi(text);
    let mut result = String::with_capacity(winansi.len() * 2);
    for &b in &winansi {
        match b {
            b'\\' => result.push_str("\\\\"),
            b'(' => result.push_str("\\("),
            b')' => result.push_str("\\)"),
            0x20..=0x7E => result.push(b as char),
            _ => {
                // Octal escape: \NNN (3-digit, zero-padded)
                result.push_str(&format!("\\{:03o}", b));
            }
        }
    }
    result
}

fn escape_pdf_string(s: &str) -> String {
    s.replace('\\', "\\\\")
        .replace('(', "\\(")
        .replace(')', "\\)")
}

/// A reference to an image XObject used on a page.
struct ImageRef {
    name: String,
    obj_id: usize,
}

/// A custom TrueType font entry for the PDF font dictionary.
struct CustomFontEntry {
    /// Sanitized PDF name used as the resource key (e.g., "MyFont").
    pdf_name: String,
    /// Object ID of the font object.
    font_obj_id: usize,
}

/// Minimal PDF writer that produces valid PDF files.
struct PdfWriter {
    objects: Vec<String>,
    /// Raw binary objects stored separately (index corresponds to objects slot).
    binary_objects: std::collections::HashMap<usize, Vec<u8>>,
    page_ids: Vec<usize>,
    /// Annotation object IDs grouped by page index.
    page_annotations: Vec<Vec<usize>>,
    /// Image references grouped by page index.
    page_images: Vec<Vec<ImageRef>>,
    /// ExtGState entries (name, opacity) grouped by page index.
    page_ext_gstates: Vec<Vec<(String, f32)>>,
    /// Shading dictionary entries grouped by page index.
    page_shadings: Vec<Vec<ShadingEntry>>,
    /// Custom TrueType font entries.
    custom_font_entries: Vec<CustomFontEntry>,
}

impl PdfWriter {
    fn new() -> Self {
        Self {
            objects: Vec::new(),
            binary_objects: std::collections::HashMap::new(),
            page_ids: Vec::new(),
            page_annotations: Vec::new(),
            page_images: Vec::new(),
            page_ext_gstates: Vec::new(),
            page_shadings: Vec::new(),
            custom_font_entries: Vec::new(),
        }
    }

    fn next_id(&self) -> usize {
        self.objects.len() + 1
    }

    /// Add an image as a PDF XObject and return its object ID.
    fn add_image_object(
        &mut self,
        data: &[u8],
        width: u32,
        height: u32,
        format: ImageFormat,
        png_metadata: Option<&PngMetadata>,
    ) -> usize {
        let id = self.next_id();
        let header = match format {
            ImageFormat::Jpeg => {
                format!(
                    "{id} 0 obj\n<< /Type /XObject /Subtype /Image /Width {width} /Height {height} /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /DCTDecode /Length {len} >>\nstream\n",
                    len = data.len(),
                )
            }
            ImageFormat::Png => {
                let meta = png_metadata.expect("PNG metadata required for PNG images");
                let color_space = match meta.channels {
                    1 | 2 => "/DeviceGray",
                    _ => "/DeviceRGB",
                };
                format!(
                    "{id} 0 obj\n<< /Type /XObject /Subtype /Image /Width {width} /Height {height} /ColorSpace {color_space} /BitsPerComponent {bpc} /Filter /FlateDecode /DecodeParms << /Predictor 15 /Columns {width} /Colors {channels} /BitsPerComponent {bpc} >> /Length {len} >>\nstream\n",
                    bpc = meta.bit_depth,
                    channels = meta.channels,
                    len = data.len(),
                )
            }
        };
        self.objects.push(header);
        self.binary_objects.insert(id, data.to_vec());
        id
    }

    /// Embed a TrueType font and return the PDF resource name to reference it.
    fn add_ttf_font(&mut self, name: &str, ttf: &TtfFont) -> String {
        let pdf_name = sanitize_pdf_name(name);

        // 1. Font stream: embed the full TTF data
        let stream_id = self.next_id();
        let data = &ttf.data;
        let header = format!(
            "{stream_id} 0 obj\n<< /Length {} /Length1 {} >>\nstream\n",
            data.len(),
            data.len(),
        );
        self.objects.push(header);
        self.binary_objects.insert(stream_id, data.clone());

        // 2. FontDescriptor
        let descriptor_id = self.next_id();
        let ascent_pdf = (ttf.ascent as i32 * 1000) / ttf.units_per_em as i32;
        let descent_pdf = (ttf.descent as i32 * 1000) / ttf.units_per_em as i32;
        let bbox_pdf = [
            (ttf.bbox[0] as i32 * 1000) / ttf.units_per_em as i32,
            (ttf.bbox[1] as i32 * 1000) / ttf.units_per_em as i32,
            (ttf.bbox[2] as i32 * 1000) / ttf.units_per_em as i32,
            (ttf.bbox[3] as i32 * 1000) / ttf.units_per_em as i32,
        ];
        self.objects.push(format!(
            "{descriptor_id} 0 obj\n<< /Type /FontDescriptor /FontName /{pdf_name} /Flags {flags} /FontBBox [{b0} {b1} {b2} {b3}] /Ascent {ascent} /Descent {descent} /ItalicAngle 0 /CapHeight {ascent} /StemV 80 /FontFile2 {stream_id} 0 R >>\nendobj",
            flags = ttf.flags,
            b0 = bbox_pdf[0],
            b1 = bbox_pdf[1],
            b2 = bbox_pdf[2],
            b3 = bbox_pdf[3],
            ascent = ascent_pdf,
            descent = descent_pdf,
        ));

        // 3. Widths array for WinAnsiEncoding range (32..255)
        let first_char = 32u16;
        let last_char = 255u16;
        let mut widths = Vec::new();
        for c in first_char..=last_char {
            widths.push(ttf.char_width_pdf(c));
        }
        let widths_str: String = widths
            .iter()
            .map(|w| w.to_string())
            .collect::<Vec<_>>()
            .join(" ");

        // 4. Font object
        let font_id = self.next_id();
        self.objects.push(format!(
            "{font_id} 0 obj\n<< /Type /Font /Subtype /TrueType /BaseFont /{pdf_name} /Encoding /WinAnsiEncoding /FirstChar {first_char} /LastChar {last_char} /Widths [{widths_str}] /FontDescriptor {descriptor_id} 0 R >>\nendobj",
        ));

        self.custom_font_entries.push(CustomFontEntry {
            pdf_name: pdf_name.clone(),
            font_obj_id: font_id,
        });

        pdf_name
    }

    #[allow(clippy::too_many_arguments)]
    fn add_page(
        &mut self,
        width: f32,
        height: f32,
        content: &str,
        annotations: Vec<LinkAnnotation>,
        images: Vec<ImageRef>,
        ext_gstates: Vec<(String, f32)>,
        shadings: Vec<ShadingEntry>,
    ) {
        // Content stream
        let stream = content.as_bytes();
        let content_id = self.next_id();
        self.objects.push(format!(
            "{content_id} 0 obj\n<< /Length {} >>\nstream\n{content}\nendstream\nendobj",
            stream.len(),
        ));

        // Annotation objects
        let mut annot_ids = Vec::new();
        for annot in &annotations {
            let annot_id = self.next_id();
            self.objects.push(format!(
                "{annot_id} 0 obj\n<< /Type /Annot /Subtype /Link /Rect [{x1} {y1} {x2} {y2}] /Border [0 0 0] /A << /Type /Action /S /URI /URI ({uri}) >> >>\nendobj",
                x1 = annot.x1,
                y1 = annot.y1,
                x2 = annot.x2,
                y2 = annot.y2,
                uri = escape_pdf_string(&annot.url),
            ));
            annot_ids.push(annot_id);
        }

        // Page object (placeholder — will be updated in finish())
        let page_id = self.next_id();
        self.objects.push(format!(
            "{page_id} 0 obj\n<< /Type /Page /MediaBox [0 0 {width} {height}] /Contents {content_id} 0 R >>\nendobj",
        ));

        self.page_ids.push(page_id);
        self.page_annotations.push(annot_ids);
        self.page_images.push(images);
        self.page_ext_gstates.push(ext_gstates);
        self.page_shadings.push(shadings);
    }

    fn finish_to_writer<W: std::io::Write>(
        self,
        out: &mut W,
        bookmarks: &[BookmarkEntry],
    ) -> Result<(), IronpressError> {
        let mut bytes_written: usize = 0;
        out.write_all(b"%PDF-1.4\n")?;
        bytes_written += b"%PDF-1.4\n".len();

        // Font objects
        let font_base_id = self.objects.len() + 1;
        let font_names = [
            // Helvetica (sans-serif)
            "Helvetica",
            "Helvetica-Bold",
            "Helvetica-Oblique",
            "Helvetica-BoldOblique",
            // Times Roman (serif)
            "Times-Roman",
            "Times-Bold",
            "Times-Italic",
            "Times-BoldItalic",
            // Courier (monospace)
            "Courier",
            "Courier-Bold",
            "Courier-Oblique",
            "Courier-BoldOblique",
        ];

        let mut all_objects: Vec<String> = self.objects.clone();

        for (i, name) in font_names.iter().enumerate() {
            let id = font_base_id + i;
            all_objects.push(format!(
                "{id} 0 obj\n<< /Type /Font /Subtype /Type1 /BaseFont /{name} /Encoding /WinAnsiEncoding >>\nendobj",
            ));
        }

        // Font dictionary (standard + custom fonts)
        let font_dict_id = font_base_id + font_names.len();
        let mut font_entries: Vec<String> = font_names
            .iter()
            .enumerate()
            .map(|(i, name)| format!("/{name} {} 0 R", font_base_id + i))
            .collect();
        // Add custom font entries
        for entry in &self.custom_font_entries {
            font_entries.push(format!("/{} {} 0 R", entry.pdf_name, entry.font_obj_id));
        }
        let font_entries_str = font_entries.join(" ");
        all_objects.push(format!(
            "{font_dict_id} 0 obj\n<< {font_entries_str} >>\nendobj",
        ));

        // Collect all image object IDs used across all pages
        let mut all_image_refs: Vec<(&str, usize)> = Vec::new();
        for page_imgs in &self.page_images {
            for img in page_imgs {
                if !all_image_refs.iter().any(|(_, id)| *id == img.obj_id) {
                    all_image_refs.push((&img.name, img.obj_id));
                }
            }
        }

        // Collect unique ExtGState entries across all pages
        let mut gs_entries: Vec<(String, f32)> = Vec::new();
        for page_gs in &self.page_ext_gstates {
            for (name, opacity) in page_gs {
                if !gs_entries.iter().any(|(n, _)| n == name) {
                    gs_entries.push((name.clone(), *opacity));
                }
            }
        }
        let has_opacity = !gs_entries.is_empty();

        // Add ExtGState objects if needed
        let mut gs_obj_refs: Vec<(String, usize)> = Vec::new();
        if has_opacity {
            // GSDefault (opacity 1.0)
            let default_gs_id = all_objects.len() + 1;
            all_objects.push(format!(
                "{default_gs_id} 0 obj\n<< /Type /ExtGState /ca 1 /CA 1 >>\nendobj"
            ));
            gs_obj_refs.push(("GSDefault".to_string(), default_gs_id));

            // Per-element ExtGState objects
            for (name, opacity) in &gs_entries {
                let gs_id = all_objects.len() + 1;
                all_objects.push(format!(
                    "{gs_id} 0 obj\n<< /Type /ExtGState /ca {opacity} /CA {opacity} >>\nendobj"
                ));
                gs_obj_refs.push((name.clone(), gs_id));
            }
        }

        // Add Shading objects
        let mut shading_obj_refs: Vec<(String, usize)> = Vec::new();
        for page_sh in &self.page_shadings {
            for entry in page_sh {
                let sh_id = all_objects.len() + 1;
                let function_str = build_shading_function(&entry.stops);
                let coords_str = if entry.shading_type == 2 {
                    // Axial: only first 4 coords
                    format!(
                        "{} {} {} {}",
                        entry.coords[0], entry.coords[1], entry.coords[2], entry.coords[3]
                    )
                } else {
                    // Radial: all 6 coords
                    format!(
                        "{} {} {} {} {} {}",
                        entry.coords[0],
                        entry.coords[1],
                        entry.coords[2],
                        entry.coords[3],
                        entry.coords[4],
                        entry.coords[5]
                    )
                };
                all_objects.push(format!(
                    "{sh_id} 0 obj\n<< /ShadingType {} /ColorSpace /DeviceRGB /Coords [{coords_str}] /Function {function_str} /Extend [true true] >>\nendobj",
                    entry.shading_type,
                ));
                shading_obj_refs.push((entry.name.clone(), sh_id));
            }
        }

        // Resources dictionary
        let resources_id = all_objects.len() + 1;
        let mut resource_parts = format!("/Font {font_dict_id} 0 R");

        if !all_image_refs.is_empty() {
            let xobj_entries: String = all_image_refs
                .iter()
                .map(|(name, id)| format!("/{name} {id} 0 R"))
                .collect::<Vec<_>>()
                .join(" ");
            resource_parts.push_str(&format!(" /XObject << {xobj_entries} >>"));
        }

        if has_opacity {
            let gs_dict: String = gs_obj_refs
                .iter()
                .map(|(name, id)| format!("/{name} {id} 0 R"))
                .collect::<Vec<_>>()
                .join(" ");
            resource_parts.push_str(&format!(" /ExtGState << {gs_dict} >>"));
        }

        if !shading_obj_refs.is_empty() {
            let shading_dict: String = shading_obj_refs
                .iter()
                .map(|(name, id)| format!("/{name} {id} 0 R"))
                .collect::<Vec<_>>()
                .join(" ");
            resource_parts.push_str(&format!(" /Shading << {shading_dict} >>"));
        }

        all_objects.push(format!(
            "{resources_id} 0 obj\n<< {resource_parts} >>\nendobj",
        ));

        // Update page objects to include parent, resources, and annotations
        let pages_id = resources_id + 1;
        for (idx, &page_id) in self.page_ids.iter().enumerate() {
            let obj = &mut all_objects[page_id - 1];
            let annot_ids = &self.page_annotations[idx];
            let mut extra = format!("/Parent {pages_id} 0 R /Resources {resources_id} 0 R");
            if !annot_ids.is_empty() {
                let annots_str: String = annot_ids
                    .iter()
                    .map(|id| format!("{id} 0 R"))
                    .collect::<Vec<_>>()
                    .join(" ");
                extra.push_str(&format!(" /Annots [{annots_str}]"));
            }
            *obj = obj.replace("/Contents", &format!("{extra} /Contents"));
        }

        // Pages object
        let kids: String = self
            .page_ids
            .iter()
            .map(|id| format!("{id} 0 R"))
            .collect::<Vec<_>>()
            .join(" ");
        all_objects.push(format!(
            "{pages_id} 0 obj\n<< /Type /Pages /Kids [{kids}] /Count {} >>\nendobj",
            self.page_ids.len(),
        ));

        // Outlines (PDF bookmarks from headings)
        let outlines_ref = if bookmarks.is_empty() {
            String::new()
        } else {
            let count = bookmarks.len();
            // Outline root object
            let root_id = all_objects.len() + 1;
            let first_entry_id = root_id + 1;
            let last_entry_id = first_entry_id + count - 1;
            all_objects.push(format!(
                "{root_id} 0 obj\n<< /Type /Outlines /First {first_entry_id} 0 R /Last {last_entry_id} 0 R /Count {count} >>\nendobj",
            ));

            // Outline entry objects (flat list, linked via Prev/Next)
            for (i, bm) in bookmarks.iter().enumerate() {
                let entry_id = first_entry_id + i;
                let page_obj_id = self.page_ids.get(bm.page_index).copied().unwrap_or(1);

                let mut entry = format!(
                    "{entry_id} 0 obj\n<< /Title ({title}) /Parent {root_id} 0 R /Dest [{page_obj_id} 0 R /XYZ 0 {dest_y} 0]",
                    title = escape_pdf_string(&bm.title),
                    dest_y = bm.y_pos,
                );
                if i > 0 {
                    entry.push_str(&format!(" /Prev {} 0 R", first_entry_id + i - 1));
                }
                if i + 1 < count {
                    entry.push_str(&format!(" /Next {} 0 R", first_entry_id + i + 1));
                }
                entry.push_str(" >>\nendobj");
                all_objects.push(entry);
            }

            format!(" /Outlines {root_id} 0 R /PageMode /UseOutlines")
        };

        // Catalog
        let catalog_id = all_objects.len() + 1;
        all_objects.push(format!(
            "{catalog_id} 0 obj\n<< /Type /Catalog /Pages {pages_id} 0 R{outlines_ref} >>\nendobj",
        ));

        // Write objects and track offsets for xref
        // Binary objects (images) need special handling
        let mut offsets = Vec::new();
        for (idx, obj_str) in all_objects.iter().enumerate() {
            offsets.push(bytes_written);
            let obj_id = idx + 1;
            if let Some(bin_data) = self.binary_objects.get(&obj_id) {
                // Write the header (stored in obj_str), then binary data, then endstream/endobj
                out.write_all(obj_str.as_bytes())?;
                bytes_written += obj_str.len();
                out.write_all(bin_data)?;
                bytes_written += bin_data.len();
                out.write_all(b"\nendstream\nendobj\n")?;
                bytes_written += b"\nendstream\nendobj\n".len();
            } else {
                out.write_all(obj_str.as_bytes())?;
                bytes_written += obj_str.len();
                out.write_all(b"\n")?;
                bytes_written += 1;
            }
        }

        // Cross-reference table
        let xref_offset = bytes_written;
        let xref_header = format!("xref\n0 {}\n", all_objects.len() + 1);
        out.write_all(xref_header.as_bytes())?;
        out.write_all(b"0000000000 65535 f \n")?;
        for offset in &offsets {
            let entry = format!("{:010} 00000 n \n", offset);
            out.write_all(entry.as_bytes())?;
        }

        // Trailer
        let trailer = format!(
            "trailer\n<< /Size {} /Root {catalog_id} 0 R >>\nstartxref\n{xref_offset}\n%%EOF\n",
            all_objects.len() + 1,
        );
        out.write_all(trailer.as_bytes())?;

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::layout::engine::{LayoutBorder, layout};
    use crate::parser::html::parse_html;

    #[test]
    fn render_simple_pdf() {
        let nodes = parse_html("<p>Hello World</p>").unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();

        // Valid PDF starts with %PDF
        assert!(pdf.starts_with(b"%PDF-1.4"));
        // Valid PDF ends with %%EOF
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("%%EOF"));
        // Contains Helvetica font
        assert!(content.contains("/Helvetica"));
    }

    #[test]
    fn render_bold_italic() {
        let nodes = parse_html("<p><strong>Bold</strong> and <em>italic</em></p>").unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("/Helvetica-Bold"));
        assert!(content.contains("/Helvetica-Oblique"));
    }

    #[test]
    fn render_empty_document() {
        let nodes = parse_html("").unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        assert!(pdf.starts_with(b"%PDF-1.4"));
    }

    #[test]
    fn pdf_string_escaping() {
        assert_eq!(escape_pdf_string("hello"), "hello");
        assert_eq!(escape_pdf_string("(test)"), "\\(test\\)");
        assert_eq!(escape_pdf_string("back\\slash"), "back\\\\slash");
    }

    #[test]
    fn render_background_color() {
        let html = r#"<pre>code here</pre>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        // Pre has gray background — PDF should contain rectangle fill commands
        assert!(content.contains("re\nf\n") || content.contains("re"));
    }

    #[test]
    fn render_center_align() {
        let html = r#"<p style="text-align: center">Centered</p>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn render_right_align() {
        let html = r#"<p style="text-align: right">Right</p>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn render_underline() {
        let html = "<p><u>Underlined text</u></p>";
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        // Underline draws a line with stroke command
        assert!(content.contains(" l\nS\n"));
    }

    #[test]
    fn render_bold_italic_combined() {
        let html = "<p><strong><em>Bold Italic</em></strong></p>";
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("/Helvetica-BoldOblique"));
    }

    #[test]
    fn render_page_break_in_content() {
        let html = r#"<p>Page 1</p><div style="page-break-before: always"><p>Page 2</p></div>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        // Should have multiple page objects
        assert!(content.matches("/Type /Page").count() >= 2);
    }

    #[test]
    fn render_colored_text() {
        let html = r#"<p style="color: red">Red text</p>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("1 0 0 rg")); // red in PDF
    }

    #[test]
    fn render_table_basic() {
        let html = r#"
            <table>
                <tr><th>Name</th><th>Age</th></tr>
                <tr><td>Alice</td><td>30</td></tr>
            </table>
        "#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        // No default cell borders — only CSS-specified borders produce strokes
        assert!(content.contains("Name"));
        assert!(content.contains("Alice"));
    }

    #[test]
    fn render_table_with_background() {
        let html = r#"
            <table>
                <tr><td style="background-color: yellow">Highlighted</td></tr>
            </table>
        "#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        // Background fill command
        assert!(content.contains("re\nf\n"));
    }

    #[test]
    fn render_empty_line_skipped() {
        let html = "<p>Above</p><br><p>Below</p>";
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("Above"));
        assert!(content.contains("Below"));
    }

    #[test]
    fn render_empty_run_skipped() {
        let html = "<p>Text</p>";
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn render_page_break_element() {
        let html = r#"<p>Page 1</p><div style="page-break-before: always"><p>Page 2</p></div>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        // Multiple pages rendered
        assert!(content.matches("/Type /Page ").count() >= 2);
    }

    #[test]
    fn render_cell_text_empty_line_skipped() {
        let html = r#"<table><tr><td></td><td>Content</td></tr></table>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("Content"));
    }

    #[test]
    fn render_horizontal_rule() {
        let html = "<p>Above</p><hr><p>Below</p>";
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        // HR draws a line with stroke
        assert!(content.contains(" l\nS\n"));
    }

    #[test]
    fn render_input_element() {
        let pdf = crate::html_to_pdf(r#"<input type="text" value="Hello">"#).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
        assert!(pdf.len() > 100);
    }

    #[test]
    fn render_input_with_placeholder() {
        let pdf = crate::html_to_pdf(r#"<input placeholder="Type here...">"#).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn render_select_element() {
        let pdf =
            crate::html_to_pdf(r#"<select><option>A</option><option>B</option></select>"#).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
        assert!(pdf.len() > 100);
    }

    #[test]
    fn render_textarea_element() {
        let pdf = crate::html_to_pdf(r#"<textarea>Hello World</textarea>"#).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
        assert!(pdf.len() > 100);
    }

    #[test]
    fn render_video_element() {
        let pdf = crate::html_to_pdf(r#"<video width="320" height="240"></video>"#).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
        assert!(pdf.len() > 100);
    }

    #[test]
    fn render_audio_element() {
        let pdf = crate::html_to_pdf(r#"<audio></audio>"#).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
        assert!(pdf.len() > 100);
    }

    #[test]
    fn render_progress_element() {
        let pdf = crate::html_to_pdf(r#"<progress value="0.7" max="1"></progress>"#).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
        let content = String::from_utf8_lossy(&pdf);
        // Progress bar draws rectangles (track + fill + border)
        assert!(
            content.contains("re\nf\n"),
            "Expected filled rectangles for progress bar"
        );
    }

    #[test]
    fn render_progress_empty() {
        let pdf = crate::html_to_pdf(r#"<progress value="0" max="1"></progress>"#).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn render_meter_element() {
        let pdf = crate::html_to_pdf(r#"<meter value="0.5" max="1"></meter>"#).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
        let content = String::from_utf8_lossy(&pdf);
        assert!(
            content.contains("re\nf\n"),
            "Expected filled rectangles for meter bar"
        );
    }

    #[test]
    fn render_meter_low_value() {
        let pdf = crate::html_to_pdf(r#"<meter value="5" max="100" low="25" high="75"></meter>"#)
            .unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn render_form_controls_styled() {
        let html = r#"
            <input type="text" value="styled" style="width: 200px; border: 2px solid blue; background-color: #eee">
        "#;
        let pdf = crate::html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn render_mixed_form_and_text() {
        let html = r#"
            <p>Fill in the form:</p>
            <input type="text" value="John">
            <p>Select country:</p>
            <select><option>France</option></select>
            <p>Comments:</p>
            <textarea>Great product!</textarea>
            <p>Rating:</p>
            <progress value="80" max="100"></progress>
        "#;
        let pdf = crate::html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
        assert!(pdf.len() > 500);
    }

    #[test]
    fn render_pdf_bookmarks_from_headings() {
        let html = "<h1>Chapter 1</h1><p>Content</p><h2>Section 1.1</h2><p>More</p>";
        let pdf = crate::html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("/Type /Outlines"), "Expected PDF outlines");
        assert!(
            content.contains("Chapter 1"),
            "Expected heading text in bookmark"
        );
        assert!(
            content.contains("Section 1.1"),
            "Expected h2 heading in bookmark"
        );
    }

    #[test]
    fn render_pdf_no_bookmarks_without_headings() {
        let html = "<p>No headings here</p>";
        let pdf = crate::html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(
            !content.contains("/Type /Outlines"),
            "Should not have outlines without headings"
        );
    }

    #[test]
    fn render_pdf_bookmarks_multi_page() {
        let html = r#"
            <h1>Page 1 Title</h1>
            <p>Content</p>
            <div style="page-break-before: always">
                <h1>Page 2 Title</h1>
                <p>More content</p>
            </div>
        "#;
        let pdf = crate::html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("Page 1 Title"));
        assert!(content.contains("Page 2 Title"));
        assert!(content.contains("/Type /Outlines"));
    }

    #[test]
    fn render_pdf_bookmarks_all_levels() {
        let html = "<h1>H1</h1><h2>H2</h2><h3>H3</h3><h4>H4</h4><h5>H5</h5><h6>H6</h6>";
        let pdf = crate::html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("/Count 6"), "Expected 6 outline entries");
    }

    #[test]
    fn render_page_footer() {
        let pdf = crate::HtmlConverter::new()
            .footer("Page {page} of {pages}")
            .convert("<h1>Title</h1><p>Content</p>")
            .unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(
            content.contains("Page 1 of 1"),
            "Expected footer with page numbers"
        );
    }

    #[test]
    fn render_page_header() {
        let pdf = crate::HtmlConverter::new()
            .header("My Document")
            .convert("<p>Content</p>")
            .unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(
            content.contains("My Document"),
            "Expected header text in PDF"
        );
    }

    #[test]
    fn render_header_and_footer() {
        let pdf = crate::HtmlConverter::new()
            .header("Report Title")
            .footer("Page {page} of {pages}")
            .convert("<p>Page 1</p>")
            .unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("Report Title"));
        assert!(content.contains("Page 1 of 1"));
    }

    #[test]
    fn render_footer_multi_page() {
        let html = r#"
            <p>First page</p>
            <div style="page-break-before: always"><p>Second page</p></div>
        "#;
        let pdf = crate::HtmlConverter::new()
            .footer("Page {page} of {pages}")
            .convert(html)
            .unwrap();
        let content = String::from_utf8_lossy(&pdf);
        // Verify page number substitution works (at least page 1 and last page are present)
        assert!(content.contains("Page 1 of"), "Expected footer with page 1");
        assert!(content.contains("Page 2 of"), "Expected footer with page 2");
    }

    #[test]
    fn render_no_header_footer_by_default() {
        let pdf = crate::html_to_pdf("<p>Test</p>").unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(!content.contains("Page 1 of"));
    }

    #[test]
    fn render_header_only_no_footer() {
        let pdf = crate::HtmlConverter::new()
            .header("Header Only")
            .convert("<p>Content</p>")
            .unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("Header Only"));
        assert!(!content.contains("Page 1"));
    }

    #[test]
    fn render_footer_only_no_header() {
        let pdf = crate::HtmlConverter::new()
            .footer("{page}/{pages}")
            .convert("<p>Content</p>")
            .unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("1/1"));
    }

    #[test]
    fn render_progress_bar_zero_fraction() {
        let html = r#"<progress value="0" max="1"></progress>"#;
        let pdf = crate::html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        // Track is drawn but fill is skipped when fraction=0
        assert!(content.contains("re\nf\n")); // track rect
        assert!(content.contains("re\nS\n")); // border stroke
    }

    #[test]
    fn render_progress_bar_full_fraction() {
        let html = r#"<progress value="1" max="1"></progress>"#;
        let pdf = crate::html_to_pdf(html).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn render_bookmark_special_chars() {
        let html = r#"<h1>Title with (parens) &amp; "quotes"</h1>"#;
        let pdf = crate::html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("/Type /Outlines"));
    }

    #[test]
    fn render_single_heading_bookmark() {
        let html = "<h1>Only One</h1><p>Text</p>";
        let pdf = crate::html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("/Count 1"));
        assert!(content.contains("Only One"));
    }

    #[test]
    fn render_link_annotation() {
        let html = r#"<p><a href="https://example.com">Click here</a></p>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        // Should contain a Link annotation with the URI
        assert!(
            content.contains("/Subtype /Link"),
            "PDF should contain a Link annotation"
        );
        assert!(
            content.contains("/S /URI"),
            "PDF should contain a URI action"
        );
        assert!(
            content.contains("https://example.com"),
            "PDF should contain the link URL"
        );
        // The page object should reference annotations
        assert!(
            content.contains("/Annots ["),
            "Page should have an /Annots array"
        );
    }

    #[test]
    fn render_link_no_annotation_without_href() {
        // An <a> tag without href should not produce an annotation
        let html = "<p><a>No link</a></p>";
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(
            !content.contains("/Subtype /Link"),
            "PDF should not contain a Link annotation without href"
        );
    }

    #[test]
    fn render_link_url_escaped() {
        // URL with parentheses should be properly escaped
        let html = r#"<p><a href="https://example.com/page(1)">Link</a></p>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("/Subtype /Link"));
        assert!(content.contains(r"https://example.com/page\(1\)"));
    }

    #[test]
    fn render_multiple_links() {
        let html =
            r#"<p><a href="https://one.com">One</a> and <a href="https://two.com">Two</a></p>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("https://one.com"));
        assert!(content.contains("https://two.com"));
        // Should have two Link annotations
        assert_eq!(
            content.matches("/Subtype /Link").count(),
            2,
            "Should have exactly 2 link annotations"
        );
    }

    #[test]
    fn render_page_without_links_has_no_annots() {
        let html = "<p>No links here</p>";
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(
            !content.contains("/Annots"),
            "Page without links should not have /Annots"
        );
    }

    #[test]
    fn render_image_contains_xobject() {
        // Use a data URI with a tiny JPEG-like payload
        let html = r#"<img src="data:image/jpeg;base64,/9j/4AAC/9k=" width="100" height="80">"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(
            content.contains("/XObject"),
            "PDF with image should contain /XObject in resources"
        );
        assert!(
            content.contains("/Subtype /Image"),
            "PDF should contain image XObject"
        );
        assert!(
            content.contains("/Filter /DCTDecode"),
            "JPEG image should use DCTDecode filter"
        );
        assert!(
            content.contains("Do"),
            "PDF should contain Do operator to draw image"
        );
    }

    #[test]
    fn render_no_image_no_xobject() {
        let html = "<p>No images here</p>";
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(
            !content.contains("/XObject"),
            "PDF without images should not contain /XObject"
        );
    }

    #[test]
    fn render_border_draws_rectangle_stroke() {
        let html = r#"<div style="border: 1px solid black">Bordered text</div>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        // Border draws a rectangle with stroke (re + S)
        assert!(
            content.contains("re\nS\n"),
            "PDF should contain rectangle stroke for border"
        );
        // The stroke color should be black (0 0 0 RG)
        assert!(
            content.contains("0 0 0 RG"),
            "Border stroke color should be black"
        );
    }

    #[test]
    fn render_border_with_custom_color() {
        let html = r#"<div style="border: 2px solid red">Red border</div>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        // Red border: 1 0 0 RG
        assert!(
            content.contains("1 0 0 RG"),
            "Border stroke color should be red"
        );
        assert!(
            content.contains("re\nS\n"),
            "PDF should contain rectangle stroke for border"
        );
    }

    #[test]
    fn render_times_roman_font_family() {
        let html = r#"<p style="font-family: serif">Serif text</p>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(
            content.contains("/Times-Roman"),
            "PDF should use Times-Roman for serif font-family"
        );
    }

    #[test]
    fn render_times_bold_italic() {
        let html =
            r#"<p style="font-family: serif"><strong><em>Bold Italic Serif</em></strong></p>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(
            content.contains("/Times-BoldItalic"),
            "PDF should use Times-BoldItalic for bold italic serif"
        );
    }

    #[test]
    fn render_times_bold() {
        let html = r#"<p style="font-family: times"><strong>Bold Serif</strong></p>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(
            content.contains("/Times-Bold"),
            "PDF should use Times-Bold for bold serif"
        );
    }

    #[test]
    fn render_times_italic() {
        let html = r#"<p style="font-family: serif"><em>Italic Serif</em></p>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(
            content.contains("/Times-Italic"),
            "PDF should use Times-Italic for italic serif"
        );
    }

    #[test]
    fn render_courier_font_family() {
        let html = r#"<p style="font-family: monospace">Monospace text</p>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(
            content.contains("/Courier ") || content.contains("/Courier\n"),
            "PDF should use Courier for monospace font-family"
        );
    }

    #[test]
    fn render_courier_bold_italic() {
        let html =
            r#"<p style="font-family: courier"><strong><em>Bold Italic Mono</em></strong></p>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(
            content.contains("/Courier-BoldOblique"),
            "PDF should use Courier-BoldOblique for bold italic monospace"
        );
    }

    #[test]
    fn render_courier_bold() {
        let html = r#"<p style="font-family: monospace"><strong>Bold Mono</strong></p>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(
            content.contains("/Courier-Bold"),
            "PDF should use Courier-Bold for bold monospace"
        );
    }

    #[test]
    fn render_courier_oblique() {
        let html = r#"<p style="font-family: courier"><em>Italic Mono</em></p>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(
            content.contains("/Courier-Oblique"),
            "PDF should use Courier-Oblique for italic monospace"
        );
    }

    #[test]
    fn render_font_family_via_stylesheet() {
        let html = r#"
            <html>
            <head><style>p { font-family: serif }</style></head>
            <body><p>Styled serif</p></body>
            </html>
        "#;
        let pdf = crate::html_to_pdf(html).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(
            content.contains("/Times-Roman"),
            "Stylesheet font-family should produce Times-Roman"
        );
    }

    #[test]
    fn render_jpeg_image_contains_xobject() {
        // Use a data URI with a tiny JPEG-like payload
        let html = r#"<img src="data:image/jpeg;base64,/9j/4AAC/9k=" width="100" height="80">"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(
            content.contains("/XObject"),
            "PDF with image should contain /XObject in resources"
        );
        assert!(
            content.contains("/Subtype /Image"),
            "PDF should contain image XObject"
        );
        assert!(
            content.contains("/Filter /DCTDecode"),
            "JPEG image should use DCTDecode filter"
        );
        assert!(
            content.contains("Do"),
            "PDF should contain Do operator to draw image"
        );
    }

    #[test]
    fn render_png_image_contains_flatedecode() {
        // Build a minimal valid PNG as base64 data URI
        let png_bytes = build_minimal_test_png();
        let b64 = simple_base64_encode_test(&png_bytes);
        let html = format!(r#"<img src="data:image/png;base64,{b64}" width="100" height="100">"#,);
        let nodes = parse_html(&html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(
            content.contains("/XObject"),
            "PDF with PNG image should contain /XObject in resources"
        );
        assert!(
            content.contains("/Subtype /Image"),
            "PDF should contain image XObject"
        );
        assert!(
            content.contains("/Filter /FlateDecode"),
            "PNG image should use FlateDecode filter"
        );
        assert!(
            content.contains("/Predictor 15"),
            "PNG image should have Predictor 15 in DecodeParms"
        );
        assert!(
            content.contains("/Colors 3"),
            "RGB PNG should have Colors 3"
        );
        assert!(
            content.contains("Do"),
            "PDF should contain Do operator to draw image"
        );
    }

    #[test]
    fn render_png_grayscale_image() {
        let png_bytes = build_test_png_with_color_type(0); // Grayscale
        let b64 = simple_base64_encode_test(&png_bytes);
        let html = format!(r#"<img src="data:image/png;base64,{b64}" width="50" height="50">"#,);
        let nodes = parse_html(&html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("/Filter /FlateDecode"));
        assert!(content.contains("/ColorSpace /DeviceGray"));
        assert!(content.contains("/Colors 1"));
    }

    /// Build a minimal valid PNG (1x1 RGB, 8-bit).
    fn build_minimal_test_png() -> Vec<u8> {
        build_test_png_with_color_type(2) // RGB
    }

    fn build_test_png_with_color_type(color_type: u8) -> Vec<u8> {
        let mut png = Vec::new();
        // PNG signature
        png.extend_from_slice(&[137, 80, 78, 71, 13, 10, 26, 10]);
        // IHDR chunk (13 bytes data)
        let mut ihdr = Vec::new();
        ihdr.extend_from_slice(&1u32.to_be_bytes()); // width
        ihdr.extend_from_slice(&1u32.to_be_bytes()); // height
        ihdr.push(8); // bit depth
        ihdr.push(color_type);
        ihdr.push(0); // compression
        ihdr.push(0); // filter
        ihdr.push(0); // interlace
        append_png_chunk(&mut png, b"IHDR", &ihdr);
        // IDAT chunk with dummy zlib-compressed data
        let idat = [
            0x78, 0x01, 0x62, 0x60, 0x60, 0x60, 0x00, 0x00, 0x00, 0x04, 0x00, 0x01,
        ];
        append_png_chunk(&mut png, b"IDAT", &idat);
        // IEND
        append_png_chunk(&mut png, b"IEND", &[]);
        png
    }

    fn append_png_chunk(buf: &mut Vec<u8>, chunk_type: &[u8; 4], data: &[u8]) {
        buf.extend_from_slice(&(data.len() as u32).to_be_bytes());
        buf.extend_from_slice(chunk_type);
        buf.extend_from_slice(data);
        buf.extend_from_slice(&[0, 0, 0, 0]); // CRC placeholder
    }

    fn simple_base64_encode_test(data: &[u8]) -> String {
        const CHARS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        let mut result = String::new();
        let mut i = 0;
        while i < data.len() {
            let b0 = data[i] as u32;
            let b1 = if i + 1 < data.len() {
                data[i + 1] as u32
            } else {
                0
            };
            let b2 = if i + 2 < data.len() {
                data[i + 2] as u32
            } else {
                0
            };
            let triple = (b0 << 16) | (b1 << 8) | b2;
            result.push(CHARS[((triple >> 18) & 0x3F) as usize] as char);
            result.push(CHARS[((triple >> 12) & 0x3F) as usize] as char);
            if i + 1 < data.len() {
                result.push(CHARS[((triple >> 6) & 0x3F) as usize] as char);
            } else {
                result.push('=');
            }
            if i + 2 < data.len() {
                result.push(CHARS[(triple & 0x3F) as usize] as char);
            } else {
                result.push('=');
            }
            i += 3;
        }
        result
    }

    #[test]
    fn render_all_12_fonts_registered() {
        let html = "<p>Test</p>";
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        // All 12 standard font variants should be registered as font objects
        for name in &[
            "Helvetica",
            "Helvetica-Bold",
            "Helvetica-Oblique",
            "Helvetica-BoldOblique",
            "Times-Roman",
            "Times-Bold",
            "Times-Italic",
            "Times-BoldItalic",
            "Courier",
            "Courier-Bold",
            "Courier-Oblique",
            "Courier-BoldOblique",
        ] {
            assert!(
                content.contains(&format!("/BaseFont /{name}")),
                "PDF should register font {name}"
            );
        }
    }

    #[test]
    fn render_opacity_produces_extgstate() {
        let html = r#"<div style="opacity: 0.5">Semi-transparent</div>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(
            content.contains("/ca 0.5"),
            "PDF should contain fill opacity /ca 0.5"
        );
        assert!(
            content.contains("/CA 0.5"),
            "PDF should contain stroke opacity /CA 0.5"
        );
        assert!(
            content.contains("/ExtGState"),
            "PDF should contain ExtGState resource"
        );
        assert!(content.contains("gs\n"), "PDF should use gs operator");
    }

    #[test]
    fn render_full_opacity_no_extgstate() {
        let html = r#"<div>Fully opaque</div>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(
            !content.contains("/ExtGState"),
            "PDF should not contain ExtGState for full opacity"
        );
    }

    #[test]
    fn render_width_constrains_background() {
        let html = r#"<div style="width: 200pt; background-color: red">Narrow</div>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(
            content.contains("200"),
            "PDF should contain the constrained width 200"
        );
    }

    #[test]
    fn render_justify_produces_tw_operator() {
        // Use enough words to force line wrapping so a non-last line exists
        let words = "word ".repeat(80);
        let html = format!(r#"<p style="text-align: justify">{words}</p>"#,);
        let nodes = parse_html(&html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(
            content.contains("Tw\n"),
            "Justified text should produce Tw operator in PDF"
        );
    }

    #[test]
    fn render_justify_last_line_no_tw() {
        // A single short line (which is the last line) should not have Tw
        let html = r#"<p style="text-align: justify">Short line</p>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        // The single line is the last line, so no Tw should be applied
        assert!(
            !content.contains("Tw\n"),
            "Last line of justified paragraph should not have Tw"
        );
    }

    #[test]
    fn render_justify_resets_tw() {
        let words = "word ".repeat(80);
        let html = format!(r#"<p style="text-align: justify">{words}</p>"#,);
        let nodes = parse_html(&html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        // Tw should be reset to 0 after each justified line
        assert!(
            content.contains("0 Tw\n"),
            "Tw should be reset to 0 after justified lines"
        );
    }

    // --- Overflow / Visibility / Transform PDF rendering tests ---

    #[test]
    fn render_visibility_hidden_skips_content() {
        let html = r#"<div style="visibility: hidden">Hidden text</div><p>Visible text</p>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(
            !content.contains("Hidden text"),
            "visibility: hidden should not render text content"
        );
        assert!(
            content.contains("Visible"),
            "Other text should still render"
        );
    }

    #[test]
    fn render_overflow_hidden_produces_clip_path() {
        let html =
            r#"<div style="overflow: hidden; width: 200pt; height: 100pt">Clipped content</div>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(
            content.contains("re W n"),
            "overflow: hidden should produce clipping path (re W n)"
        );
        assert!(
            content.contains("Clipped"),
            "Content should still be rendered inside clip"
        );
    }

    #[test]
    fn render_transform_rotate_produces_cm() {
        let html = r#"<div style="transform: rotate(45deg)">Rotated text</div>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        // rotate(45deg) should produce cos/sin values in a cm operator
        assert!(
            content.contains("cm\n"),
            "transform: rotate should produce cm operator"
        );
        assert!(
            content.contains("q\n"),
            "transform should save graphics state with q"
        );
        assert!(
            content.contains("Q\n"),
            "transform should restore graphics state with Q"
        );
        // cos(45) ~= 0.7071, sin(45) ~= 0.7071
        assert!(
            content.contains("0.707"),
            "rotate(45deg) should contain cos/sin values ~0.707"
        );
    }

    #[test]
    fn render_transform_scale_produces_cm() {
        let html = r#"<div style="transform: scale(2)">Scaled text</div>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(
            content.contains("2 0 0 2 0 0 cm"),
            "transform: scale(2) should produce '2 0 0 2 0 0 cm'"
        );
    }

    #[test]
    fn render_transform_translate_produces_cm() {
        let html = r#"<div style="transform: translate(10pt, 20pt)">Translated text</div>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(
            content.contains("1 0 0 1 10 20 cm"),
            "transform: translate(10pt, 20pt) should produce '1 0 0 1 10 20 cm'"
        );
    }

    #[test]
    fn render_overflow_visible_no_clip() {
        let html = r#"<div style="width: 200pt">Normal content</div>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(
            !content.contains("re W n"),
            "No overflow should not produce clipping path"
        );
    }

    #[test]
    fn render_border_radius_produces_bezier_curves() {
        let html = r#"<div style="border: 1px solid black; border-radius: 10pt; background-color: red">Rounded</div>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        // Bezier curves use 'c' operator; rounded rects should have them
        assert!(
            content.contains(" c\n"),
            "Border-radius should produce Bezier curve commands"
        );
        // Should also have 'h' to close the path
        assert!(
            content.contains("h\n"),
            "Rounded rect path should be closed with 'h'"
        );
    }

    #[test]
    fn render_outline_draws_outside_element() {
        let html = r#"<div style="outline: 2px solid red; width: 100pt">Outlined</div>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        // Outline should produce a stroke command (S) with outline color
        assert!(
            content.contains("1 0 0 RG"),
            "Outline should set red stroke color"
        );
        assert!(
            content.contains("S\n"),
            "Outline should produce a stroke command"
        );
    }

    #[test]
    fn render_border_radius_zero_uses_rectangle() {
        let html = r#"<div style="border: 1px solid black; background-color: blue">Square</div>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        // Without border-radius, should use 're' (rectangle) not Bezier curves
        assert!(
            content.contains("re\n"),
            "Zero border-radius should use rectangle operator"
        );
    }

    #[test]
    fn build_shading_function_single_stop() {
        // Single stop produces a constant-color Type 2 function
        let stops = vec![(0.5, (1.0, 0.0, 0.0))];
        let result = build_shading_function(&stops);
        assert!(result.contains("/FunctionType 2"));
        assert!(result.contains("/C0 [1 0 0]"));
        assert!(result.contains("/C1 [1 0 0]"));
    }

    #[test]
    fn build_shading_function_two_stops() {
        let stops = vec![(0.0, (1.0, 0.0, 0.0)), (1.0, (0.0, 0.0, 1.0))];
        let result = build_shading_function(&stops);
        assert!(result.contains("/FunctionType 2"));
        assert!(result.contains("/C0 [1 0 0]"));
        assert!(result.contains("/C1 [0 0 1]"));
    }

    #[test]
    fn build_shading_function_three_stops() {
        let stops = vec![
            (0.0, (1.0, 0.0, 0.0)),
            (0.5, (0.0, 1.0, 0.0)),
            (1.0, (0.0, 0.0, 1.0)),
        ];
        let result = build_shading_function(&stops);
        assert!(result.contains("/FunctionType 3"));
        assert!(result.contains("/Bounds [0.5]"));
        assert!(result.contains("/Encode [0 1 0 1]"));
    }

    #[test]
    fn build_shading_function_empty_stops() {
        let stops: Vec<(f32, (f32, f32, f32))> = vec![];
        let result = build_shading_function(&stops);
        assert!(result.contains("/FunctionType 2"));
        assert!(result.contains("/C0 [0 0 0]"));
    }

    #[test]
    fn render_cell_text_with_empty_line_and_empty_run() {
        // Covers lines 718, 724: empty line text skipped, empty run skipped
        let empty_run = TextRun {
            text: String::new(),
            font_size: 12.0,
            bold: false,
            italic: false,
            underline: false,
            line_through: false,
            color: (0.0, 0.0, 0.0),
            font_family: FontFamily::Helvetica,
            link_url: None,
            background_color: None,
            padding: (0.0, 0.0),
            border_radius: 0.0,
        };
        let non_empty_run = TextRun {
            text: "Hello".to_string(),
            font_size: 12.0,
            bold: false,
            italic: false,
            underline: false,
            line_through: false,
            color: (0.0, 0.0, 0.0),
            font_family: FontFamily::Helvetica,
            link_url: None,
            background_color: None,
            padding: (0.0, 0.0),
            border_radius: 0.0,
        };
        let cell = TableCell {
            lines: vec![
                TextLine {
                    runs: vec![empty_run.clone()],
                    height: 14.0,
                },
                TextLine {
                    runs: vec![empty_run.clone(), non_empty_run],
                    height: 14.0,
                },
            ],
            bold: false,
            colspan: 1,
            rowspan: 1,
            padding_top: 2.0,
            padding_bottom: 2.0,
            padding_left: 2.0,
            padding_right: 2.0,
            background_color: None,
            border: LayoutBorder::default(),
            text_align: TextAlign::Left,
        };
        let mut content = String::new();
        let fonts = HashMap::new();
        render_cell_text(&mut content, &cell, 0.0, 100.0, 50.0, 20.0, &fonts);
        assert!(content.contains("Hello"));
    }

    #[test]
    fn text_block_empty_run_skipped() {
        // Covers line 401: empty text run within a text block line is skipped
        use crate::layout::engine::LayoutElement;
        let empty_run = TextRun {
            text: String::new(),
            font_size: 12.0,
            bold: false,
            italic: false,
            underline: false,
            line_through: false,
            color: (0.0, 0.0, 0.0),
            font_family: FontFamily::Helvetica,
            link_url: None,
            background_color: None,
            padding: (0.0, 0.0),
            border_radius: 0.0,
        };
        let real_run = TextRun {
            text: "Data".to_string(),
            font_size: 12.0,
            bold: false,
            italic: false,
            underline: false,
            line_through: false,
            color: (0.0, 0.0, 0.0),
            font_family: FontFamily::Helvetica,
            link_url: None,
            background_color: None,
            padding: (0.0, 0.0),
            border_radius: 0.0,
        };
        let page = Page {
            elements: vec![(
                0.0,
                LayoutElement::TextBlock {
                    lines: vec![TextLine {
                        runs: vec![empty_run, real_run],
                        height: 14.0,
                    }],
                    margin_top: 0.0,
                    margin_bottom: 0.0,
                    text_align: TextAlign::Left,
                    background_color: None,
                    padding_top: 0.0,
                    padding_bottom: 0.0,
                    padding_left: 0.0,
                    padding_right: 0.0,
                    border: LayoutBorder::default(),
                    block_width: None,
                    block_height: None,
                    opacity: 1.0,
                    float: Float::None,
                    clear: crate::style::computed::Clear::None,
                    position: Position::Static,
                    offset_top: 0.0,
                    offset_left: 0.0,
                    box_shadow: None,
                    visible: true,
                    clip_rect: None,
                    transform: None,
                    background_gradient: None,
                    background_radial_gradient: None,
                    border_radius: 0.0,
                    outline_width: 0.0,
                    outline_color: None,
                    text_indent: 0.0,
                    letter_spacing: 0.0,
                    word_spacing: 0.0,
                    vertical_align: crate::style::computed::VerticalAlign::Baseline,
                    z_index: 0,
                    heading_level: None,
                },
            )],
        };
        let pdf = render_pdf(&[page], PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("Data"));
    }

    #[test]
    fn page_break_element_renders() {
        // Covers line 677: PageBreak empty match arm
        let page = Page {
            elements: vec![
                (
                    0.0,
                    LayoutElement::TextBlock {
                        lines: vec![TextLine {
                            runs: vec![TextRun {
                                text: "Before".to_string(),
                                font_size: 12.0,
                                bold: false,
                                italic: false,
                                underline: false,
                                line_through: false,
                                color: (0.0, 0.0, 0.0),
                                font_family: FontFamily::Helvetica,
                                link_url: None,
                                background_color: None,
                                padding: (0.0, 0.0),
                                border_radius: 0.0,
                            }],
                            height: 14.0,
                        }],
                        margin_top: 0.0,
                        margin_bottom: 0.0,
                        text_align: TextAlign::Left,
                        background_color: None,
                        padding_top: 0.0,
                        padding_bottom: 0.0,
                        padding_left: 0.0,
                        padding_right: 0.0,
                        border: LayoutBorder::default(),
                        block_width: None,
                        block_height: None,
                        opacity: 1.0,
                        float: Float::None,
                        clear: crate::style::computed::Clear::None,
                        position: Position::Static,
                        offset_top: 0.0,
                        offset_left: 0.0,
                        box_shadow: None,
                        visible: true,
                        clip_rect: None,
                        transform: None,
                        background_gradient: None,
                        background_radial_gradient: None,
                        border_radius: 0.0,
                        outline_width: 0.0,
                        outline_color: None,
                        text_indent: 0.0,
                        letter_spacing: 0.0,
                        word_spacing: 0.0,
                        vertical_align: crate::style::computed::VerticalAlign::Baseline,
                        z_index: 0,
                        heading_level: None,
                    },
                ),
                (20.0, LayoutElement::PageBreak),
            ],
        };
        let pdf = render_pdf(&[page], PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(content.contains("Before"));
    }

    #[test]
    fn font_name_for_run_custom_bold_italic() {
        // Covers lines 761-763: Custom font bold+italic fallback names
        let run_bi = TextRun {
            text: "test".to_string(),
            font_size: 12.0,
            bold: true,
            italic: true,
            underline: false,
            line_through: false,
            color: (0.0, 0.0, 0.0),
            font_family: FontFamily::Custom("MyFont".to_string()),
            link_url: None,
            background_color: None,
            padding: (0.0, 0.0),
            border_radius: 0.0,
        };
        assert_eq!(font_name_for_run(&run_bi), "Helvetica-BoldOblique");

        let run_b = TextRun {
            text: "test".to_string(),
            font_size: 12.0,
            bold: true,
            italic: false,
            underline: false,
            line_through: false,
            color: (0.0, 0.0, 0.0),
            font_family: FontFamily::Custom("MyFont".to_string()),
            link_url: None,
            background_color: None,
            padding: (0.0, 0.0),
            border_radius: 0.0,
        };
        assert_eq!(font_name_for_run(&run_b), "Helvetica-Bold");

        let run_i = TextRun {
            text: "test".to_string(),
            font_size: 12.0,
            bold: false,
            italic: true,
            underline: false,
            line_through: false,
            color: (0.0, 0.0, 0.0),
            font_family: FontFamily::Custom("MyFont".to_string()),
            link_url: None,
            background_color: None,
            padding: (0.0, 0.0),
            border_radius: 0.0,
        };
        assert_eq!(font_name_for_run(&run_i), "Helvetica-Oblique");
    }

    #[test]
    fn render_radial_gradient_uses_shading() {
        use crate::style::computed::GradientStop;
        use crate::types::Color;
        let mut content = String::new();
        let mut shadings = Vec::new();
        let mut counter = 0usize;
        let gradient = RadialGradient {
            stops: vec![
                GradientStop {
                    color: Color {
                        r: 255,
                        g: 0,
                        b: 0,
                        a: 255,
                    },
                    position: 0.0,
                },
                GradientStop {
                    color: Color {
                        r: 0,
                        g: 0,
                        b: 255,
                        a: 255,
                    },
                    position: 1.0,
                },
            ],
        };
        render_radial_gradient(
            &mut content,
            &gradient,
            0.0,
            0.0,
            1.0,
            1.0,
            &mut shadings,
            &mut counter,
        );
        assert!(!content.is_empty());
        assert!(content.contains("/SH0 sh"));
        assert_eq!(shadings.len(), 1);
        assert_eq!(shadings[0].shading_type, 3);
    }

    #[test]
    fn utf8_to_winansi_ascii() {
        let input = "Hello, World! 123";
        let result = utf8_to_winansi(input);
        assert_eq!(result, input.as_bytes());
    }

    #[test]
    fn utf8_to_winansi_em_dash() {
        // "hello — world" contains U+2014 em dash which should become 0x97
        let input = "hello \u{2014} world";
        let result = utf8_to_winansi(input);
        let expected: Vec<u8> = vec![
            b'h', b'e', b'l', b'l', b'o', b' ', 0x97, b' ', b'w', b'o', b'r', b'l', b'd',
        ];
        assert_eq!(result, expected);
    }

    #[test]
    fn utf8_to_winansi_quotes() {
        // Left/right single and double curly quotes
        let input = "\u{2018}hello\u{2019} \u{201C}world\u{201D}";
        let result = utf8_to_winansi(input);
        assert_eq!(result[0], 0x91); // left single quote
        assert_eq!(result[6], 0x92); // right single quote
        assert_eq!(result[8], 0x93); // left double quote
        assert_eq!(result[14], 0x94); // right double quote
    }

    #[test]
    fn utf8_to_winansi_latin1() {
        // e-acute (U+00E9), n-tilde (U+00F1), u-diaeresis (U+00FC)
        let input = "\u{00E9}\u{00F1}\u{00FC}";
        let result = utf8_to_winansi(input);
        assert_eq!(result, vec![0xE9, 0xF1, 0xFC]);
    }

    #[test]
    fn utf8_to_winansi_unknown() {
        // Chinese character and emoji should be replaced with '?'
        let input = "\u{4E16}\u{1F600}";
        let result = utf8_to_winansi(input);
        assert_eq!(result, vec![b'?', b'?']);
    }

    #[test]
    fn utf8_to_winansi_en_dash_bullet_ellipsis_euro_trademark() {
        assert_eq!(utf8_to_winansi("\u{2013}"), vec![0x96]); // en dash
        assert_eq!(utf8_to_winansi("\u{2022}"), vec![0x95]); // bullet
        assert_eq!(utf8_to_winansi("\u{2026}"), vec![0x85]); // ellipsis
        assert_eq!(utf8_to_winansi("\u{20AC}"), vec![0x80]); // euro
        assert_eq!(utf8_to_winansi("\u{2122}"), vec![0x99]); // trademark
    }

    #[test]
    fn encode_pdf_text_special_chars() {
        assert_eq!(encode_pdf_text("hello"), "hello");
        assert_eq!(encode_pdf_text("(test)"), "\\(test\\)");
        assert_eq!(encode_pdf_text("back\\slash"), "back\\\\slash");
    }

    #[test]
    fn encode_pdf_text_em_dash() {
        let encoded = encode_pdf_text("hello \u{2014} world");
        // 0x97 = 151 decimal = 227 octal; em dash should be \227
        assert_eq!(encoded, "hello \\227 world");
    }

    #[test]
    fn encode_pdf_text_em_dash_in_pdf_bytes() {
        // Verify that rendering em dash produces correct octal escape in PDF
        // and does NOT produce UTF-8 bytes or mojibake
        let html = "<p>hello \u{2014} world</p>";
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let pdf_str = String::from_utf8_lossy(&pdf);

        // The PDF content stream should contain the octal escape \227
        assert!(
            pdf_str.contains("\\227"),
            "PDF should contain octal escape \\227 for em dash"
        );

        // The raw UTF-8 bytes for em dash (0xE2 0x80 0x94) should NOT appear
        let has_utf8_em_dash = pdf.windows(3).any(|w| w == [0xE2, 0x80, 0x94]);
        assert!(
            !has_utf8_em_dash,
            "PDF should not contain raw UTF-8 bytes for em dash"
        );

        // The mojibake pattern should not appear
        let has_mojibake = pdf.windows(2).any(|w| w == [0xC3, 0xA2]);
        assert!(!has_mojibake, "PDF should not contain mojibake bytes");
    }

    #[test]
    fn integration_em_dash_no_mojibake_in_pdf() {
        // Render HTML with em dash and verify the raw UTF-8 mojibake bytes
        // "\xC3\xA2\xC2\x80\xC2\x94" (the UTF-8 encoding of U+2014 read as
        // latin1) do NOT appear in the output.
        let html = "<p>hello \u{2014} world</p>";
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();

        // The mojibake sequence for em dash in UTF-8 misinterpreted as latin1
        // is bytes [0xC3, 0xA2]. This must NOT appear in the PDF.
        let has_mojibake = pdf.windows(2).any(|w| w == [0xC3, 0xA2]);
        assert!(
            !has_mojibake,
            "PDF output contains UTF-8 mojibake for em dash"
        );

        // The octal escape sequence \227 (for byte 0x97) should appear in the PDF
        let pdf_str = String::from_utf8_lossy(&pdf);
        assert!(
            pdf_str.contains("\\227"),
            "PDF output should contain octal escape \\227 for WinAnsi em dash"
        );
    }

    #[test]
    fn total_row_bold_from_descendant_selector() {
        use crate::parser::css::parse_stylesheet;
        let html = r#"<html><head><style>
            .total-row td { font-weight: bold; font-size: 12pt; }
        </style></head><body>
        <table>
            <tr><td>Item</td><td>$100</td></tr>
            <tr class="total-row"><td>Total</td><td>$100</td></tr>
        </table>
        </body></html>"#;
        let result = crate::parser::html::parse_html_with_styles(html).unwrap();
        let mut rules = Vec::new();
        for css in &result.stylesheets {
            rules.extend(parse_stylesheet(css));
        }
        let pages = crate::layout::engine::layout_with_rules(
            &result.nodes,
            PageSize::A4,
            Margin::default(),
            &rules,
        );
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let pdf_str = String::from_utf8_lossy(&pdf);
        // The total row cells should use Helvetica-Bold
        assert!(
            pdf_str.contains("/Helvetica-Bold 12 Tf"),
            "Total row should use Helvetica-Bold at 12pt, PDF content:\n{}",
            pdf_str
                .lines()
                .filter(|l| l.contains("Helvetica"))
                .collect::<Vec<_>>()
                .join("\n")
        );
    }

    #[test]
    fn table_cell_em_dash_encoded_correctly() {
        let html = r#"<table><tr><td>HTML/CSS to PDF conversion — Enterprise</td></tr></table>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let pdf_str = String::from_utf8_lossy(&pdf);
        // Em dash in table cell should be encoded as octal \227
        assert!(
            pdf_str.contains("\\227"),
            "Table cell em dash should be encoded as \\227"
        );
        // No raw UTF-8 bytes for em dash
        let has_utf8_em_dash = pdf.windows(3).any(|w| w == [0xE2, 0x80, 0x94]);
        assert!(
            !has_utf8_em_dash,
            "Table cell should not contain raw UTF-8 em dash bytes"
        );
    }

    #[test]
    fn linear_gradient_uses_shading() {
        let html = r#"<div style="background: linear-gradient(to bottom, red, blue); height: 50pt">Gradient</div>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(
            content.contains("/ShadingType 2"),
            "Linear gradient should produce ShadingType 2 (axial)"
        );
    }

    #[test]
    fn radial_gradient_uses_shading_in_pdf() {
        let html =
            r#"<div style="background: radial-gradient(red, blue); height: 50pt">Gradient</div>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let content = String::from_utf8_lossy(&pdf);
        assert!(
            content.contains("/ShadingType 3"),
            "Radial gradient should produce ShadingType 3"
        );
    }

    #[test]
    fn border_top_only_renders_single_line() {
        let html = r#"<div style="border-top: 2pt solid red">Top border only</div>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let pdf_str = String::from_utf8_lossy(&pdf);
        // Per-side border renders as a move-to + line-to + stroke, not a rectangle
        assert!(
            pdf_str.contains("l S\n"),
            "Should have line stroke for top border"
        );
        assert!(pdf_str.contains("1 0 0 RG"), "Should have red stroke color");
    }

    #[test]
    fn border_bottom_renders() {
        let html = r#"<div style="border-bottom: 1pt solid blue">Bottom border</div>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let pdf_str = String::from_utf8_lossy(&pdf);
        assert!(
            pdf_str.contains("l S\n"),
            "Should have line stroke for bottom border"
        );
        assert!(
            pdf_str.contains("0 0 1 RG"),
            "Should have blue stroke color"
        );
    }

    #[test]
    fn border_left_renders() {
        let html = r#"<blockquote style="border-left: 3pt solid green">Left border</blockquote>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let pdf_str = String::from_utf8_lossy(&pdf);
        assert!(
            pdf_str.contains("l S\n"),
            "Should have line stroke for left border"
        );
        assert!(
            pdf_str.contains("0 0.50196 0 RG")
                || pdf_str.contains("0 0.501960")
                || pdf_str.contains("RG"),
            "Should have green stroke color"
        );
    }

    #[test]
    fn non_uniform_borders_render_per_side() {
        let html =
            r#"<div style="border-top: 2pt solid red; border-bottom: 1pt solid blue">Mixed</div>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let pdf_str = String::from_utf8_lossy(&pdf);
        // Non-uniform borders should produce per-side line strokes
        assert!(pdf_str.contains("1 0 0 RG"), "Should have red for top");
        assert!(pdf_str.contains("0 0 1 RG"), "Should have blue for bottom");
        // Should use line strokes, not rectangle
        let stroke_count = pdf_str.matches("l S\n").count();
        assert!(
            stroke_count >= 2,
            "Should have at least 2 line strokes, got {stroke_count}"
        );
    }

    #[test]
    fn gradient_clipped_to_border_radius() {
        let html = r#"<div style="background: linear-gradient(to bottom, red, blue); border-radius: 10pt; height: 50pt">Clipped</div>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let pdf_str = String::from_utf8_lossy(&pdf);
        assert!(
            pdf_str.contains("sh"),
            "Should have shading operator for gradient"
        );
        assert!(
            pdf_str.contains("W n"),
            "Should have clip operator for border-radius"
        );
    }

    #[test]
    fn flexrow_with_gradient() {
        let html = r#"<div style="display: flex; background: linear-gradient(to right, red, blue); height: 40pt"><div style="width: 100pt">A</div></div>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let pdf_str = String::from_utf8_lossy(&pdf);
        assert!(
            pdf_str.contains("/ShadingType 2"),
            "FlexRow with linear-gradient should produce ShadingType 2"
        );
    }

    #[test]
    fn flexrow_cell_background() {
        let html = r#"<div style="display: flex"><div style="width: 100pt; background-color: yellow">Yellow</div><div style="width: 100pt">Plain</div></div>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let pdf_str = String::from_utf8_lossy(&pdf);
        // Yellow = 1 1 0 rg
        assert!(
            pdf_str.contains("1 1 0 rg"),
            "Should have yellow fill color for cell background"
        );
        assert!(
            pdf_str.contains("re\nf\n"),
            "Should have rectangle fill for cell background"
        );
    }

    #[test]
    fn flexrow_cell_border_radius() {
        let html = r#"<div style="display: flex"><div style="width: 100pt; background-color: red; border-radius: 8pt">Round</div></div>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let pdf_str = String::from_utf8_lossy(&pdf);
        // Rounded rect uses Bezier curve commands (c)
        assert!(pdf_str.contains("1 0 0 rg"), "Should have red fill");
        assert!(
            pdf_str.contains(" c\n"),
            "Should have Bezier curve for border-radius"
        );
    }

    #[test]
    fn flexrow_cell_gradient() {
        let html = r#"<div style="display: flex"><div style="width: 150pt; background: linear-gradient(to bottom, green, yellow)">Grad</div></div>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let pdf_str = String::from_utf8_lossy(&pdf);
        assert!(
            pdf_str.contains("sh"),
            "Should have shading for cell gradient"
        );
        assert!(
            pdf_str.contains("/ShadingType 2"),
            "Cell gradient should use axial shading"
        );
    }

    #[test]
    fn flexrow_border_renders() {
        let html = r#"<div style="display: flex; border: 2pt solid black"><div style="width: 100pt">Bordered</div></div>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let pdf_str = String::from_utf8_lossy(&pdf);
        assert!(
            pdf_str.contains("re\nS\n"),
            "Should have rectangle stroke for uniform flex border"
        );
        assert!(
            pdf_str.contains("0 0 0 RG"),
            "Should have black stroke color"
        );
    }

    #[test]
    fn flexrow_border_radius_background() {
        let html = r#"<div style="display: flex; border-radius: 10pt; background-color: #cccccc"><div style="width: 100pt">Rounded</div></div>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let pdf_str = String::from_utf8_lossy(&pdf);
        // Rounded background uses Bezier curves, not re
        assert!(
            pdf_str.contains(" c\n"),
            "Should have Bezier curves for rounded background"
        );
        assert!(pdf_str.contains("f\n"), "Should have fill command");
    }

    #[test]
    fn inline_span_border_radius() {
        let html = r#"<div style="display: flex"><div style="width: 300pt"><p><span style="background-color: yellow; border-radius: 4pt; padding: 2pt">Tag</span> text</p></div></div>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let pdf_str = String::from_utf8_lossy(&pdf);
        // Inline span with border-radius should produce rounded rect path + fill
        assert!(
            pdf_str.contains("1 1 0 rg"),
            "Should have yellow fill for span bg"
        );
    }

    #[test]
    fn table_cell_borders_render() {
        use crate::parser::css::parse_stylesheet;
        let html = r#"<html><head><style>
            td { border-bottom: 1pt solid #999999; }
        </style></head><body>
        <table><tr><td>Cell</td></tr></table>
        </body></html>"#;
        let result = crate::parser::html::parse_html_with_styles(html).unwrap();
        let mut rules = Vec::new();
        for css in &result.stylesheets {
            rules.extend(parse_stylesheet(css));
        }
        let pages = crate::layout::engine::layout_with_rules(
            &result.nodes,
            PageSize::A4,
            Margin::default(),
            &rules,
        );
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let pdf_str = String::from_utf8_lossy(&pdf);
        assert!(
            pdf_str.contains("l\nS\n") || pdf_str.contains("l S\n") || pdf_str.contains("re\nS\n"),
            "Table cell border should produce stroke commands"
        );
    }

    #[test]
    fn text_align_right_in_flex_cell() {
        let html = r#"<div style="display: flex"><div style="width: 200pt; text-align: right">Right</div></div>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let pdf_str = String::from_utf8_lossy(&pdf);
        assert!(pdf_str.contains("Right"), "Should contain the text 'Right'");
        // The text x-position should be offset from left (not at left margin)
        assert!(
            pdf_str.contains("Td"),
            "Should have text positioning operator"
        );
    }

    #[test]
    fn text_align_center_in_flex_cell() {
        let html = r#"<div style="display: flex"><div style="width: 200pt; text-align: center">Center</div></div>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let pdf_str = String::from_utf8_lossy(&pdf);
        assert!(
            pdf_str.contains("Center"),
            "Should contain the text 'Center'"
        );
        assert!(
            pdf_str.contains("Td"),
            "Should have text positioning operator"
        );
    }

    #[test]
    fn absolute_position_offset() {
        let html = r#"<div style="position: absolute; left: 100pt; top: 50pt">Absolute</div>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let pdf_str = String::from_utf8_lossy(&pdf);
        assert!(
            pdf_str.contains("Absolute"),
            "Should contain positioned text"
        );
    }

    #[test]
    fn float_right_position() {
        let html = r#"<div style="float: right; width: 100pt">Floated</div>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let pdf_str = String::from_utf8_lossy(&pdf);
        assert!(pdf_str.contains("Floated"), "Should contain floated text");
    }

    #[test]
    fn radial_gradient_clipped() {
        let html = r#"<div style="background: radial-gradient(red, blue); border-radius: 10pt; height: 50pt">Radial</div>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let pdf_str = String::from_utf8_lossy(&pdf);
        assert!(
            pdf_str.contains("/ShadingType 3"),
            "Should have radial shading"
        );
        assert!(
            pdf_str.contains("W n"),
            "Should clip radial gradient to border-radius"
        );
    }

    #[test]
    fn opacity_renders_extgstate() {
        let html = r#"<div style="opacity: 0.5">Transparent</div>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let pdf_str = String::from_utf8_lossy(&pdf);
        assert!(
            pdf_str.contains("/ExtGState"),
            "Should have ExtGState for opacity"
        );
        assert!(pdf_str.contains("gs\n"), "Should apply graphics state");
    }

    #[test]
    fn box_shadow_renders() {
        let html = r#"<div style="box-shadow: 2pt 2pt 0 #888888; height: 30pt">Shadow</div>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let pdf_str = String::from_utf8_lossy(&pdf);
        // Box shadow renders as a filled rectangle behind the element
        assert!(
            pdf_str.contains("re\nf\n") || pdf_str.contains("f\n"),
            "Should have fill for box shadow"
        );
        assert!(pdf_str.contains("Shadow"), "Should contain the text");
    }

    // --- Coverage tests for uncovered lines ---

    #[test]
    fn position_absolute_block_x() {
        // Covers line 93, 128: Position::Absolute uses margin.left + offset_left
        let html =
            r#"<div style="position: absolute; left: 50pt; background-color: cyan">Absolute</div>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let pdf_str = String::from_utf8_lossy(&pdf);
        assert!(
            pdf_str.contains("Absolute"),
            "Should render absolute positioned text"
        );
    }

    #[test]
    fn position_relative_block_x() {
        // Covers lines 119-120, 129: Position::Relative block_x calculation
        let html =
            r#"<div style="position: relative; left: 30pt; background-color: lime">Relative</div>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let pdf_str = String::from_utf8_lossy(&pdf);
        assert!(
            pdf_str.contains("Relative"),
            "Should render relative positioned text"
        );
    }

    #[test]
    fn float_right_positioning() {
        // Covers line 131: Float::Right block_x = margin.left + available_width - render_w
        let html = r#"<div style="float: right; width: 100pt">Float right</div>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let pdf_str = String::from_utf8_lossy(&pdf);
        assert!(
            pdf_str.contains("Float right"),
            "Should render float right text"
        );
    }

    #[test]
    fn per_side_border_rendering() {
        // Covers lines 390-396: non-uniform per-side borders (left border with x_left offset)
        let html = r#"<div style="border-top: 2pt solid red; border-right: 3pt solid green; border-bottom: 1pt solid blue; border-left: 4pt solid black; width: 200pt; height: 50pt">Borders</div>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let pdf_str = String::from_utf8_lossy(&pdf);
        // Non-uniform borders produce per-side stroke commands
        assert!(
            pdf_str.contains("1 0 0 RG"),
            "Should have red top border stroke"
        );
        assert!(
            pdf_str.contains("0 0 0 RG"),
            "Should have black left border stroke"
        );
        assert!(
            pdf_str.contains("l\nS\n") || pdf_str.contains("l S\n"),
            "Should have per-side line strokes"
        );
    }

    #[test]
    fn center_align_with_inline_span() {
        // Covers line 487: TextAlign::Center branch in TextBlock with inline padding
        let html = r#"<p style="text-align: center"><span style="background-color: yellow; padding: 4pt">Centered Span</span></p>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let pdf_str = String::from_utf8_lossy(&pdf);
        assert!(
            pdf_str.contains("Centered Span"),
            "Should render centered span text"
        );
        assert!(
            pdf_str.contains("1 1 0 rg"),
            "Should have yellow background fill"
        );
    }

    #[test]
    fn right_align_with_inline_span() {
        // Covers line 491: TextAlign::Right branch in TextBlock with inline padding
        let html = r#"<p style="text-align: right"><span style="background-color: lime; padding: 4pt">Right Span</span></p>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let pdf_str = String::from_utf8_lossy(&pdf);
        assert!(
            pdf_str.contains("Right Span"),
            "Should render right-aligned span text"
        );
    }

    #[test]
    fn letter_spacing_in_text_rendering() {
        // Covers line 519 (letter-spacing sets Tc operator)
        let html = r#"<p style="letter-spacing: 2pt">Spaced out</p>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let pdf_str = String::from_utf8_lossy(&pdf);
        assert!(
            pdf_str.contains("Tc\n"),
            "Letter spacing should produce Tc operator"
        );
        assert!(
            pdf_str.contains("0 Tc\n"),
            "Letter spacing should be reset to 0"
        );
    }

    #[test]
    fn underline_and_strikethrough_rendering() {
        // Covers underline and strikethrough draw lines with font-size-relative thickness
        let html = r#"<p><span style="text-decoration: underline">Under</span> <span style="text-decoration: line-through">Strike</span></p>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let pdf_str = String::from_utf8_lossy(&pdf);
        // Both underline and strikethrough produce line strokes (S operator)
        let stroke_count = pdf_str.matches(" w\n").count();
        assert!(
            stroke_count >= 2,
            "Should have at least 2 stroke weight commands (underline + strikethrough), got {stroke_count}"
        );
        // Thickness should scale with font size (not hardcoded 0.5)
        assert!(
            pdf_str.contains(" l\nS\n"),
            "Should draw stroke lines for text decorations"
        );
    }

    #[test]
    fn table_cell_all_borders() {
        // Covers lines 621, 626-627, 705-724: table cell border rendering (all 4 sides)
        use crate::parser::css::parse_stylesheet;
        let html = r#"<html><head><style>
            td { border: 2pt solid red; }
        </style></head><body>
        <table><tr><td>Bordered Cell</td></tr></table>
        </body></html>"#;
        let result = crate::parser::html::parse_html_with_styles(html).unwrap();
        let mut rules = Vec::new();
        for css in &result.stylesheets {
            rules.extend(parse_stylesheet(css));
        }
        let pages = crate::layout::engine::layout_with_rules(
            &result.nodes,
            PageSize::A4,
            Margin::default(),
            &rules,
        );
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let pdf_str = String::from_utf8_lossy(&pdf);
        assert!(pdf_str.contains("Bordered Cell"), "Should render cell text");
        // Red border strokes
        assert!(
            pdf_str.contains("1 0 0 RG"),
            "Should have red border stroke color"
        );
        // Should have multiple line strokes (top, right, bottom, left)
        let stroke_count = pdf_str.matches("l S\n").count() + pdf_str.matches("l\nS\n").count();
        assert!(
            stroke_count >= 4,
            "Should have at least 4 border line strokes, got {stroke_count}"
        );
    }

    #[test]
    fn table_cell_rowspan_continuation() {
        // Covers lines 667, 669: rowspan > 1 cell rendering
        let html = r#"<table>
            <tr><td rowspan="2">Spanning</td><td>A</td></tr>
            <tr><td>B</td></tr>
        </table>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let pdf_str = String::from_utf8_lossy(&pdf);
        assert!(pdf_str.contains("Spanning"), "Should render rowspan cell");
        assert!(pdf_str.contains("A"), "Should render first row cell");
        assert!(pdf_str.contains("B"), "Should render second row cell");
    }

    #[test]
    fn flexrow_container_gradient() {
        // Covers lines 742, 744, 753, 848-874: FlexRow linear gradient with border-radius
        let html = r#"<div style="display: flex; background: linear-gradient(to right, red, blue); border-radius: 5pt"><div>Gradient Flex</div></div>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let pdf_str = String::from_utf8_lossy(&pdf);
        assert!(
            pdf_str.contains("Gradient Flex"),
            "Should render flex content"
        );
        // Linear gradient produces shading reference
        assert!(
            pdf_str.contains("sh\n"),
            "Should have shading operator for gradient"
        );
    }

    #[test]
    fn flexrow_non_uniform_border() {
        // Covers lines 790, 798, 804-805, 939-969: FlexRow non-uniform per-side border
        let html = r#"<div style="display: flex; border-top: 2pt solid red; border-right: 3pt solid green; border-bottom: 1pt solid blue; border-left: 4pt solid black"><div>Flex Borders</div></div>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let pdf_str = String::from_utf8_lossy(&pdf);
        assert!(
            pdf_str.contains("Flex Borders"),
            "Should render flex content"
        );
        // Non-uniform borders produce per-side strokes
        assert!(
            pdf_str.contains("1 0 0 RG"),
            "Should have red stroke for top"
        );
    }

    #[test]
    fn flexrow_cell_inline_background_with_border_radius() {
        // Covers lines 852-903, 982-1001: FlexRow cell bg with border-radius and gradient
        let html = r#"<div style="display: flex"><div style="background-color: orange; border-radius: 8pt; width: 100pt">Cell BG</div></div>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let pdf_str = String::from_utf8_lossy(&pdf);
        assert!(pdf_str.contains("Cell BG"), "Should render cell text");
        // Orange background: 1 0.647.. 0 rg — check for the fill command
        assert!(
            pdf_str.contains("rg\n"),
            "Should have fill color for cell background"
        );
    }

    #[test]
    fn flexrow_cell_text_alignment() {
        // Covers lines 918-969, 1084, 1090: FlexRow cell text-align center and right
        let html = r#"<div style="display: flex">
            <div style="width: 200pt; text-align: center">Center</div>
            <div style="width: 200pt; text-align: right">Right</div>
        </div>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let pdf_str = String::from_utf8_lossy(&pdf);
        assert!(
            pdf_str.contains("Center"),
            "Should render center-aligned text"
        );
        assert!(
            pdf_str.contains("Right"),
            "Should render right-aligned text"
        );
    }

    #[test]
    fn render_cell_text_vertical_centering() {
        // Covers lines 1116-1123: render_cell_text vertical centering with bg + border-radius
        let run = TextRun {
            text: "Centered".to_string(),
            font_size: 14.0,
            bold: false,
            italic: false,
            underline: false,
            line_through: false,
            color: (0.0, 0.0, 0.0),
            font_family: FontFamily::Helvetica,
            link_url: None,
            background_color: Some((1.0, 0.0, 0.0)),
            padding: (4.0, 2.0),
            border_radius: 3.0,
        };
        let cell = TableCell {
            lines: vec![TextLine {
                runs: vec![run],
                height: 16.0,
            }],
            bold: false,
            colspan: 1,
            rowspan: 1,
            padding_top: 4.0,
            padding_bottom: 4.0,
            padding_left: 4.0,
            padding_right: 4.0,
            background_color: None,
            border: LayoutBorder::default(),
            text_align: TextAlign::Center,
        };
        let mut content = String::new();
        let fonts = HashMap::new();
        render_cell_text(&mut content, &cell, 10.0, 200.0, 100.0, 40.0, &fonts);
        assert!(content.contains("Centered"), "Should render cell text");
        // Background with border-radius produces rounded rect
        assert!(
            content.contains("1 0 0 rg"),
            "Should have red inline background"
        );
    }

    #[test]
    fn merge_runs_border_radius_comparison() {
        // Covers lines 1175, 1179-1180: merge_runs checks border_radius equality
        let run_a = TextRun {
            text: "Hello ".to_string(),
            font_size: 12.0,
            bold: false,
            italic: false,
            underline: false,
            line_through: false,
            color: (0.0, 0.0, 0.0),
            font_family: FontFamily::Helvetica,
            link_url: None,
            background_color: Some((1.0, 1.0, 0.0)),
            padding: (2.0, 1.0),
            border_radius: 4.0,
        };
        let run_b = TextRun {
            text: "World".to_string(),
            font_size: 12.0,
            bold: false,
            italic: false,
            underline: false,
            line_through: false,
            color: (0.0, 0.0, 0.0),
            font_family: FontFamily::Helvetica,
            link_url: None,
            background_color: Some((1.0, 1.0, 0.0)),
            padding: (2.0, 1.0),
            border_radius: 8.0, // Different border_radius
        };
        let merged = merge_runs(&[run_a.clone(), run_b.clone()]);
        // Different border_radius should prevent merging
        assert_eq!(
            merged.len(),
            2,
            "Runs with different border_radius should not merge"
        );
        // Same border_radius should merge
        let mut run_b_same = run_b;
        run_b_same.border_radius = 4.0;
        let merged2 = merge_runs(&[run_a, run_b_same]);
        assert_eq!(
            merged2.len(),
            1,
            "Runs with same border_radius should merge"
        );
    }

    #[test]
    fn build_shading_function_four_stops_stitching() {
        // Covers lines 1277-1304: Type 3 stitching function with 4 stops
        let stops = vec![
            (0.0, (1.0, 0.0, 0.0)),
            (0.33, (0.0, 1.0, 0.0)),
            (0.66, (0.0, 0.0, 1.0)),
            (1.0, (1.0, 1.0, 0.0)),
        ];
        let result = build_shading_function(&stops);
        assert!(
            result.contains("/FunctionType 3"),
            "4 stops should produce Type 3 stitching function"
        );
        assert!(
            result.contains("/Bounds [0.33 0.66]"),
            "Should have bounds for intermediate stops"
        );
        assert!(
            result.contains("/Encode [0 1 0 1 0 1]"),
            "Should have encode entries for each sub-function"
        );
        // Should contain 3 sub-functions (one per stop pair)
        let subfn_count = result.matches("/FunctionType 2").count();
        assert_eq!(
            subfn_count, 3,
            "Should have 3 Type 2 sub-functions, got {subfn_count}"
        );
    }

    #[test]
    fn custom_font_embedding_in_pdf() {
        // Covers lines 1628-1657: TTF font objects in PDF
        use crate::parser::ttf::TtfFont;
        let mut cmap = HashMap::new();
        for c in 32u16..=126 {
            cmap.insert(c, c - 31);
        }
        let ttf = TtfFont {
            font_name: "TestFont".to_string(),
            units_per_em: 1000,
            bbox: [0, -200, 800, 800],
            ascent: 800,
            descent: -200,
            cmap,
            glyph_widths: (0..=96).map(|_| 500).collect(),
            num_h_metrics: 96,
            flags: 32,
            data: vec![0u8; 64], // Minimal dummy font data
        };
        let mut fonts = HashMap::new();
        fonts.insert("TestFont".to_string(), ttf);

        let run = TextRun {
            text: "Custom".to_string(),
            font_size: 12.0,
            bold: false,
            italic: false,
            underline: false,
            line_through: false,
            color: (0.0, 0.0, 0.0),
            font_family: FontFamily::Custom("TestFont".to_string()),
            link_url: None,
            background_color: None,
            padding: (0.0, 0.0),
            border_radius: 0.0,
        };
        let page = Page {
            elements: vec![(
                0.0,
                LayoutElement::TextBlock {
                    lines: vec![TextLine {
                        runs: vec![run],
                        height: 14.0,
                    }],
                    margin_top: 0.0,
                    margin_bottom: 0.0,
                    text_align: TextAlign::Left,
                    background_color: None,
                    padding_top: 0.0,
                    padding_bottom: 0.0,
                    padding_left: 0.0,
                    padding_right: 0.0,
                    border: LayoutBorder::default(),
                    block_width: None,
                    block_height: None,
                    opacity: 1.0,
                    float: Float::None,
                    clear: crate::style::computed::Clear::None,
                    position: Position::Static,
                    offset_top: 0.0,
                    offset_left: 0.0,
                    box_shadow: None,
                    visible: true,
                    clip_rect: None,
                    transform: None,
                    background_gradient: None,
                    background_radial_gradient: None,
                    border_radius: 0.0,
                    outline_width: 0.0,
                    outline_color: None,
                    text_indent: 0.0,
                    letter_spacing: 0.0,
                    word_spacing: 0.0,
                    vertical_align: crate::style::computed::VerticalAlign::Baseline,
                    z_index: 0,
                    heading_level: None,
                },
            )],
        };
        let pdf = render_pdf_with_fonts(&[page], PageSize::A4, Margin::default(), &fonts).unwrap();
        let pdf_str = String::from_utf8_lossy(&pdf);
        assert!(
            pdf_str.contains("/BaseFont /TestFont"),
            "Should have custom font BaseFont entry"
        );
        assert!(
            pdf_str.contains("/Subtype /TrueType"),
            "Should have TrueType subtype"
        );
        assert!(
            pdf_str.contains("/FontDescriptor"),
            "Should have FontDescriptor reference"
        );
        assert!(
            pdf_str.contains("/FontFile2"),
            "Should have FontFile2 reference for embedded TTF"
        );
        assert!(
            pdf_str.contains("/TestFont"),
            "Should reference custom font name"
        );
    }

    #[test]
    fn ext_gstate_objects_rendered() {
        // Covers line 2011: ExtGState objects in resource dict
        let html = r#"<div style="opacity: 0.3">Dim</div><div style="opacity: 0.7">Bright</div>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let pdf_str = String::from_utf8_lossy(&pdf);
        assert!(pdf_str.contains("/ca 0.3"), "Should have fill opacity 0.3");
        assert!(pdf_str.contains("/ca 0.7"), "Should have fill opacity 0.7");
        assert!(
            pdf_str.contains("/ExtGState"),
            "Should have ExtGState in resources"
        );
        // Should have default GS reset
        assert!(
            pdf_str.contains("/GSDefault gs"),
            "Should reset to default graphics state"
        );
    }

    #[test]
    fn flexrow_cell_gradient_with_border_radius() {
        // Covers lines 1009-1060: FlexRow cell with linear gradient + border-radius clip
        let html = r#"<div style="display: flex"><div style="width: 150pt; background: linear-gradient(to bottom, red, blue); border-radius: 10pt">Grad Cell</div></div>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let pdf_str = String::from_utf8_lossy(&pdf);
        assert!(pdf_str.contains("Grad Cell"), "Should render cell text");
        assert!(
            pdf_str.contains("sh\n"),
            "Should have shading operator for cell gradient"
        );
    }

    #[test]
    fn half_leading_text_positioning() {
        // Text blocks should use half-leading model (not full line.height offset)
        let html = "<p style=\"font-size: 20pt; line-height: 2\">Test</p>";
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let pdf_str = String::from_utf8_lossy(&pdf);
        // Should contain Td operator for text positioning
        assert!(pdf_str.contains("Td\n"), "Should have text positioning");
        // Text should be rendered
        assert!(pdf_str.contains("(Test)"), "Should contain text content");
    }

    #[test]
    fn underline_in_flex_cell() {
        // Underline in flex cells should produce stroke commands
        let html = r#"<html><head><style>
            .row { display: flex; }
        </style></head><body>
        <div class="row">
            <div><u>Underlined in flex</u></div>
        </div>
        </body></html>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let pdf_str = String::from_utf8_lossy(&pdf);
        // Should have a stroke line for underline
        assert!(
            pdf_str.contains(" l\nS\n"),
            "Should draw underline stroke in flex cell"
        );
    }

    #[test]
    fn strikethrough_in_flex_cell() {
        let html = r#"<html><head><style>
            .row { display: flex; }
        </style></head><body>
        <div class="row">
            <div><del>Deleted in flex</del></div>
        </div>
        </body></html>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let pdf_str = String::from_utf8_lossy(&pdf);
        assert!(
            pdf_str.contains(" l\nS\n"),
            "Should draw strikethrough stroke in flex cell"
        );
    }

    #[test]
    fn underline_in_table_cell() {
        let html = r#"<table><tr><td><u>Underlined cell</u></td></tr></table>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let pdf_str = String::from_utf8_lossy(&pdf);
        assert!(
            pdf_str.contains(" l\nS\n"),
            "Should draw underline stroke in table cell"
        );
    }

    #[test]
    fn strikethrough_in_table_cell() {
        let html = r#"<table><tr><td><s>Struck cell</s></td></tr></table>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let pdf_str = String::from_utf8_lossy(&pdf);
        assert!(
            pdf_str.contains(" l\nS\n"),
            "Should draw strikethrough stroke in table cell"
        );
    }

    #[test]
    fn font_size_relative_underline_thickness() {
        // Large font should produce thicker underline than small font
        let html = r#"<p><span style="font-size: 6pt; text-decoration: underline">Small</span></p>
        <p><span style="font-size: 30pt; text-decoration: underline">Big</span></p>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let pdf_str = String::from_utf8_lossy(&pdf);
        // Both should have strokes; thickness should vary
        let w_count = pdf_str.matches(" w\n").count();
        assert!(
            w_count >= 2,
            "Should have at least 2 underline thickness commands, got {w_count}"
        );
    }

    #[test]
    fn table_cell_vertical_centering_with_metrics() {
        // Table cells with different row heights should center text
        let html = r#"<table>
            <tr>
                <td style="padding: 20pt">Centered</td>
                <td>Short</td>
            </tr>
        </table>"#;
        let nodes = parse_html(html).unwrap();
        let pages = layout(&nodes, PageSize::A4, Margin::default());
        let pdf = render_pdf(&pages, PageSize::A4, Margin::default()).unwrap();
        let pdf_str = String::from_utf8_lossy(&pdf);
        assert!(
            pdf_str.contains("(Centered)"),
            "Should render centered cell text"
        );
        assert!(pdf_str.contains("(Short)"), "Should render short cell text");
    }
}