rhwp 0.9.0

HWP/HWPX document engine for Rust applications, WebAssembly, and CLI automation
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
//! PDF renderers.
//!
//! The compatibility backend converts SVG output with svg2pdf/pdf-writer. The
//! opt-in direct backend records PageLayerTree replay into a Skia PDF canvas.
//! Both backends support single and multiple pages and are native-only.

// 같은 판정 소스를 각 usvg 버전이 실제 선택한 face에 적용한다.
use usvg as style_usvg;

#[cfg(not(target_arch = "wasm32"))]
#[path = "pdf_synthetic_bold.rs"]
mod synthetic_bold;
#[cfg(not(target_arch = "wasm32"))]
#[doc(hidden)]
pub use synthetic_bold::{prepare_svg_with_synthetic_bold, PdfBoldReport};

#[cfg(not(target_arch = "wasm32"))]
#[path = "pdf_synthetic_italic.rs"]
mod synthetic_italic;
#[cfg(not(target_arch = "wasm32"))]
#[doc(hidden)]
pub use synthetic_italic::{parse_svg_with_synthetic_italic, PdfItalicReport};

/// Native PDF implementation selected by callers such as `export-pdf`.
#[cfg(not(target_arch = "wasm32"))]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum PdfBackend {
    /// Existing PageRenderTree/layered SVG -> svg2pdf compatibility path.
    #[default]
    CompatibilitySvg,
    /// PageLayerTree -> Skia PDF recording path. Requires `native-skia`.
    DirectLayer,
}

#[cfg(not(target_arch = "wasm32"))]
impl PdfBackend {
    pub fn parse(value: &str) -> Option<Self> {
        match value.trim().to_ascii_lowercase().as_str() {
            "svg" | "compat" | "compat-svg" | "compatibility" => Some(Self::CompatibilitySvg),
            "direct" | "direct-layer" | "layer" | "layer-skia" | "skia" => Some(Self::DirectLayer),
            _ => None,
        }
    }

    pub fn as_str(self) -> &'static str {
        match self {
            Self::CompatibilitySvg => "svg",
            Self::DirectLayer => "direct",
        }
    }
}

/// Options specific to direct PageLayerTree PDF recording.
#[cfg(not(target_arch = "wasm32"))]
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq)]
pub struct DirectPdfExportOptions {
    /// Font directories loaded into the native Skia font manager.
    pub font_paths: Vec<std::path::PathBuf>,
    /// Raster resolution for effects that the PDF canvas cannot record as vectors.
    pub raster_dpi: f32,
    /// Optional deterministic document metadata. Dates are intentionally omitted.
    pub title: Option<String>,
    pub author: Option<String>,
    pub subject: Option<String>,
    pub keywords: Option<String>,
}

#[cfg(not(target_arch = "wasm32"))]
impl Default for DirectPdfExportOptions {
    fn default() -> Self {
        Self {
            font_paths: Vec::new(),
            raster_dpi: 144.0,
            title: None,
            author: None,
            subject: None,
            keywords: None,
        }
    }
}

/// Limits for static direct-PDF inspection. Values are clamped to the documented
/// hard bounds, including zero (which becomes one).
#[cfg(all(not(target_arch = "wasm32"), feature = "native-skia"))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DirectPdfPreflightLimits {
    /// Stored issues: 1..=4096, default 256.
    pub max_issues: usize,
    /// Visited pages, layer nodes, and paint operations combined:
    /// 1..=1_000_000, default 100_000.
    pub max_work_items: usize,
}

#[cfg(all(not(target_arch = "wasm32"), feature = "native-skia"))]
impl Default for DirectPdfPreflightLimits {
    fn default() -> Self {
        Self {
            max_issues: 256,
            max_work_items: 100_000,
        }
    }
}

/// Stable static rejection codes. Callers must not classify human messages.
#[cfg(all(not(target_arch = "wasm32"), feature = "native-skia"))]
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DirectPdfPreflightReason {
    EmptyDocument,
    InvalidRasterDpi,
    InvalidPageWidth,
    InvalidPageHeight,
    PageWidthTooLarge,
    PageHeightTooLarge,
    InvalidLayerBounds,
    InvalidClipBounds,
    InvalidPaintBounds,
    InvalidTextClipPath,
    UnsupportedLineStyle,
    InvalidStrokeWidth,
    InvalidArrowSize,
    InvalidArrowGeometry,
    InvalidConnectorShaft,
    UnsupportedArrowTangent,
    InvalidRotation,
    UnsupportedGradientType,
    GradientColorCountOutOfRange,
    InvalidGradientStops,
    InvalidGradientBounds,
    InvalidExpandedGradientStops,
    InvalidGradientAxis,
    InvalidRadialGradientCenter,
    InvalidRadialGradientCircle,
    UnsupportedPatternFill,
    UnsupportedShapeShadow,
    InvalidOpacity,
    UnsupportedImageFormat,
    InvalidImagePayload,
    InvalidBackgroundBorderWidth,
    UnsupportedBlackWhiteAdjustment,
    UnsupportedImageWatermark,
    UnsupportedPattern8x8,
    InvalidLineGeometry,
    InvalidCornerRadius,
    InvalidPathGeometry,
    InvalidConnectorEndpoints,
    InvalidTextGeometry,
    InvalidFootnoteFontSize,
    InvalidEquationGeometry,
}

/// Zero-based location in the supplied page selection. Node indices count a
/// depth-first pre-order traversal; operation indices count all ops on a page.
/// Document/option issues have no page, page issues no node, and layer/clip
/// issues no operation. `operation` names the PaintOp rather than message text.
#[cfg(all(not(target_arch = "wasm32"), feature = "native-skia"))]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct DirectPdfPreflightLocation {
    pub page_index: Option<usize>,
    pub node_index: Option<usize>,
    pub op_index: Option<usize>,
    pub operation: Option<&'static str>,
}

#[cfg(all(not(target_arch = "wasm32"), feature = "native-skia"))]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DirectPdfPreflightIssue {
    pub location: DirectPdfPreflightLocation,
    pub reason: DirectPdfPreflightReason,
    /// The existing export diagnostic, retained for display and compatibility.
    pub message: String,
}

#[cfg(all(not(target_arch = "wasm32"), feature = "native-skia"))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DirectPdfPreflightLimit {
    Issues,
    WorkItems,
}

/// A bounded static inspection, not a font/resource or successful-replay proof.
#[cfg(all(not(target_arch = "wasm32"), feature = "native-skia"))]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DirectPdfPreflightReport {
    pub issues: Vec<DirectPdfPreflightIssue>,
    /// True only when inspection stopped before completing the input. Reaching
    /// exactly the issue limit without another issue does not truncate a report.
    pub truncated: bool,
    pub limit_reached: Option<DirectPdfPreflightLimit>,
    pub work_items_checked: usize,
    /// Effective limits after applying the hard bounds.
    pub limits: DirectPdfPreflightLimits,
}

#[cfg(all(not(target_arch = "wasm32"), feature = "native-skia"))]
impl DirectPdfPreflightReport {
    /// True means all static checks completed without rejection. It does not
    /// promise image decoding, exact fonts, text-alternative preparation, or PDF
    /// recording. Export continues to fail closed on those runtime failures.
    pub fn is_admitted(&self) -> bool {
        self.issues.is_empty() && !self.truncated
    }
}

/// Inspect the static direct-PDF subset without creating fonts or a PDF canvas.
///
/// Pages follow selection order, nodes depth-first pre-order, ops source order,
/// and checks the same order as export. Each reason occurs at most once at one
/// location; equal reasons at distinct locations are retained. Independent
/// invalid fields on one op are all reported. Derived geometry is checked only
/// after its prerequisite fields pass. Image formats are inspected, but encoded
/// images are decoded only by export. A bounded report cannot guarantee that
/// font/resource preparation or actual strict replay will succeed.
#[cfg(all(not(target_arch = "wasm32"), feature = "native-skia"))]
pub fn preflight_direct_pdf(
    layer_trees: &[crate::paint::PageLayerTree],
    options: &DirectPdfExportOptions,
    limits: DirectPdfPreflightLimits,
) -> DirectPdfPreflightReport {
    direct_pdf_validation::preflight(layer_trees, options, limits)
}

#[cfg(all(not(target_arch = "wasm32"), feature = "native-skia"))]
fn validate_direct_pdf_tree(
    tree: &crate::paint::PageLayerTree,
    page_index: usize,
) -> Result<(), String> {
    let mut inspection = direct_pdf_validation::Inspection::first_error();
    direct_pdf_validation::validate_tree(tree, page_index, &mut inspection);
    match inspection.report.issues.into_iter().next() {
        Some(issue) => Err(issue.message),
        None => Ok(()),
    }
}

#[cfg(all(not(target_arch = "wasm32"), feature = "native-skia"))]
mod direct_pdf_validation {
    use super::{
        DirectPdfExportOptions, DirectPdfPreflightIssue, DirectPdfPreflightLimit,
        DirectPdfPreflightLimits, DirectPdfPreflightLocation, DirectPdfPreflightReason as Reason,
        DirectPdfPreflightReport,
    };
    use crate::model::image::ImageEffect;
    use crate::paint::{LayerNodeKind, PageLayerTree, PaintOp};
    use crate::renderer::render_tree::{BoundingBox, PathNode, ShapeTransform};
    use crate::renderer::{
        ArrowStyle, GradientFillInfo, LineRenderType, LineStyle, PathCommand, ShapeStyle,
    };

    pub(super) const CSS_PX_TO_PDF_POINT: f64 = 72.0 / 96.0;
    const MAX_PDF_PAGE_DIMENSION_POINTS: f64 = 14_400.0;

    pub(super) struct Failure {
        reason: Reason,
        pub(super) message: String,
    }

    fn failure(reason: Reason, message: String) -> Failure {
        Failure { reason, message }
    }

    pub(super) struct Inspection {
        pub(super) report: DirectPdfPreflightReport,
        location: DirectPdfPreflightLocation,
        location_start: usize,
        first_error: bool,
        stopped: bool,
    }

    impl Inspection {
        fn new(limits: DirectPdfPreflightLimits) -> Self {
            Self {
                report: DirectPdfPreflightReport {
                    issues: Vec::new(),
                    truncated: false,
                    limit_reached: None,
                    work_items_checked: 0,
                    limits: DirectPdfPreflightLimits {
                        max_issues: limits.max_issues.clamp(1, 4096),
                        max_work_items: limits.max_work_items.clamp(1, 1_000_000),
                    },
                },
                location: DirectPdfPreflightLocation::default(),
                location_start: 0,
                first_error: false,
                stopped: false,
            }
        }

        pub(super) fn first_error() -> Self {
            let mut result = Self::new(DirectPdfPreflightLimits::default());
            result.first_error = true;
            result
        }

        fn locate(&mut self, location: DirectPdfPreflightLocation) {
            self.location = location;
            self.location_start = self.report.issues.len();
        }

        fn begin_item(&mut self) -> bool {
            if self.stopped {
                return false;
            }
            if !self.first_error
                && self.report.work_items_checked == self.report.limits.max_work_items
            {
                self.truncate(DirectPdfPreflightLimit::WorkItems);
                return false;
            }
            self.report.work_items_checked = self.report.work_items_checked.saturating_add(1);
            true
        }

        fn truncate(&mut self, limit: DirectPdfPreflightLimit) {
            self.report.truncated = true;
            self.report.limit_reached = Some(limit);
            self.stopped = true;
        }

        fn reject(&mut self, failure: Failure) {
            if self.stopped
                || self.report.issues[self.location_start..]
                    .iter()
                    .any(|issue| issue.reason == failure.reason)
            {
                return;
            }
            if self.report.issues.len() == self.report.limits.max_issues {
                self.truncate(DirectPdfPreflightLimit::Issues);
                return;
            }
            self.report.issues.push(DirectPdfPreflightIssue {
                location: self.location,
                reason: failure.reason,
                message: failure.message,
            });
            if self.first_error {
                self.stopped = true;
            }
        }

        fn check(&mut self, result: Result<(), Failure>) -> bool {
            match result {
                Ok(()) => true,
                Err(error) => {
                    self.reject(error);
                    false
                }
            }
        }
    }

    fn is_valid_skia_scalar(value: f64) -> bool {
        value.is_finite() && value.abs() <= f32::MAX as f64
    }

    fn same_skia_point(left: (f64, f64), right: (f64, f64)) -> bool {
        (left.0 as f32, left.1 as f32) == (right.0 as f32, right.1 as f32)
    }

    fn valid_path_commands(commands: &[PathCommand]) -> bool {
        commands.iter().all(|command| match *command {
            PathCommand::MoveTo(x, y) | PathCommand::LineTo(x, y) => {
                is_valid_skia_scalar(x) && is_valid_skia_scalar(y)
            }
            PathCommand::CurveTo(x1, y1, x2, y2, x, y) => [x1, y1, x2, y2, x, y]
                .iter()
                .all(|value| is_valid_skia_scalar(*value)),
            PathCommand::ArcTo(rx, ry, rotation, _, _, x, y) => [rx, ry, rotation, x, y]
                .iter()
                .all(|value| is_valid_skia_scalar(*value)),
            PathCommand::ClosePath => true,
        })
    }

    fn validate_bbox(
        bbox: BoundingBox,
        page_index: usize,
        context: &str,
        reason: Reason,
    ) -> Result<(), Failure> {
        if [bbox.x, bbox.y, bbox.width, bbox.height]
            .iter()
            .any(|value| !is_valid_skia_scalar(*value))
            || bbox.width < 0.0
            || bbox.height < 0.0
        {
            return Err(failure(
                reason,
                format!(
                    "direct PDF page {} has invalid {context} bounds",
                    page_index + 1
                ),
            ));
        }
        Ok(())
    }

    fn unsupported(page_index: usize, op: &str, reason: Reason, detail: &str) -> Failure {
        failure(reason, format!(
            "direct PDF page {} cannot replay {op} without visual loss: {detail}; use the svg backend",
            page_index + 1
        ))
    }

    fn validate_line_style(
        style: &LineStyle,
        page_index: usize,
        op: &str,
        inspection: &mut Inspection,
    ) -> bool {
        let mut valid = true;
        if style.line_type != LineRenderType::Single || style.shadow.is_some() {
            inspection.reject(unsupported(
                page_index,
                op,
                Reason::UnsupportedLineStyle,
                "multi-line or shadow style",
            ));
            valid = false;
        }
        if !is_valid_skia_scalar(style.width) || style.width < 0.0 {
            inspection.reject(failure(
                Reason::InvalidStrokeWidth,
                format!(
                    "direct PDF page {} has invalid {op} stroke width: {}",
                    page_index + 1,
                    style.width
                ),
            ));
            valid = false;
        }
        if [
            (style.start_arrow, style.start_arrow_size),
            (style.end_arrow, style.end_arrow_size),
        ]
        .into_iter()
        .any(|(arrow, size)| arrow != ArrowStyle::None && size > 8)
        {
            inspection.reject(unsupported(
                page_index,
                op,
                Reason::InvalidArrowSize,
                "invalid arrow size",
            ));
            valid = false;
        }
        valid
    }

    fn has_skia_outline_area(commands: &[PathCommand]) -> bool {
        // Test the actual f32 outline, including translations that expose a
        // collapsed arrowhead. Compute the determinant in f64 to avoid overflow.
        let point = |x: f64, y: f64| (f64::from(x as f32), f64::from(y as f32));
        let mut points = Vec::new();
        for command in commands {
            match *command {
                PathCommand::MoveTo(x, y) | PathCommand::LineTo(x, y) => points.push(point(x, y)),
                PathCommand::CurveTo(a, b, c, d, e, f) => {
                    points.extend([point(a, b), point(c, d), point(e, f)]);
                }
                PathCommand::ClosePath => {}
                PathCommand::ArcTo(..) => return false,
            }
        }
        let Some(&(x0, y0)) = points.first() else {
            return false;
        };
        let Some(&(x1, y1)) = points.iter().find(|&&p| p != (x0, y0)) else {
            return false;
        };
        points
            .iter()
            .any(|&(x, y)| (x1 - x0) * (y - y0) != (y1 - y0) * (x - x0))
    }

    fn validate_arrow_heads(
        heads: &[crate::renderer::arrow::ArrowHead],
        style: &LineStyle,
        page_index: usize,
        op: &str,
    ) -> Result<(), Failure> {
        let requested = usize::from(style.start_arrow != ArrowStyle::None)
            + usize::from(style.end_arrow != ArrowStyle::None);
        if heads.len() != requested
            || heads.iter().any(|head| {
                !valid_path_commands(&head.commands) || !has_skia_outline_area(&head.commands)
            })
        {
            return Err(unsupported(
                page_index,
                op,
                Reason::InvalidArrowGeometry,
                "invalid arrow geometry",
            ));
        }
        Ok(())
    }

    fn validate_connector_shaft(
        path: &PathNode,
        style: &LineStyle,
        page_index: usize,
    ) -> Result<(), Failure> {
        let invalid = || {
            unsupported(
                page_index,
                "connector",
                Reason::InvalidConnectorShaft,
                "invalid connector shaft",
            )
        };
        let Some((PathCommand::MoveTo(x1, y1), segments)) = path.commands.split_first() else {
            return Err(invalid());
        };
        if segments.is_empty()
            || segments.iter().any(|command| {
                !matches!(command, PathCommand::LineTo(..) | PathCommand::CurveTo(..))
            })
        {
            return Err(invalid());
        }
        let endpoint = |command: &PathCommand| match *command {
            PathCommand::LineTo(x, y) | PathCommand::CurveTo(_, _, _, _, x, y) => (x, y),
            _ => unreachable!("validated open connector segment"),
        };
        let (x2, y2) = endpoint(segments.last().expect("nonempty connector"));
        if path.connector_endpoints != Some((*x1, *y1, x2, y2)) {
            return Err(invalid());
        }
        // The shared producer uses first/last controls, rather than deriving a
        // higher-order Bezier tangent for an endpoint-coincident control.
        let start_control = match segments[0] {
            PathCommand::LineTo(x, y) | PathCommand::CurveTo(x, y, ..) => (x, y),
            _ => unreachable!("validated open connector segment"),
        };
        let end_control = match *segments.last().expect("nonempty connector") {
            PathCommand::CurveTo(_, _, x, y, _, _) => (x, y),
            PathCommand::LineTo(..) => {
                if segments.len() == 1 {
                    (*x1, *y1)
                } else {
                    endpoint(&segments[segments.len() - 2])
                }
            }
            _ => unreachable!("validated open connector segment"),
        };
        if (style.start_arrow != ArrowStyle::None && same_skia_point(start_control, (*x1, *y1)))
            || (style.end_arrow != ArrowStyle::None && same_skia_point(end_control, (x2, y2)))
        {
            return Err(unsupported(
                page_index,
                "connector",
                Reason::UnsupportedArrowTangent,
                "unsupported arrow tangent",
            ));
        }
        Ok(())
    }

    fn validate_transform(
        transform: ShapeTransform,
        page_index: usize,
        op: &str,
    ) -> Result<(), Failure> {
        if !is_valid_skia_scalar(transform.rotation) {
            return Err(failure(
                Reason::InvalidRotation,
                format!(
                    "direct PDF page {} has invalid {op} rotation",
                    page_index + 1
                ),
            ));
        }
        Ok(())
    }

    fn validate_gradient(
        gradient: &GradientFillInfo,
        bbox: BoundingBox,
        page_index: usize,
        op: &str,
        inspection: &mut Inspection,
    ) {
        if inspection.stopped {
            return;
        }
        let supported_type = matches!(gradient.gradient_type, 1 | 2);
        if !supported_type {
            inspection.reject(unsupported(
                page_index,
                op,
                Reason::UnsupportedGradientType,
                "non-linear gradient fill",
            ));
        }
        let valid_center = gradient.gradient_type != 2
            || ((0..=100).contains(&gradient.center_x) && (0..=100).contains(&gradient.center_y));
        if !valid_center {
            inspection.reject(unsupported(
                page_index,
                op,
                Reason::InvalidRadialGradientCenter,
                "radial gradient center outside 0..=100 percent",
            ));
        }
        let valid_count = (2..=4096).contains(&gradient.colors.len());
        if !valid_count {
            inspection.reject(unsupported(
                page_index,
                op,
                Reason::GradientColorCountOutOfRange,
                "gradient color count outside 2..=4096",
            ));
        }
        let valid_stops = gradient.positions.is_empty()
            || (gradient.positions.len() == gradient.colors.len()
                && gradient
                    .positions
                    .iter()
                    .all(|position| position.is_finite() && (0.0..=1.0).contains(position))
                && gradient.positions.windows(2).all(|pair| pair[0] <= pair[1]));
        if !valid_stops {
            inspection.reject(unsupported(
                page_index,
                op,
                Reason::InvalidGradientStops,
                "invalid gradient stop positions",
            ));
        }
        let bounds = skia_safe::Rect::from_xywh(
            bbox.x as f32,
            bbox.y as f32,
            bbox.width as f32,
            bbox.height as f32,
        );
        let valid_bounds = bounds.is_finite()
            && !bounds.is_empty()
            && bounds.width().is_finite()
            && bounds.height().is_finite();
        if !valid_bounds {
            inspection.reject(unsupported(
                page_index,
                op,
                Reason::InvalidGradientBounds,
                "invalid gradient replay bounds",
            ));
        }
        // Derived checks require a valid, bounded source. Independent source
        // failures above are still all reported, without normalizing bad stops.
        if inspection.stopped
            || !supported_type
            || !valid_center
            || !valid_count
            || !valid_stops
            || !valid_bounds
        {
            return;
        }
        let (colors, positions) = crate::renderer::linear_gradient_color_stops(
            gradient,
            bbox.x,
            bbox.y,
            bbox.width,
            bbox.height,
        );
        if colors.len() < 2
            || colors.len() > 8192
            || colors.len() != positions.len()
            || positions
                .iter()
                .any(|position| !position.is_finite() || !(0.0..=1.0).contains(position))
            || positions.windows(2).any(|pair| pair[0] > pair[1])
        {
            inspection.reject(unsupported(
                page_index,
                op,
                Reason::InvalidExpandedGradientStops,
                "invalid expanded gradient stop positions",
            ));
        }
        if gradient.gradient_type == 2 {
            // Distinct source stops must remain distinct in the f32 shader.
            // Deliberate equal-position hard stops are preserved unchanged.
            if positions
                .windows(2)
                .any(|pair| pair[0] < pair[1] && pair[0] as f32 == pair[1] as f32)
            {
                inspection.reject(unsupported(
                    page_index,
                    op,
                    Reason::InvalidExpandedGradientStops,
                    "collapsed radial gradient stop positions",
                ));
            }
            inspection.check(validate_radial_circle(gradient, bbox, page_index, op));
            return;
        }
        let (x1, y1, x2, y2) = crate::renderer::linear_gradient_axis(
            gradient.angle,
            bbox.x,
            bbox.y,
            bbox.width,
            bbox.height,
        );
        let dx = x2 as f32 - x1 as f32;
        let dy = y2 as f32 - y1 as f32;
        let length_squared = dx * dx + dy * dy;
        if [x1, y1, x2, y2]
            .into_iter()
            .any(|value| !is_valid_skia_scalar(value))
            || !length_squared.is_finite()
            || length_squared < 1.0
        {
            inspection.reject(unsupported(
                page_index,
                op,
                Reason::InvalidGradientAxis,
                "invalid gradient axis",
            ));
        }
    }

    fn validate_radial_circle(
        gradient: &GradientFillInfo,
        bbox: BoundingBox,
        page_index: usize,
        op: &str,
    ) -> Result<(), Failure> {
        let invalid = || {
            unsupported(
                page_index,
                op,
                Reason::InvalidRadialGradientCircle,
                "invalid radial gradient circle",
            )
        };
        // Native and direct PDF replay consume this same physical circle:
        // source center to the farthest corner, without per-axis normalization.
        let (cx, cy, radius) = crate::renderer::gradient_geometry::radial_circle(
            (bbox.x, bbox.y, bbox.width, bbox.height),
            gradient.center_x,
            gradient.center_y,
        )
        .ok_or_else(invalid)?;
        if [cx, cy, radius]
            .into_iter()
            .any(|value| !is_valid_skia_scalar(value))
        {
            return Err(invalid());
        }
        let (cx, cy, radius) = (cx as f32, cy as f32, radius as f32);
        let squared_radius = radius * radius;
        // Keep the initial numerical subset explicit. Tiny/huge radii and
        // circles collapsed against a large center must fail before Skia can
        // substitute a solid fill or a degenerate shader.
        if !squared_radius.is_finite()
            || squared_radius < 1.0
            || ![cx - radius, cx + radius, cy - radius, cy + radius]
                .into_iter()
                .all(f32::is_finite)
            || cx - radius >= cx
            || cx + radius <= cx
            || cy - radius >= cy
            || cy + radius <= cy
        {
            return Err(invalid());
        }
        Ok(())
    }

    fn validate_shape_style(
        style: &ShapeStyle,
        gradient: Option<&GradientFillInfo>,
        bbox: BoundingBox,
        page_index: usize,
        op: &str,
        inspection: &mut Inspection,
    ) {
        if let Some(gradient) = gradient {
            validate_gradient(gradient, bbox, page_index, op, inspection);
        }
        if style.pattern.is_some() {
            inspection.reject(unsupported(
                page_index,
                op,
                Reason::UnsupportedPatternFill,
                "pattern fill",
            ));
        }
        if style.shadow.is_some() {
            inspection.reject(unsupported(
                page_index,
                op,
                Reason::UnsupportedShapeShadow,
                "shape shadow",
            ));
        }
        if !is_valid_skia_scalar(style.opacity) || !(0.0..=1.0).contains(&style.opacity) {
            inspection.reject(failure(
                Reason::InvalidOpacity,
                format!(
                    "direct PDF page {} has invalid {op} opacity: {}",
                    page_index + 1,
                    style.opacity
                ),
            ));
        }
        if !is_valid_skia_scalar(style.stroke_width) || style.stroke_width < 0.0 {
            inspection.reject(failure(
                Reason::InvalidStrokeWidth,
                format!(
                    "direct PDF page {} has invalid {op} stroke width: {}",
                    page_index + 1,
                    style.stroke_width
                ),
            ));
        }
    }

    fn validate_image_payload(
        data: &[u8],
        page_index: usize,
        context: &str,
        decode: bool,
    ) -> Result<(), Failure> {
        let format = match crate::renderer::image_resolver::detect_image_mime_type(data) {
            "image/png" => image::ImageFormat::Png,
            "image/jpeg" => image::ImageFormat::Jpeg,
            "image/gif" => image::ImageFormat::Gif,
            "image/bmp" => image::ImageFormat::Bmp,
            "image/tiff" => image::ImageFormat::Tiff,
            format => {
                return Err(failure(Reason::UnsupportedImageFormat, format!(
                    "direct PDF page {} does not support {context} payload format {format}; use the svg backend",
                    page_index + 1
                )));
            }
        };
        if !decode {
            return Ok(());
        }
        image::load_from_memory_with_format(data, format)
            .map(|_| ())
            .map_err(|error| {
                failure(
                    Reason::InvalidImagePayload,
                    format!(
                        "direct PDF page {} cannot decode {context} payload: {error}",
                        page_index + 1
                    ),
                )
            })
    }

    fn op_name(op: &PaintOp) -> &'static str {
        match op {
            PaintOp::PageBackground { .. } => "pageBackground",
            PaintOp::TextRun { .. } => "textRun",
            PaintOp::GlyphRun { .. } => "glyphRun",
            PaintOp::GlyphOutline { .. } => "glyphOutline",
            PaintOp::CharOverlap { .. } => "charOverlap",
            PaintOp::TextControlMark { .. } => "textControlMark",
            PaintOp::TabLeader { .. } => "tabLeader",
            PaintOp::TextDecoration { .. } => "textDecoration",
            PaintOp::ControlLabel { .. } => "controlLabel",
            PaintOp::FootnoteMarker { .. } => "footnoteMarker",
            PaintOp::Line { .. } => "line",
            PaintOp::Rectangle { .. } => "rectangle",
            PaintOp::Ellipse { .. } => "ellipse",
            PaintOp::Path { .. } => "path",
            PaintOp::Image { .. } => "image",
            PaintOp::Equation { .. } => "equation",
            PaintOp::FormObject { .. } => "formObject",
            PaintOp::Placeholder { .. } => "placeholder",
            PaintOp::RawSvg { .. } => "rawSvg",
        }
    }

    fn validate_op(op: &PaintOp, page_index: usize, inspection: &mut Inspection) {
        inspection.check(validate_bbox(
            op.bounds(),
            page_index,
            "paint operation",
            Reason::InvalidPaintBounds,
        ));
        match op {
            PaintOp::PageBackground { bbox, background } => {
                if let Some(gradient) = background.gradient.as_deref() {
                    validate_gradient(gradient, *bbox, page_index, "page background", inspection);
                }
                if !is_valid_skia_scalar(background.border_width) || background.border_width < 0.0 {
                    inspection.reject(failure(
                        Reason::InvalidBackgroundBorderWidth,
                        format!(
                            "direct PDF page {} has invalid page background border width",
                            page_index + 1
                        ),
                    ));
                }
                if inspection.stopped {
                    return;
                }
                if let Some(image) = &background.image {
                    inspection.check(validate_image_payload(
                        &image.data,
                        page_index,
                        "page background image",
                        inspection.first_error,
                    ));
                    if image.effect == ImageEffect::BlackWhite
                        && (image.brightness != 0 || image.contrast != 0)
                    {
                        inspection.reject(unsupported(
                            page_index,
                            "page background image",
                            Reason::UnsupportedBlackWhiteAdjustment,
                            "unbaked BlackWhite brightness or contrast",
                        ));
                    }
                    if image.is_real_picture_watermark_tone_preset() {
                        inspection.reject(unsupported(
                            page_index,
                            "page background image",
                            Reason::UnsupportedImageWatermark,
                            "unbaked RealPic watermark tone",
                        ));
                    }
                    if image.effect == ImageEffect::Pattern8x8 {
                        inspection.reject(unsupported(
                            page_index,
                            "page background image",
                            Reason::UnsupportedPattern8x8,
                            "Pattern8x8 effect",
                        ));
                    }
                }
            }
            PaintOp::Line { line, .. } => {
                inspection.check(validate_transform(line.transform, page_index, "line"));
                let valid_style = validate_line_style(&line.style, page_index, "line", inspection);
                let valid_geometry = [line.x1, line.y1, line.x2, line.y2]
                    .iter()
                    .all(|value| is_valid_skia_scalar(*value))
                    && !((line.style.start_arrow != ArrowStyle::None
                        || line.style.end_arrow != ArrowStyle::None)
                        && same_skia_point((line.x1, line.y1), (line.x2, line.y2)));
                if !valid_geometry {
                    inspection.reject(failure(
                        Reason::InvalidLineGeometry,
                        format!(
                            "direct PDF page {} has invalid line geometry",
                            page_index + 1
                        ),
                    ));
                }
                if valid_style && valid_geometry && !inspection.stopped {
                    inspection.check(validate_arrow_heads(
                        &crate::renderer::arrow::line_heads(
                            (line.x1, line.y1, line.x2, line.y2),
                            &line.style,
                        ),
                        &line.style,
                        page_index,
                        "line",
                    ));
                }
            }
            PaintOp::Rectangle { bbox, rect } => {
                inspection.check(validate_transform(rect.transform, page_index, "rectangle"));
                if !is_valid_skia_scalar(rect.corner_radius) || rect.corner_radius < 0.0 {
                    inspection.reject(failure(
                        Reason::InvalidCornerRadius,
                        format!(
                            "direct PDF page {} has invalid rectangle corner radius",
                            page_index + 1
                        ),
                    ));
                }
                validate_shape_style(
                    &rect.style,
                    rect.gradient.as_deref(),
                    *bbox,
                    page_index,
                    "rectangle",
                    inspection,
                );
            }
            PaintOp::Ellipse { bbox, ellipse } => {
                inspection.check(validate_transform(ellipse.transform, page_index, "ellipse"));
                validate_shape_style(
                    &ellipse.style,
                    ellipse.gradient.as_deref(),
                    *bbox,
                    page_index,
                    "ellipse",
                    inspection,
                );
            }
            PaintOp::Path { bbox, path } => {
                inspection.check(validate_transform(path.transform, page_index, "path"));
                validate_shape_style(
                    &path.style,
                    path.gradient.as_deref(),
                    *bbox,
                    page_index,
                    "path",
                    inspection,
                );
                let valid_geometry = valid_path_commands(&path.commands);
                if !valid_geometry {
                    inspection.reject(failure(
                        Reason::InvalidPathGeometry,
                        format!(
                            "direct PDF page {} has invalid path geometry",
                            page_index + 1
                        ),
                    ));
                }
                let valid_endpoints = path.connector_endpoints.is_none_or(|(x1, y1, x2, y2)| {
                    [x1, y1, x2, y2].into_iter().all(is_valid_skia_scalar)
                });
                if !valid_endpoints {
                    inspection.reject(failure(
                        Reason::InvalidConnectorEndpoints,
                        format!(
                            "direct PDF page {} has invalid connector endpoints",
                            page_index + 1
                        ),
                    ));
                }
                if let Some(style) = &path.line_style {
                    let valid_style =
                        validate_line_style(style, page_index, "connector", inspection);
                    let has_arrows = style.start_arrow != ArrowStyle::None
                        || style.end_arrow != ArrowStyle::None;
                    let valid_tangent = !has_arrows
                        || !path.commands.iter().any(|command| {
                            matches!(command, PathCommand::ArcTo(..) | PathCommand::ClosePath)
                        });
                    if !valid_tangent {
                        inspection.reject(unsupported(
                            page_index,
                            "connector",
                            Reason::UnsupportedArrowTangent,
                            "unsupported arrow tangent",
                        ));
                    }
                    if valid_style
                        && valid_geometry
                        && valid_endpoints
                        && valid_tangent
                        && !inspection.stopped
                    {
                        let valid_shaft = !has_arrows
                            || inspection.check(validate_connector_shaft(path, style, page_index));
                        if valid_shaft && !inspection.stopped {
                            inspection.check(validate_arrow_heads(
                                &crate::renderer::arrow::connector_heads(path),
                                style,
                                page_index,
                                "connector",
                            ));
                        }
                    }
                }
            }
            PaintOp::Image {
                image, resolved, ..
            } => {
                inspection.check(validate_transform(image.transform, page_index, "image"));
                if inspection.stopped {
                    return;
                }
                if let Some(data) = resolved
                    .as_deref()
                    .map(|payload| &payload.data[..])
                    .or(image.data.as_deref())
                {
                    inspection.check(validate_image_payload(
                        data,
                        page_index,
                        "image",
                        inspection.first_error,
                    ));
                }
                let baked = resolved
                    .as_deref()
                    .is_some_and(|payload| payload.suppress_effects);
                if !baked
                    && image.effect == ImageEffect::BlackWhite
                    && (image.brightness != 0 || image.contrast != 0)
                {
                    inspection.reject(unsupported(
                        page_index,
                        "image",
                        Reason::UnsupportedBlackWhiteAdjustment,
                        "unbaked BlackWhite brightness or contrast",
                    ));
                }
                if !baked && image.is_watermark() {
                    inspection.reject(unsupported(
                        page_index,
                        "image",
                        Reason::UnsupportedImageWatermark,
                        "unbaked image watermark tone or opacity",
                    ));
                }
                if !baked && image.effect == ImageEffect::Pattern8x8 {
                    inspection.reject(unsupported(
                        page_index,
                        "image",
                        Reason::UnsupportedPattern8x8,
                        "Pattern8x8 effect",
                    ));
                }
                if !is_valid_skia_scalar(image.opacity) || !(0.0..=1.0).contains(&image.opacity) {
                    inspection.reject(failure(
                        Reason::InvalidOpacity,
                        format!(
                            "direct PDF page {} has invalid image opacity: {}",
                            page_index + 1,
                            image.opacity
                        ),
                    ));
                }
            }
            PaintOp::TextRun { run, .. } => {
                if [
                    run.baseline,
                    run.rotation,
                    run.style.font_size,
                    run.style.letter_spacing,
                    run.style.ratio,
                ]
                .iter()
                .any(|value| !is_valid_skia_scalar(*value))
                {
                    inspection.reject(failure(
                        Reason::InvalidTextGeometry,
                        format!(
                            "direct PDF page {} has invalid text geometry",
                            page_index + 1
                        ),
                    ));
                }
            }
            PaintOp::FootnoteMarker { marker, .. } => {
                if !is_valid_skia_scalar(marker.base_font_size) {
                    inspection.reject(failure(
                        Reason::InvalidFootnoteFontSize,
                        format!(
                            "direct PDF page {} has invalid footnote marker font size",
                            page_index + 1
                        ),
                    ));
                }
            }
            PaintOp::Equation { equation, .. } => {
                if !is_valid_skia_scalar(equation.font_size)
                    || !is_valid_skia_scalar(equation.layout_box.width)
                    || !is_valid_skia_scalar(equation.layout_box.height)
                {
                    inspection.reject(failure(
                        Reason::InvalidEquationGeometry,
                        format!(
                            "direct PDF page {} has invalid equation geometry",
                            page_index + 1
                        ),
                    ));
                }
            }
            PaintOp::GlyphRun { .. }
            | PaintOp::GlyphOutline { .. }
            | PaintOp::CharOverlap { .. }
            | PaintOp::TextControlMark { .. }
            | PaintOp::TabLeader { .. }
            | PaintOp::TextDecoration { .. }
            | PaintOp::ControlLabel { .. }
            | PaintOp::FormObject { .. }
            | PaintOp::Placeholder { .. }
            | PaintOp::RawSvg { .. } => {}
        }
    }

    pub(super) fn validate_tree(
        tree: &PageLayerTree,
        page_index: usize,
        inspection: &mut Inspection,
    ) {
        // A stack of iterators bounds traversal storage by visited depth rather
        // than allocating a copy of every sibling. No recursive validator stack.
        let mut pending = vec![std::slice::from_ref(&tree.root).iter()];
        let mut node_index = 0;
        let mut op_index = 0;
        while let Some(siblings) = pending.last_mut() {
            let Some(node) = siblings.next() else {
                pending.pop();
                continue;
            };
            if !inspection.begin_item() {
                break;
            }
            let location = DirectPdfPreflightLocation {
                page_index: Some(page_index),
                node_index: Some(node_index),
                ..Default::default()
            };
            node_index += 1;
            inspection.locate(location);
            inspection.check(validate_bbox(
                node.bounds,
                page_index,
                "layer",
                Reason::InvalidLayerBounds,
            ));
            if inspection.stopped {
                break;
            }
            match &node.kind {
                LayerNodeKind::Group { children, .. } => pending.push(children.iter()),
                LayerNodeKind::ClipPath { paths, child } => {
                    if !crate::model::text_clip::valid(paths) {
                        inspection.reject(failure(
                            Reason::InvalidTextClipPath,
                            "invalid text clip path".into(),
                        ));
                    }
                    if !inspection.stopped {
                        pending.push(std::slice::from_ref(child.as_ref()).iter());
                    }
                }
                LayerNodeKind::ClipRect { clip, child, .. } => {
                    inspection.check(validate_bbox(
                        *clip,
                        page_index,
                        "clip",
                        Reason::InvalidClipBounds,
                    ));
                    if !inspection.stopped {
                        pending.push(std::slice::from_ref(child.as_ref()).iter());
                    }
                }
                LayerNodeKind::Leaf { ops } => {
                    for op in ops {
                        if !inspection.begin_item() {
                            break;
                        }
                        inspection.locate(DirectPdfPreflightLocation {
                            op_index: Some(op_index),
                            operation: Some(op_name(op)),
                            ..location
                        });
                        op_index += 1;
                        validate_op(op, page_index, inspection);
                    }
                }
            }
        }
    }

    pub(super) fn page_dimension(value: f64, width: bool) -> Result<f32, Failure> {
        let label = if width { "width" } else { "height" };
        let points = value * CSS_PX_TO_PDF_POINT;
        let skia_points = points as f32;
        // A positive f64 page extent can underflow to zero in Skia's scalar
        // type. Reject before begin_page, whose native canvas must be non-null.
        if !points.is_finite() || points <= 0.0 || skia_points <= 0.0 {
            return Err(failure(
                if width {
                    Reason::InvalidPageWidth
                } else {
                    Reason::InvalidPageHeight
                },
                format!("invalid direct PDF page {label}: {value}"),
            ));
        }
        if points > MAX_PDF_PAGE_DIMENSION_POINTS {
            return Err(failure(if width { Reason::PageWidthTooLarge } else { Reason::PageHeightTooLarge },
                format!("direct PDF page {label} exceeds {MAX_PDF_PAGE_DIMENSION_POINTS} points: {points}")));
        }
        Ok(skia_points)
    }

    pub(super) fn preflight(
        trees: &[PageLayerTree],
        options: &DirectPdfExportOptions,
        limits: DirectPdfPreflightLimits,
    ) -> DirectPdfPreflightReport {
        let mut inspection = Inspection::new(limits);
        if trees.is_empty() {
            inspection.reject(failure(
                Reason::EmptyDocument,
                "direct PDF export requires at least one page".into(),
            ));
        }
        if !options.raster_dpi.is_finite() || options.raster_dpi <= 0.0 {
            inspection.reject(failure(
                Reason::InvalidRasterDpi,
                format!("invalid direct PDF raster dpi: {}", options.raster_dpi),
            ));
        }
        for (page_index, tree) in trees.iter().enumerate() {
            if !inspection.begin_item() {
                break;
            }
            validate_tree(tree, page_index, &mut inspection);
            if inspection.stopped {
                break;
            }
            inspection.locate(DirectPdfPreflightLocation {
                page_index: Some(page_index),
                ..Default::default()
            });
            inspection.check(page_dimension(tree.page_width, true).map(|_| ()));
            inspection.check(page_dimension(tree.page_height, false).map(|_| ()));
        }
        inspection.report
    }
}

/// PDF 내보내기 폰트 설정.
///
/// `export-pdf`는 SVG를 usvg/svg2pdf로 변환하므로 generic font family와 수식 SVG
/// font-family를 PDF 변환 직전에 조정한다.
#[cfg(not(target_arch = "wasm32"))]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PdfExportOptions {
    /// serif generic fallback family.
    pub fallback_serif: String,
    /// sans-serif generic fallback family.
    pub fallback_sans: String,
    /// monospace generic fallback family.
    pub fallback_mono: String,
    /// 사용자 지정 수식 우선 폰트. None이면 기존 수식 font-family 체인을 유지한다.
    pub equation_font: Option<String>,
    /// 사용자 지정 폰트 탐색 디렉토리. 기본 탐색 경로보다 먼저 로드한다.
    pub font_paths: Vec<std::path::PathBuf>,
    /// 텍스트를 PDF 폰트로 임베드할지 여부. `false` 면 글리프를 path 로 변환한다.
    ///
    /// [Task #2264] 임베드 경로(폰트 서브셋)가 PDF 변환 메모리의 지배항이다.
    /// 실측(텍스트 1639개·이미지 2개인 1페이지 기준): `svg2pdf::to_chunk` 최대 RSS 가
    /// 164 MB → 69 MB 로 떨어진다. 대신 **PDF 의 텍스트 선택·검색 기능을 잃는다**
    /// (시각적 출력은 동일). 기본값은 종전 동작인 `true` 다.
    pub embed_text: bool,
}

#[cfg(not(target_arch = "wasm32"))]
impl Default for PdfExportOptions {
    fn default() -> Self {
        Self {
            fallback_serif: default_serif_family().to_string(),
            fallback_sans: default_sans_family().to_string(),
            fallback_mono: default_mono_family().to_string(),
            equation_font: None,
            font_paths: Vec::new(),
            embed_text: true,
        }
    }
}

#[cfg(all(not(target_arch = "wasm32"), target_os = "windows"))]
fn default_serif_family() -> &'static str {
    "바탕"
}

#[cfg(all(not(target_arch = "wasm32"), target_os = "windows"))]
fn default_sans_family() -> &'static str {
    "맑은 고딕"
}

#[cfg(all(not(target_arch = "wasm32"), target_os = "windows"))]
fn default_mono_family() -> &'static str {
    "D2Coding"
}

#[cfg(all(not(target_arch = "wasm32"), target_os = "linux"))]
fn default_serif_family() -> &'static str {
    "Noto Serif CJK KR"
}

#[cfg(all(not(target_arch = "wasm32"), target_os = "linux"))]
fn default_sans_family() -> &'static str {
    "Noto Sans CJK KR"
}

#[cfg(all(not(target_arch = "wasm32"), target_os = "linux"))]
fn default_mono_family() -> &'static str {
    "Noto Sans Mono CJK KR"
}

#[cfg(all(not(target_arch = "wasm32"), target_os = "macos"))]
fn default_serif_family() -> &'static str {
    "AppleMyungjo"
}

#[cfg(all(not(target_arch = "wasm32"), target_os = "macos"))]
fn default_sans_family() -> &'static str {
    "Apple SD Gothic Neo"
}

#[cfg(all(not(target_arch = "wasm32"), target_os = "macos"))]
fn default_mono_family() -> &'static str {
    "Menlo"
}

#[cfg(all(
    not(target_arch = "wasm32"),
    not(any(target_os = "windows", target_os = "linux", target_os = "macos"))
))]
fn default_serif_family() -> &'static str {
    "Noto Serif CJK KR"
}

#[cfg(all(
    not(target_arch = "wasm32"),
    not(any(target_os = "windows", target_os = "linux", target_os = "macos"))
))]
fn default_sans_family() -> &'static str {
    "Noto Sans CJK KR"
}

#[cfg(all(
    not(target_arch = "wasm32"),
    not(any(target_os = "windows", target_os = "linux", target_os = "macos"))
))]
fn default_mono_family() -> &'static str {
    "Noto Sans Mono CJK KR"
}

/// 폰트 데이터베이스를 초기화 (시스템 폰트 + 프로젝트 폰트 로드)
#[cfg(not(target_arch = "wasm32"))]
fn create_fontdb(options: &PdfExportOptions) -> usvg::fontdb::Database {
    let mut fontdb = usvg::fontdb::Database::new();
    fontdb.load_system_fonts();
    // [#2864] 조달 순서는 renderer::font_paths 가 단일 정의한다.
    // 종전의 ttfs/hwp·ttfs/windows(로컬 전용)와 /mnt/c/Windows/Fonts(WSL2 전용)는
    // 제거했다 — 서버·컨테이너에서 무의미하고 /mnt/c 는 #2268 간헐 행의 원인이었다.
    crate::renderer::font_paths::load_into_fontdb(&mut fontdb, &options.font_paths);
    fontdb.set_serif_family(options.fallback_serif.as_str());
    fontdb.set_sans_serif_family(options.fallback_sans.as_str());
    fontdb.set_monospace_family(options.fallback_mono.as_str());
    warn_missing_family(
        &fontdb,
        "serif",
        &options.fallback_serif,
        "--fallback-serif",
    );
    warn_missing_family(
        &fontdb,
        "sans-serif",
        &options.fallback_sans,
        "--fallback-sans",
    );
    warn_missing_family(
        &fontdb,
        "monospace",
        &options.fallback_mono,
        "--fallback-mono",
    );
    if let Some(equation_font) = options.equation_font.as_deref() {
        let family = first_font_family(equation_font);
        if !family.is_empty() {
            warn_missing_family(&fontdb, "equation", &family, "--equation-font");
        }
    }
    fontdb
}

// A document with more distinct fallback characters than this is unusual enough
// that keeping the stock resolver is safer than retaining an unbounded index.
#[cfg(not(target_arch = "wasm32"))]
const PDF_FONT_FALLBACK_INDEX_MAX_CHARS: usize = 4_096;

// Coverage is stored as one Option<bool> slot per visited face position. Cap the
// total logical slot length as well as the number of characters so Vec capacity
// and HashMap metadata cannot grow with an unbounded system font inventory.
#[cfg(not(target_arch = "wasm32"))]
const PDF_FONT_FALLBACK_INDEX_MAX_FACE_SLOTS: usize = 262_144;

#[cfg(not(target_arch = "wasm32"))]
#[derive(Debug)]
struct PdfFontFallbackIndex {
    database: Option<(std::sync::Weak<usvg::fontdb::Database>, usize)>,
    coverage_by_char: std::collections::HashMap<char, Vec<Option<bool>>>,
    face_slot_count: usize,
    disabled: bool,
}

#[cfg(not(target_arch = "wasm32"))]
impl PdfFontFallbackIndex {
    fn new() -> Self {
        Self {
            database: None,
            coverage_by_char: std::collections::HashMap::new(),
            face_slot_count: 0,
            disabled: false,
        }
    }

    fn disable(&mut self) {
        self.coverage_by_char.clear();
        self.face_slot_count = 0;
        self.disabled = true;
    }

    fn select(
        &mut self,
        c: char,
        used_fonts: &[usvg::fontdb::ID],
        fontdb: &std::sync::Arc<usvg::fontdb::Database>,
        max_chars: usize,
        max_face_slots: usize,
    ) -> PdfFontFallbackLookup {
        if self.disabled {
            return PdfFontFallbackLookup::Default;
        }

        // A custom select_font callback may add faces through Arc::make_mut. Cached
        // IDs and ordering only describe the exact database observed on first use;
        // fall back globally if that identity or face inventory changes.
        let database = std::sync::Arc::downgrade(fontdb);
        let face_count = fontdb.len();
        match self.database.as_ref() {
            None => self.database = Some((database, face_count)),
            Some((cached, cached_face_count))
                if *cached_face_count != face_count
                    || !std::sync::Weak::ptr_eq(cached, &database) =>
            {
                self.disable();
                return PdfFontFallbackLookup::Default;
            }
            Some(_) => {}
        }

        if !self.coverage_by_char.contains_key(&c) {
            if self.coverage_by_char.len() >= max_chars {
                self.disable();
                return PdfFontFallbackLookup::Default;
            }
            self.coverage_by_char.insert(c, Vec::new());
        }

        // Preserve usvg 0.45's exact short-circuit order: exclusion and face
        // compatibility are checked before the potentially expensive cmap probe,
        // and the first supporting face returns immediately. The index only
        // replaces has_char calls that stock usvg would otherwise repeat.
        let base_face = fontdb.face(used_fonts[0]);
        for (face_index, face) in fontdb.faces().enumerate() {
            if used_fonts.contains(&face.id) {
                continue;
            }
            let Some(base_face) = base_face else {
                return PdfFontFallbackLookup::Cached(None);
            };
            if base_face.style != face.style
                && base_face.weight != face.weight
                && base_face.stretch != face.stretch
            {
                continue;
            }

            let cached = self
                .coverage_by_char
                .get(&c)
                .and_then(|coverage| coverage.get(face_index))
                .copied()
                .flatten();
            let supports_char = match cached {
                Some(supports_char) => supports_char,
                None => {
                    let Some(required_len) = face_index.checked_add(1) else {
                        self.disable();
                        return PdfFontFallbackLookup::Default;
                    };
                    let current_len = self
                        .coverage_by_char
                        .get(&c)
                        .map_or(0, |coverage| coverage.len());
                    let additional_slots = required_len.saturating_sub(current_len);
                    let Some(next_face_slot_count) =
                        self.face_slot_count.checked_add(additional_slots)
                    else {
                        self.disable();
                        return PdfFontFallbackLookup::Default;
                    };
                    if next_face_slot_count > max_face_slots {
                        self.disable();
                        return PdfFontFallbackLookup::Default;
                    }

                    let supports_char = pdf_font_face_has_char(fontdb, face.id, c);
                    let coverage = self
                        .coverage_by_char
                        .get_mut(&c)
                        .expect("fallback coverage was inserted above");
                    if coverage.len() < required_len {
                        coverage.resize(required_len, None);
                        self.face_slot_count = next_face_slot_count;
                    }
                    coverage[face_index] = Some(supports_char);
                    supports_char
                }
            };
            if supports_char {
                return PdfFontFallbackLookup::Cached(Some(face.id));
            }
        }

        PdfFontFallbackLookup::Cached(None)
    }
}

#[cfg(not(target_arch = "wasm32"))]
enum PdfFontFallbackLookup {
    Cached(Option<usvg::fontdb::ID>),
    Default,
}

#[cfg(not(target_arch = "wasm32"))]
fn pdf_font_face_has_char(fontdb: &usvg::fontdb::Database, id: usvg::fontdb::ID, c: char) -> bool {
    fontdb
        .with_face_data(id, |font_data, face_index| {
            ttf_parser::Face::parse(font_data, face_index)
                .ok()
                .and_then(|face| face.glyph_index(c))
                .is_some()
        })
        .unwrap_or(false)
}

/// Builds the bounded fallback selector used by compatibility PDF conversion.
///
/// The limits are arguments so integration tests can exercise overflow without
/// manufacturing a production-sized font database. Callers should normally use
/// [`svgs_to_pdf_with_options`] instead.
#[cfg(not(target_arch = "wasm32"))]
#[doc(hidden)]
pub fn pdf_font_fallback_selector_with_limits(
    max_chars: usize,
    max_face_slots: usize,
) -> usvg::FallbackSelectionFn<'static> {
    let index = std::sync::Mutex::new(PdfFontFallbackIndex::new());
    let default_selector = usvg::FontResolver::default_fallback_selector();

    Box::new(move |c, used_fonts, fontdb| {
        let lookup = match index.lock() {
            Ok(mut index) => index.select(c, used_fonts, fontdb, max_chars, max_face_slots),
            Err(_) => PdfFontFallbackLookup::Default,
        };
        match lookup {
            PdfFontFallbackLookup::Cached(id) => id,
            PdfFontFallbackLookup::Default => default_selector(c, used_fonts, fontdb),
        }
    })
}

#[cfg(not(target_arch = "wasm32"))]
fn warn_missing_family(
    fontdb: &usvg::fontdb::Database,
    kind: &str,
    family: &str,
    option_name: &str,
) {
    if !font_family_exists(fontdb, family) {
        eprintln!(
            "WARN: fallback {kind} font '{family}' not found.\n      한글 또는 수식이 빈칸으로 렌더링될 수 있습니다.\n      {option_name} \"<family>\" 로 설치된 폰트를 지정하세요."
        );
    }
}

#[cfg(not(target_arch = "wasm32"))]
fn font_family_exists(fontdb: &usvg::fontdb::Database, family: &str) -> bool {
    fontdb.faces().any(|face| {
        face.families
            .iter()
            .any(|(name, _)| name == family || name.eq_ignore_ascii_case(family))
    })
}

/// SVG에서 없는 한글 폰트명에 fallback 추가
#[cfg(not(target_arch = "wasm32"))]
fn add_font_fallbacks(svg: &str, options: &PdfExportOptions) -> String {
    let serif = css_family_for_attr(&options.fallback_serif);
    let sans = css_family_for_attr(&options.fallback_sans);
    svg.replace(
        "font-family=\"휴먼명조\"",
        &format!("font-family=\"휴먼명조, {serif}, serif\""),
    )
    .replace(
        "font-family=\"HCI Poppy\"",
        &format!("font-family=\"HCI Poppy, {sans}, sans-serif\""),
    )
}

/// #3772: bold `<text>`/`<tspan>` 에서만 ExtraLight 를 뺀다.
///
/// SVG 생성기가 이미 뺀 경우 no-op. 외부 SVG 나 옛 골든을 svg2pdf 에 넣을 때도
/// ExtraLight(200) 이 bold 로 남지 않게 하는 PDF 직전 안전망이다.
#[cfg(not(target_arch = "wasm32"))]
fn drop_extralight_from_bold_svg_runs(svg: &str) -> String {
    let mut out = String::with_capacity(svg.len());
    let mut rest = svg;
    while let Some(rel) = rest.find('<') {
        out.push_str(&rest[..rel]);
        rest = &rest[rel..];
        let end = rest.find('>').map(|i| i + 1).unwrap_or(rest.len());
        let tag = &rest[..end];
        rest = &rest[end..];
        if svg_tag_is_text_run(tag) && svg_tag_is_bold_weight(tag) {
            out.push_str(&crate::renderer::drop_noto_sans_kr_extralight(tag));
        } else {
            out.push_str(tag);
        }
    }
    out.push_str(rest);
    out
}

#[cfg(not(target_arch = "wasm32"))]
fn svg_tag_is_text_run(tag: &str) -> bool {
    let Some(rest) = tag.strip_prefix('<') else {
        return false;
    };
    let name = rest
        .split(|c: char| c.is_ascii_whitespace() || c == '>' || c == '/')
        .next()
        .unwrap_or("");
    name.eq_ignore_ascii_case("text") || name.eq_ignore_ascii_case("tspan")
}

#[cfg(not(target_arch = "wasm32"))]
fn svg_tag_is_bold_weight(tag: &str) -> bool {
    let lower = tag.to_ascii_lowercase();
    if lower.contains("font-weight=\"bold\"") || lower.contains("font-weight='bold'") {
        return true;
    }
    for weight in ["600", "700", "800", "900"] {
        if lower.contains(&format!("font-weight=\"{weight}\""))
            || lower.contains(&format!("font-weight='{weight}'"))
        {
            return true;
        }
    }
    false
}

/// SVG→PDF 직전에 generic 폴백·수식 폰트·bold ExtraLight 제거를 적용한다.
#[cfg(not(target_arch = "wasm32"))]
pub fn apply_pdf_font_options(svg: &str, options: &PdfExportOptions) -> String {
    let svg = add_font_fallbacks(svg, options);
    let svg = drop_extralight_from_bold_svg_runs(&svg);
    if let Some(equation_font) = options.equation_font.as_deref() {
        let attr = format!(
            "font-family=\"{}\"",
            escape_xml_attr(&equation_font_chain(equation_font))
        );
        svg.replace(
            crate::renderer::equation::svg_render::DEFAULT_EQUATION_FONT_FAMILY_ATTR,
            &attr,
        )
    } else {
        svg
    }
}

#[cfg(not(target_arch = "wasm32"))]
fn equation_font_chain(equation_font: &str) -> String {
    if equation_font.contains(',') {
        return equation_font.trim().to_string();
    }
    let first = css_family_for_attr(equation_font);
    let default =
        "'Latin Modern Math', 'STIX Two Text', 'STIX Two Math', 'Times New Roman', 'Times', serif";
    if first == "'Latin Modern Math'" {
        default.to_string()
    } else {
        format!("{first}, {default}")
    }
}

#[cfg(not(target_arch = "wasm32"))]
fn first_font_family(value: &str) -> String {
    value
        .split(',')
        .next()
        .unwrap_or_default()
        .trim()
        .trim_matches('"')
        .trim_matches('\'')
        .to_string()
}

#[cfg(not(target_arch = "wasm32"))]
fn css_family_for_attr(family: &str) -> String {
    let family = family.trim();
    if family.eq_ignore_ascii_case("serif")
        || family.eq_ignore_ascii_case("sans-serif")
        || family.eq_ignore_ascii_case("monospace")
    {
        return family.to_string();
    }
    let escaped = escape_xml_attr(family);
    format!("'{escaped}'")
}

#[cfg(not(target_arch = "wasm32"))]
fn escape_xml_attr(value: &str) -> String {
    let mut escaped = String::with_capacity(value.len());
    for ch in value.chars() {
        match ch {
            '&' => escaped.push_str("&amp;"),
            '<' => escaped.push_str("&lt;"),
            '>' => escaped.push_str("&gt;"),
            '"' => escaped.push_str("&quot;"),
            '\'' => escaped.push_str("&apos;"),
            // XML 1.0 허용 문자: #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
            // 그 외(제어문자 등)는 제거 — PDF 에 심는 XMP 메타데이터가 불법 XML 이 되지 않도록 (#3382 계열)
            '\u{09}' | '\u{0A}' | '\u{0D}' => escaped.push(ch),
            '\u{20}'..='\u{D7FF}' | '\u{E000}'..='\u{FFFD}' | '\u{10000}'..='\u{10FFFF}' => {
                escaped.push(ch)
            }
            _ => {} // XML 무효 문자 제거
        }
    }
    escaped
}

/// [#3824] PDF 텍스트 표면(`ToUnicode`)의 한컴 PUA 를 표준 코드포인트로 바꾼다.
///
/// #3385 가 `export-text` 표면을 고쳤지만, 사용자가 실제로 검색하는 **PDF 표면**은
/// 그대로 PUA 를 내보내고 있었다. "①" 을 검색하면 안 걸리고 스크린리더는 사설 영역
/// 문자를 읽는다.
///
/// **렌더 결정은 건드리지 않는다.** 글리프 선택은 PUA 로 두어야 fallback 이 맞는다
/// (`map_pua_bullet_char` 주석 참조). 바꿀 곳은 글리프 → 유니코드 대응표뿐이다.
///
/// 매핑은 새로 짓지 않고 텍스트 표면이 쓰는 표(`pua_to_text_surface`)를 그대로
/// 재사용한다 — 두 표면이 갈리지 않게 하는 것이 이 수정의 요지다.
///
/// ## 왜 바이트 수준인가
///
/// `ToUnicode` CMap 은 svg2pdf 가 만든다. 그런데 한컴 PUA 의 뜻은 **rhwp 도메인
/// 지식**이라 범용 SVG 변환기가 알 이유가 없다. 그래서 rhwp 가 자기 출력에서
/// 대응표만 고친다.
///
/// 안전 근거 — 실측으로 확인한 세 성질에 기댄다.
///   1. CMap 스트림은 **비압축**이다(`/Type /CMap`, `/Filter` 없음).
///   2. svg2pdf 는 `beginbfchar` 만 쓴다(`beginbfrange` 0개).
///   3. 대체 문자열이 원본보다 짧으므로 **공백으로 채워 길이를 보존**한다 →
///      `/Length` 와 xref 오프셋을 건드리지 않는다. 채움 공백은 꺾쇠 **안**에
///      들어가는데(`<2460    >`), PDF 명세상 16진 문자열 안의 공백은 무시되므로
///      `<2460>` 과 같은 값이다.
///
/// 길이가 늘어나는 경우(다중 문자 대체)는 **건너뛴다** — 길이 보존이 깨지기 때문이다.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn remap_pua_in_tounicode(pdf: &mut [u8]) {
    const BEGIN: &[u8] = b"beginbfchar";
    const END: &[u8] = b"endbfchar";
    let mut cursor = 0usize;
    while let Some(rel) = find_bytes(&pdf[cursor..], BEGIN) {
        let start = cursor + rel + BEGIN.len();
        let Some(rel_end) = find_bytes(&pdf[start..], END) else {
            break;
        };
        let end = start + rel_end;
        remap_bfchar_block(&mut pdf[start..end]);
        cursor = end + END.len();
    }
}

#[cfg(not(target_arch = "wasm32"))]
fn find_bytes(hay: &[u8], needle: &[u8]) -> Option<usize> {
    if needle.is_empty() || hay.len() < needle.len() {
        return None;
    }
    hay.windows(needle.len()).position(|w| w == needle)
}

/// `<src> <dst>` 쌍이 늘어선 블록에서 dst 만 고친다.
#[cfg(not(target_arch = "wasm32"))]
fn remap_bfchar_block(block: &mut [u8]) {
    let mut spans: Vec<(usize, usize)> = Vec::new();
    let mut i = 0usize;
    while i < block.len() {
        if block[i] == b'<' {
            match block[i + 1..].iter().position(|&b| b == b'>') {
                Some(rel) => {
                    spans.push((i + 1, i + 1 + rel));
                    i += rel + 2;
                }
                None => break,
            }
            continue;
        }
        i += 1;
    }
    // 짝수 번째가 src, 홀수 번째가 dst 다.
    for pair in spans.chunks(2) {
        let dst = match pair {
            [_src, dst] => *dst,
            _ => continue,
        };
        let (s, e) = dst;
        let text = match utf16be_hex_to_string(&block[s..e]) {
            Some(t) => t,
            None => continue,
        };
        let mapped = crate::renderer::composer::pua_to_text_surface(&text);
        if mapped.as_ref() == text.as_str() {
            continue;
        }
        let hex = string_to_utf16be_hex(mapped.as_ref());
        if hex.len() > e - s {
            continue; // 길이 보존이 깨진다 — 손대지 않는다
        }
        block[s..s + hex.len()].copy_from_slice(hex.as_bytes());
        for b in &mut block[s + hex.len()..e] {
            *b = b' ';
        }
    }
}

#[cfg(not(target_arch = "wasm32"))]
fn utf16be_hex_to_string(hex: &[u8]) -> Option<String> {
    if hex.is_empty() || !hex.len().is_multiple_of(4) {
        return None;
    }
    let mut units = Vec::with_capacity(hex.len() / 4);
    for quad in hex.chunks(4) {
        let mut v: u16 = 0;
        for &b in quad {
            let d = (b as char).to_digit(16)? as u16;
            v = v.checked_mul(16)?.checked_add(d)?;
        }
        units.push(v);
    }
    String::from_utf16(&units).ok()
}

#[cfg(not(target_arch = "wasm32"))]
fn string_to_utf16be_hex(s: &str) -> String {
    let mut out = String::new();
    for unit in s.encode_utf16() {
        out.push_str(&format!("{unit:04X}"));
    }
    out
}

/// 단일 SVG를 PDF로 변환
#[cfg(not(target_arch = "wasm32"))]
pub fn svg_to_pdf(svg_content: &str) -> Result<Vec<u8>, String> {
    svgs_to_pdf(&[svg_content.to_string()])
}

/// 단일 SVG를 옵션 기반 PDF로 변환
#[cfg(not(target_arch = "wasm32"))]
pub fn svg_to_pdf_with_options(
    svg_content: &str,
    options: &PdfExportOptions,
) -> Result<Vec<u8>, String> {
    svgs_to_pdf_with_options(&[svg_content.to_string()], options)
}

/// #3773: 한 페이지의 svg2pdf `SubsetError` 를 문서 전체 실패로 올리지 않는다.
#[cfg(not(target_arch = "wasm32"))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Svg2pdfPageIsolation {
    /// 서브셋과 무관한 변환 오류. 문서 전체를 실패시킨다.
    Fatal,
    /// `embed_text=true` 첫 실패. 글리프 path 변환으로 한 번 재시도한다.
    RetryWithoutEmbedText,
    /// 재시도 뒤에도 `SubsetError`. 해당 페이지만 건너뛴다.
    SkipPage,
}

/// svg2pdf 페이지 변환 오류를 격리 정책으로 분류한다.
#[cfg(not(target_arch = "wasm32"))]
pub fn classify_svg2pdf_page_error(
    err: &svg2pdf::ConversionError,
    embed_text: bool,
    already_retried: bool,
) -> Svg2pdfPageIsolation {
    if !matches!(err, svg2pdf::ConversionError::SubsetError(_)) {
        return Svg2pdfPageIsolation::Fatal;
    }
    if embed_text && !already_retried {
        Svg2pdfPageIsolation::RetryWithoutEmbedText
    } else {
        Svg2pdfPageIsolation::SkipPage
    }
}

/// 시험용 dummy `SubsetError`. 실제 폰트 ID 가 없어도 격리 분기를 탈 수 있다.
#[cfg(not(target_arch = "wasm32"))]
pub fn svg2pdf_subset_error_stub() -> svg2pdf::ConversionError {
    svg2pdf::ConversionError::SubsetError(usvg::fontdb::ID::dummy())
}

/// 시험용 비-Subset 변환 오류. 문서 전체 실패 분기를 고정한다.
#[cfg(not(target_arch = "wasm32"))]
pub fn svg2pdf_invalid_image_error() -> svg2pdf::ConversionError {
    svg2pdf::ConversionError::InvalidImage
}

/// svg2pdf `to_chunk` 래퍼. 시험이 성공 경로를 재사용할 때 쓴다.
#[cfg(not(target_arch = "wasm32"))]
pub fn svg2pdf_to_chunk(
    tree: &usvg::Tree,
    embed_text: bool,
) -> Result<(pdf_writer::Chunk, pdf_writer::Ref), svg2pdf::ConversionError> {
    let mut conversion = svg2pdf::ConversionOptions::default();
    conversion.embed_text = embed_text;
    svg2pdf::to_chunk(tree, conversion)
}

#[cfg(not(target_arch = "wasm32"))]
fn convert_page_chunk<F>(
    tree: &usvg::Tree,
    embed_text: bool,
    page_index: usize,
    to_chunk: &mut F,
) -> Result<Option<(pdf_writer::Chunk, pdf_writer::Ref)>, String>
where
    F: FnMut(
        &usvg::Tree,
        bool,
    ) -> Result<(pdf_writer::Chunk, pdf_writer::Ref), svg2pdf::ConversionError>,
{
    match to_chunk(tree, embed_text) {
        Ok(ok) => Ok(Some(ok)),
        Err(err) => match classify_svg2pdf_page_error(&err, embed_text, false) {
            Svg2pdfPageIsolation::Fatal => Err(format!("SVG→chunk 변환 실패: {:?}", err)),
            Svg2pdfPageIsolation::RetryWithoutEmbedText => {
                eprintln!(
                    "WARN: 페이지 {} svg2pdf SubsetError({err:?}) — embed_text=false 로 재시도합니다.",
                    page_index + 1
                );
                match to_chunk(tree, false) {
                    Ok(ok) => Ok(Some(ok)),
                    Err(err2) => match classify_svg2pdf_page_error(&err2, false, true) {
                        Svg2pdfPageIsolation::SkipPage => {
                            eprintln!(
                                "WARN: 페이지 {} svg2pdf SubsetError({err2:?}) — 이 페이지만 건너뛰고 PDF 를 계속합니다.",
                                page_index + 1
                            );
                            Ok(None)
                        }
                        Svg2pdfPageIsolation::Fatal
                        | Svg2pdfPageIsolation::RetryWithoutEmbedText => {
                            Err(format!("SVG→chunk 변환 실패: {:?}", err2))
                        }
                    },
                }
            }
            Svg2pdfPageIsolation::SkipPage => {
                eprintln!(
                    "WARN: 페이지 {} svg2pdf SubsetError({err:?}) — 이 페이지만 건너뛰고 PDF 를 계속합니다.",
                    page_index + 1
                );
                Ok(None)
            }
        },
    }
}

/// 여러 SVG 페이지를 단일 다중 페이지 PDF로 생성
#[cfg(not(target_arch = "wasm32"))]
pub fn svgs_to_pdf(svg_pages: &[String]) -> Result<Vec<u8>, String> {
    svgs_to_pdf_with_options(svg_pages, &PdfExportOptions::default())
}

/// 여러 SVG 페이지를 옵션 기반 단일 다중 페이지 PDF로 생성
#[cfg(not(target_arch = "wasm32"))]
pub fn svgs_to_pdf_with_options(
    svg_pages: &[String],
    export_options: &PdfExportOptions,
) -> Result<Vec<u8>, String> {
    svgs_to_pdf_with_to_chunk(svg_pages, export_options, svg2pdf_to_chunk)
}

/// [#6612] 페이지 SVG 안의 `data:image/svg+xml` 그림을 이미지째 읽는 usvg 리졸버.
///
/// rhwp 는 WMF·EMF·AI 그림을 SVG 로 바꿔 `<image href="data:image/svg+xml;base64,…">` 로
/// 심는다. usvg 의 기본 데이터 리졸버는 이런 하위 SVG 를 `load_sub_svg` 로 읽는데, 그 함수는
/// SVG 규격("`<image>` 가 참조한 SVG 는 자기 안에 `<image>` 를 둘 수 없다")대로 하위 SVG 의
/// `<image>` 를 전부 버린다. 비트맵을 품은 WMF(`<svg viewBox><image href="data:image/png"/></svg>`)
/// 는 그래서 PDF 에서 빈칸이 됐다(hwp3-sample14 그림 13장 전부). 페이지 SVG 와 하위 SVG 를
/// 모두 rhwp 가 만들므로 하위 SVG 를 같은 옵션으로 파싱해 이미지를 유지한다. 다른 mime 은
/// usvg 기본 리졸버가 처리한다.
#[cfg(not(target_arch = "wasm32"))]
fn pdf_image_href_resolver() -> usvg::ImageHrefResolver<'static> {
    let default_data = usvg::ImageHrefResolver::default_data_resolver();
    usvg::ImageHrefResolver {
        resolve_data: Box::new(move |mime, data, opts| match mime {
            "image/svg+xml" => match usvg::Tree::from_data(&data, opts) {
                Ok(tree) => Some(usvg::ImageKind::SVG(tree)),
                Err(e) => {
                    eprintln!("경고: PDF 변환 중 하위 SVG 그림을 파싱하지 못해 건너뜁니다: {e}");
                    None
                }
            },
            _ => default_data(mime, data, opts),
        }),
        resolve_string: usvg::ImageHrefResolver::default_string_resolver(),
    }
}

/// 페이지별 `to_chunk` 를 주입할 수 있는 PDF 변환.
///
/// #3773: `SubsetError` 는 경고로 강등하고 나머지 페이지를 계속한다.
#[cfg(not(target_arch = "wasm32"))]
pub fn svgs_to_pdf_with_to_chunk<F>(
    svg_pages: &[String],
    export_options: &PdfExportOptions,
    to_chunk: F,
) -> Result<Vec<u8>, String>
where
    F: FnMut(
        &usvg::Tree,
        bool,
    ) -> Result<(pdf_writer::Chunk, pdf_writer::Ref), svg2pdf::ConversionError>,
{
    svgs_to_pdf_with_links_and_to_chunk(
        svg_pages,
        &vec![Vec::new(); svg_pages.len()],
        export_options,
        to_chunk,
    )
}

/// 페이지와 같은 순서의 링크 사각형을 PDF annotation으로 저장한다.
#[cfg(not(target_arch = "wasm32"))]
pub fn svgs_to_pdf_with_links(
    svg_pages: &[String],
    links: &[Vec<super::hyperlinks::PdfLink>],
    options: &PdfExportOptions,
) -> Result<Vec<u8>, String> {
    svgs_to_pdf_with_links_and_to_chunk(svg_pages, links, options, svg2pdf_to_chunk)
}

/// 페이지 변환 실패 시 링크 귀속도 검증하는 주입점.
#[cfg(not(target_arch = "wasm32"))]
#[doc(hidden)]
pub fn svgs_to_pdf_with_links_and_to_chunk<F>(
    svg_pages: &[String],
    links: &[Vec<super::hyperlinks::PdfLink>],
    export_options: &PdfExportOptions,
    to_chunk: F,
) -> Result<Vec<u8>, String>
where
    F: FnMut(
        &usvg::Tree,
        bool,
    ) -> Result<(pdf_writer::Chunk, pdf_writer::Ref), svg2pdf::ConversionError>,
{
    svgs_to_pdf_annotations_impl(
        svg_pages,
        links,
        export_options,
        to_chunk,
        &vec![Vec::new(); svg_pages.len()],
    )
}

#[cfg(not(target_arch = "wasm32"))]
pub fn svgs_to_pdf_with_annotations(
    svg_pages: &[String],
    links: &[Vec<super::hyperlinks::PdfLink>],
    destinations: &[Vec<super::hyperlinks::PdfNamedDestination>],
    options: &PdfExportOptions,
) -> Result<Vec<u8>, String> {
    svgs_to_pdf_annotations_impl(svg_pages, links, options, svg2pdf_to_chunk, destinations)
}

#[cfg(not(target_arch = "wasm32"))]
fn svgs_to_pdf_annotations_impl<F>(
    svg_pages: &[String],
    links: &[Vec<super::hyperlinks::PdfLink>],
    export_options: &PdfExportOptions,
    mut to_chunk: F,
    destinations: &[Vec<super::hyperlinks::PdfNamedDestination>],
) -> Result<Vec<u8>, String>
where
    F: FnMut(
        &usvg::Tree,
        bool,
    ) -> Result<(pdf_writer::Chunk, pdf_writer::Ref), svg2pdf::ConversionError>,
{
    if links.len() != svg_pages.len() {
        return Err("PDF 페이지와 링크 목록의 길이가 다릅니다".into());
    }
    if svg_pages.is_empty() {
        return Err("페이지가 없습니다".to_string());
    }
    use pdf_writer::{Finish, Pdf, Ref};
    use std::collections::HashMap;

    let fontdb = create_fontdb(export_options);
    let mut options = usvg::Options::default();
    options.fontdb = std::sync::Arc::new(fontdb);
    options.font_resolver.select_fallback = pdf_font_fallback_selector_with_limits(
        PDF_FONT_FALLBACK_INDEX_MAX_CHARS,
        PDF_FONT_FALLBACK_INDEX_MAX_FACE_SLOTS,
    );
    options.image_href_resolver = pdf_image_href_resolver();

    let mut alloc = Ref::new(1);
    let catalog_ref = alloc.bump();
    let page_tree_ref = alloc.bump();

    // 각 페이지의 SVG를 파싱하여 chunk + page 정보 수집
    struct PageData {
        chunk: pdf_writer::Chunk,
        svg_ref: Ref,
        width: f32,
        height: f32,
        source_index: usize,
    }

    let mut page_datas: Vec<PageData> = Vec::new();

    for (page_index, svg) in svg_pages.iter().enumerate() {
        let svg_with_fallback = apply_pdf_font_options(svg, export_options);
        let (svg_with_bold, bold_report) =
            prepare_svg_with_synthetic_bold(&svg_with_fallback, &options)?;
        if bold_report.unsupported_texts > 0 {
            eprintln!("경고: PDF {}페이지의 굵게 text {}개는 혼합 글꼴/복잡한 paint로 합성하지 못했습니다.", page_index + 1, bold_report.unsupported_texts);
        }
        let (tree, italic_report) = parse_svg_with_synthetic_italic(&svg_with_bold, &options)
            .map_err(|e| format!("SVG 파싱 실패: {}", e))?;
        if italic_report.unsupported_texts > 0 {
            eprintln!(
                "경고: PDF {}페이지의 기울임 text {}개는 혼합 글꼴/복잡한 배치로 합성하지 못했습니다.",
                page_index + 1,
                italic_report.unsupported_texts,
            );
        }

        // [Task #2264] 텍스트 임베드(폰트 서브셋)가 PDF 변환 메모리의 지배항이다.
        // `embed_text=false` 면 글리프를 path 로 변환해 서브셋 경로를 통째로 건너뛴다.
        // [#3773] SubsetError 는 페이지 단위로 격리한다.
        let Some((chunk, svg_ref)) =
            convert_page_chunk(&tree, export_options.embed_text, page_index, &mut to_chunk)?
        else {
            continue;
        };

        let dpi_ratio = 72.0 / 96.0; // 96 DPI → 72 pt
        let w = tree.size().width() * dpi_ratio;
        let h = tree.size().height() * dpi_ratio;

        page_datas.push(PageData {
            chunk,
            svg_ref,
            width: w,
            height: h,
            source_index: page_index,
        });
    }

    if page_datas.is_empty() {
        return Err("모든 페이지의 SVG→PDF 변환이 SubsetError 로 건너뛰어졌습니다".to_string());
    }

    // 각 chunk를 재번호화하고 페이지 참조 수집
    let mut page_refs: Vec<Ref> = Vec::new();
    let mut renumbered_chunks: Vec<pdf_writer::Chunk> = Vec::new();
    let mut svg_refs_remapped: Vec<Ref> = Vec::new();

    for pd in &page_datas {
        let page_ref = alloc.bump();
        let content_ref = alloc.bump();
        page_refs.push(page_ref);

        // chunk 재번호화
        let mut map = HashMap::new();
        let renumbered = pd
            .chunk
            .renumber(|old| *map.entry(old).or_insert_with(|| alloc.bump()));

        let remapped_svg_ref = map.get(&pd.svg_ref).copied().unwrap_or(pd.svg_ref);
        svg_refs_remapped.push(remapped_svg_ref);
        renumbered_chunks.push(renumbered);
    }

    // PDF 생성
    let mut pdf = Pdf::new();
    let destinations_ref = alloc.bump();
    pdf.catalog(catalog_ref)
        .pages(page_tree_ref)
        .destinations(destinations_ref);
    {
        let mut named = pdf.destinations(destinations_ref);
        let mut names = std::collections::HashSet::new();
        for (index, page) in page_datas.iter().enumerate() {
            for destination in destinations.get(page.source_index).into_iter().flatten() {
                if destination.x.is_finite()
                    && destination.y.is_finite()
                    && names.insert(destination.name.as_str())
                {
                    named
                        .insert(pdf_writer::Name(
                            super::hyperlinks::pdf_destination_key(&destination.name).as_bytes(),
                        ))
                        .page(page_refs[index])
                        .xyz(
                            (destination.x * 0.75) as f32,
                            page.height - (destination.y * 0.75) as f32,
                            None,
                        );
                }
            }
        }
        named.finish();
    }
    pdf.pages(page_tree_ref)
        .count(page_refs.len() as i32)
        .kids(page_refs.iter().copied());

    // 각 페이지 생성
    let svg_name = pdf_writer::Name(b"S1");

    for (i, pd) in page_datas.iter().enumerate() {
        let page_ref = page_refs[i];
        let content_ref = alloc.bump();
        let svg_ref = svg_refs_remapped[i];

        let page_links = super::hyperlinks::page_links(
            &links[pd.source_index],
            f64::from(pd.width) / 0.75,
            f64::from(pd.height) / 0.75,
        );
        let annotation_refs: Vec<_> = page_links.iter().map(|_| alloc.bump()).collect();
        let mut page = pdf.page(page_ref);
        page.media_box(pdf_writer::Rect::new(0.0, 0.0, pd.width, pd.height));
        page.parent(page_tree_ref);
        page.contents(content_ref);
        if !annotation_refs.is_empty() {
            page.annotations(annotation_refs.iter().copied());
        }

        let mut resources = page.resources();
        resources.x_objects().pair(svg_name, svg_ref);
        resources.finish();
        page.finish();
        for (link, annotation_ref) in page_links.iter().zip(annotation_refs) {
            let r = link.rect;
            let mut annotation = pdf.annotation(annotation_ref);
            annotation
                .subtype(pdf_writer::types::AnnotationType::Link)
                .rect(pdf_writer::Rect::new(
                    (r.x * 0.75) as f32,
                    pd.height - ((r.y + r.height) * 0.75) as f32,
                    ((r.x + r.width) * 0.75) as f32,
                    pd.height - (r.y * 0.75) as f32,
                ))
                .page(page_ref)
                .border(0.0, 0.0, 0.0, None);
            use crate::model::hyperlink::{classify_destination, LinkDestinationKind};
            let mut action = annotation.action();
            match classify_destination(&link.uri) {
                Some(LinkDestinationKind::DocumentAnchor) => {
                    action
                        .action_type(pdf_writer::types::ActionType::GoTo)
                        .destination_named(pdf_writer::Name(
                            super::hyperlinks::pdf_destination_key(&link.uri[1..]).as_bytes(),
                        ));
                }
                Some(LinkDestinationKind::RelativeFile | LinkDestinationKind::LocalFile)
                    if !link.uri.to_ascii_lowercase().starts_with("file:") =>
                {
                    action.action_type(pdf_writer::types::ActionType::Launch);
                    action
                        .file_spec()
                        .path(pdf_writer::Str(link.uri.as_bytes()))
                        .unic_file(pdf_writer::TextStr(&link.uri));
                }
                Some(_) => {
                    let uri = super::hyperlinks::export_uri(&link.uri)
                        .ok_or("invalid PDF link destination")?;
                    action
                        .action_type(pdf_writer::types::ActionType::Uri)
                        .uri(pdf_writer::Str(uri.as_bytes()));
                }
                None => return Err("invalid PDF link destination".into()),
            }
            action.finish();
            annotation.finish();
        }

        // 컨텐츠 스트림: SVG XObject를 페이지 크기에 맞게 배치
        let mut content = pdf_writer::Content::new();
        content.transform([pd.width, 0.0, 0.0, pd.height, 0.0, 0.0]);
        content.x_object(svg_name);

        pdf.stream(content_ref, &content.finish());
    }

    // 모든 chunk를 PDF에 추가
    for chunk in &renumbered_chunks {
        pdf.extend(chunk);
    }

    // 문서 정보
    let info_ref = alloc.bump();
    pdf.document_info(info_ref)
        .producer(pdf_writer::TextStr("rhwp"));

    // [#3824] 텍스트 표면만 표준 코드포인트로 맞춘다 — 렌더 결정은 불변.
    let mut bytes = pdf.finish();
    remap_pua_in_tounicode(&mut bytes);
    Ok(bytes)
}

/// Record PageLayerTree pages directly into a native Skia PDF document.
#[cfg(all(not(target_arch = "wasm32"), feature = "native-skia"))]
pub fn layer_trees_to_pdf(layer_trees: &[crate::paint::PageLayerTree]) -> Result<Vec<u8>, String> {
    layer_trees_to_pdf_with_options(layer_trees, &DirectPdfExportOptions::default())
}

/// Record PageLayerTree pages directly into a native Skia PDF document.
///
/// PageLayerTree coordinates are CSS pixels at 96 DPI. PDF page coordinates
/// are points at 72 DPI, so the page and canvas are scaled by 72/96. Skia keeps
/// text, paths, and supported effects as vector commands and uses `raster_dpi`
/// for effects without a native PDF representation.
#[cfg(all(not(target_arch = "wasm32"), feature = "native-skia"))]
pub fn layer_trees_to_pdf_with_options(
    layer_trees: &[crate::paint::PageLayerTree],
    options: &DirectPdfExportOptions,
) -> Result<Vec<u8>, String> {
    layer_trees_to_pdf_with_links(layer_trees, &vec![Vec::new(); layer_trees.len()], options)
}

/// Skia PDF에도 같은 CSS px 링크 영역을 적용한다.
#[cfg(all(not(target_arch = "wasm32"), feature = "native-skia"))]
pub fn layer_trees_to_pdf_with_links(
    layer_trees: &[crate::paint::PageLayerTree],
    links: &[Vec<super::hyperlinks::PdfLink>],
    options: &DirectPdfExportOptions,
) -> Result<Vec<u8>, String> {
    layer_trees_to_pdf_with_annotations(
        layer_trees,
        links,
        &vec![Vec::new(); layer_trees.len()],
        options,
    )
}

#[cfg(all(not(target_arch = "wasm32"), feature = "native-skia"))]
pub fn layer_trees_to_pdf_with_annotations(
    layer_trees: &[crate::paint::PageLayerTree],
    links: &[Vec<super::hyperlinks::PdfLink>],
    destinations: &[Vec<super::hyperlinks::PdfNamedDestination>],
    options: &DirectPdfExportOptions,
) -> Result<Vec<u8>, String> {
    if links.len() != layer_trees.len() {
        return Err("PDF 페이지와 링크 목록의 길이가 다릅니다".into());
    }
    use direct_pdf_validation::CSS_PX_TO_PDF_POINT;

    if layer_trees.is_empty() {
        return Err("direct PDF export requires at least one page".to_string());
    }
    if !options.raster_dpi.is_finite() || options.raster_dpi <= 0.0 {
        return Err(format!(
            "invalid direct PDF raster dpi: {}",
            options.raster_dpi
        ));
    }

    let page_sizes = layer_trees
        .iter()
        .enumerate()
        .map(|(page_index, tree)| {
            validate_direct_pdf_tree(tree, page_index)?;
            Ok((
                direct_pdf_validation::page_dimension(tree.page_width, true)
                    .map_err(|error| error.message)?,
                direct_pdf_validation::page_dimension(tree.page_height, false)
                    .map_err(|error| error.message)?,
            ))
        })
        .collect::<Result<Vec<_>, String>>()?;

    let metadata = skia_safe::pdf::Metadata {
        title: options.title.clone().unwrap_or_default(),
        author: options.author.clone().unwrap_or_default(),
        subject: options.subject.clone().unwrap_or_default(),
        keywords: options.keywords.clone().unwrap_or_default(),
        creator: "rhwp".to_string(),
        producer: "rhwp PageLayerTree direct PDF (Skia)".to_string(),
        raster_dpi: Some(options.raster_dpi),
        ..Default::default()
    };
    let renderer = crate::renderer::skia::SkiaLayerRenderer::new()
        .with_font_paths(options.font_paths.as_slice());
    let mut output = Vec::new();

    {
        let mut document = skia_safe::pdf::new_document(&mut output, Some(&metadata));
        for (page_index, ((tree, &(width, height)), links)) in layer_trees
            .iter()
            .zip(page_sizes.iter())
            .zip(links)
            .enumerate()
        {
            let mut page = document.begin_page((width, height), None);
            let canvas = page.canvas();
            canvas.clear(skia_safe::Color::WHITE);
            canvas.scale((CSS_PX_TO_PDF_POINT as f32, CSS_PX_TO_PDF_POINT as f32));
            renderer
                .render_page_to_canvas_strict(canvas, tree, options.raster_dpi / 96.0)
                .map_err(|error| format!("direct PDF page replay failed: {error}"))?;
            for destination in destinations.get(page_index).into_iter().flatten() {
                if destination.x.is_finite() && destination.y.is_finite() {
                    let mut name =
                        super::hyperlinks::pdf_destination_key(&destination.name).into_bytes();
                    name.push(0);
                    canvas.annotate_named_destination(
                        (destination.x as f32, destination.y as f32),
                        &skia_safe::Data::new_copy(&name),
                    );
                }
            }
            for link in super::hyperlinks::page_links(links, tree.page_width, tree.page_height) {
                let r = link.rect;
                let mut uri = super::hyperlinks::export_uri(&link.uri)
                    .ok_or("invalid PDF link destination")?
                    .into_bytes();
                uri.push(0); // Skia URL annotation payload는 NUL 종료 문자열이다.
                let rect = skia_safe::Rect::from_xywh(
                    r.x as f32,
                    r.y as f32,
                    r.width as f32,
                    r.height as f32,
                );
                if link.uri.starts_with('#') {
                    let mut name =
                        super::hyperlinks::pdf_destination_key(&link.uri[1..]).into_bytes();
                    name.push(0);
                    canvas.annotate_link_to_destination(rect, &skia_safe::Data::new_copy(&name));
                } else {
                    canvas.annotate_rect_with_url(rect, &skia_safe::Data::new_copy(&uri));
                }
            }
            document = page.end_page();
        }
        document.close();
    }

    if !output.starts_with(b"%PDF-") || !output.windows(5).any(|window| window == b"%%EOF") {
        return Err("Skia direct PDF writer returned an incomplete document".to_string());
    }
    Ok(output)
}

#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
    use super::*;

    /// [#3824] ToUnicode 의 한컴 PUA 를 표준 코드포인트로 바꾸되 **길이를 보존**한다.
    ///
    /// 길이가 보존돼야 `/Length` 와 xref 오프셋을 건드리지 않는다 — 이 수정이
    /// 바이트 수준에서 안전한 근거가 그것뿐이다.
    #[test]
    fn tounicode_pua_is_remapped_without_changing_length() {
        // U+F02B1(사각 안 1)은 평면 15 라 UTF-16BE 서로게이트 쌍 DB80 DEB1 이다.
        let src = b"beginbfchar
<0001> <DB80DEB1>
<0002> <DB80DEB2>
endbfchar";
        let mut buf = src.to_vec();
        let before = buf.len();
        remap_pua_in_tounicode(&mut buf);

        assert_eq!(buf.len(), before, "길이가 바뀌면 /Length 와 xref 가 깨진다");
        let out = String::from_utf8(buf).expect("utf-8");
        assert!(
            out.contains("<2460") && out.contains("<2461"),
            "표준 원문자로 안 바뀌었다: {out}"
        );
        assert!(!out.contains("DB80"), "PUA 서로게이트가 남아 있다: {out}");
    }

    /// 뜻을 모르는 코드포인트는 손대지 않는다 — 매핑을 지어내지 않는다는 계약.
    #[test]
    fn tounicode_leaves_unmapped_codepoints_alone() {
        let src = b"beginbfchar
<0001> <AC00>
<0002> <0041>
endbfchar";
        let mut buf = src.to_vec();
        remap_pua_in_tounicode(&mut buf);
        assert_eq!(buf, src.to_vec(), "매핑 없는 문자를 건드렸다");
    }

    /// `beginbfchar` 블록 **밖**은 건드리지 않는다 — 콘텐츠 스트림 오손 방지.
    #[test]
    fn tounicode_does_not_touch_bytes_outside_the_block() {
        let src = b"<DB80DEB1> beginbfchar
<0001> <DB80DEB1>
endbfchar <DB80DEB1>";
        let mut buf = src.to_vec();
        remap_pua_in_tounicode(&mut buf);
        let out = String::from_utf8(buf).expect("utf-8");
        assert_eq!(
            out.matches("DB80DEB1").count(),
            2,
            "블록 밖 바이트까지 고쳤다: {out}"
        );
        assert!(out.contains("<2460"), "블록 안은 고쳐야 한다: {out}");
    }

    #[test]
    fn pdf_backend_aliases_are_explicit() {
        assert_eq!(PdfBackend::default(), PdfBackend::CompatibilitySvg);
        assert_eq!(PdfBackend::parse("svg"), Some(PdfBackend::CompatibilitySvg));
        assert_eq!(
            PdfBackend::parse("compat"),
            Some(PdfBackend::CompatibilitySvg)
        );
        assert_eq!(PdfBackend::parse("direct"), Some(PdfBackend::DirectLayer));
        assert_eq!(PdfBackend::parse("skia"), Some(PdfBackend::DirectLayer));
        assert_eq!(PdfBackend::parse("unknown"), None);
        assert_eq!(PdfBackend::CompatibilitySvg.as_str(), "svg");
        assert_eq!(PdfBackend::DirectLayer.as_str(), "direct");
    }

    #[test]
    fn default_pdf_font_options_are_os_specific_and_non_empty() {
        let options = PdfExportOptions::default();
        assert!(!options.fallback_serif.is_empty());
        assert!(!options.fallback_sans.is_empty());
        assert!(!options.fallback_mono.is_empty());
        assert!(options.equation_font.is_none());
    }

    #[test]
    fn pdf_font_options_replace_generic_fallbacks_and_equation_font() {
        let options = PdfExportOptions {
            fallback_serif: "Noto Serif CJK KR".to_string(),
            fallback_sans: "Noto Sans CJK KR".to_string(),
            fallback_mono: "Noto Sans Mono CJK KR".to_string(),
            equation_font: Some("STIX Two Math".to_string()),
            font_paths: Vec::new(),
            embed_text: true,
        };
        let svg = format!(
            r#"<svg><text font-family="휴먼명조">가</text><text font-family="HCI Poppy">A</text><text {}>x</text></svg>"#,
            crate::renderer::equation::svg_render::DEFAULT_EQUATION_FONT_FAMILY_ATTR
        );

        let out = apply_pdf_font_options(&svg, &options);

        assert!(out.contains(r#"font-family="휴먼명조, 'Noto Serif CJK KR', serif""#));
        assert!(out.contains(r#"font-family="HCI Poppy, 'Noto Sans CJK KR', sans-serif""#));
        assert!(out
            .contains(r#"font-family="&apos;STIX Two Math&apos;, &apos;Latin Modern Math&apos;"#));
    }

    #[test]
    fn equation_font_accepts_full_family_chain() {
        let chain = equation_font_chain("'Custom Math', 'Fallback Math', serif");
        assert_eq!(chain, "'Custom Math', 'Fallback Math', serif");
    }

    #[cfg(feature = "native-skia")]
    fn direct_pdf_test_tree(
        width: f64,
        height: f64,
        fill_color: crate::model::ColorRef,
    ) -> crate::paint::PageLayerTree {
        use crate::paint::{LayerNode, PaintOp, RenderProfile};
        use crate::renderer::render_tree::{BoundingBox, RectangleNode};
        use crate::renderer::ShapeStyle;

        let page_bounds = BoundingBox::new(0.0, 0.0, width, height);
        let rectangle = RectangleNode::new(
            0.0,
            ShapeStyle {
                fill_color: Some(fill_color),
                ..Default::default()
            },
            None,
        );
        crate::paint::PageLayerTree::with_profile(
            width,
            height,
            LayerNode::leaf(
                page_bounds,
                None,
                vec![PaintOp::rectangle(
                    BoundingBox::new(8.0, 8.0, width - 16.0, height - 16.0),
                    rectangle,
                )],
            ),
            RenderProfile::Print,
        )
    }

    #[cfg(feature = "native-skia")]
    #[test]
    fn skia_direct_pdf_records_multiple_layer_pages() {
        let pages = [
            direct_pdf_test_tree(96.0, 144.0, 0x000000ff),
            direct_pdf_test_tree(192.0, 96.0, 0x0000ff00),
        ];
        let options = DirectPdfExportOptions {
            title: Some("P37 direct PDF test".to_string()),
            ..Default::default()
        };

        let pdf = layer_trees_to_pdf_with_options(&pages, &options).unwrap();

        assert!(pdf.starts_with(b"%PDF-"));
        assert!(pdf.windows(5).any(|window| window == b"%%EOF"));
        assert!(pdf
            .windows(b"P37 direct PDF test".len())
            .any(|window| window == b"P37 direct PDF test"));
        assert!(pdf
            .windows(b"/Count 2".len())
            .any(|window| window == b"/Count 2"));
        assert!(pdf
            .windows(b"/MediaBox [0 0 72 108]".len())
            .any(|window| window == b"/MediaBox [0 0 72 108]"));
        assert!(pdf
            .windows(b"/MediaBox [0 0 144 72]".len())
            .any(|window| window == b"/MediaBox [0 0 144 72]"));
        assert!(!pdf
            .windows(b"/Subtype /Image".len())
            .any(|window| window == b"/Subtype /Image"));
    }

    #[cfg(feature = "native-skia")]
    #[test]
    fn skia_direct_pdf_rejects_invalid_export_inputs() {
        assert_eq!(
            layer_trees_to_pdf(&[]).unwrap_err(),
            "direct PDF export requires at least one page"
        );

        let valid = direct_pdf_test_tree(96.0, 96.0, 0x000000ff);
        for raster_dpi in [0.0, -1.0, f32::NAN, f32::INFINITY] {
            let options = DirectPdfExportOptions {
                raster_dpi,
                ..Default::default()
            };
            assert!(
                layer_trees_to_pdf_with_options(std::slice::from_ref(&valid), &options)
                    .unwrap_err()
                    .contains("invalid direct PDF raster dpi")
            );
        }

        for invalid in [
            direct_pdf_test_tree(0.0, 96.0, 0x000000ff),
            direct_pdf_test_tree(f64::NAN, 96.0, 0x000000ff),
            direct_pdf_test_tree(20_000.0, 96.0, 0x000000ff),
        ] {
            assert!(layer_trees_to_pdf(std::slice::from_ref(&invalid)).is_err());
        }

        let mut oversized_layer = direct_pdf_test_tree(96.0, 96.0, 0x000000ff);
        oversized_layer.root.bounds.x = f32::MAX as f64 * 2.0;
        assert!(layer_trees_to_pdf(&[oversized_layer])
            .unwrap_err()
            .contains("invalid layer bounds"));
    }

    #[cfg(feature = "native-skia")]
    #[test]
    fn skia_direct_pdf_rejects_corrupt_and_unvalidated_images() {
        use crate::paint::{LayerNode, PaintOp, RenderProfile};
        use crate::renderer::render_tree::{BoundingBox, ImageNode};
        use image::{ImageFormat, Rgb, RgbImage};
        use std::io::Cursor;

        let image = RgbImage::from_fn(64, 64, |x, y| {
            Rgb([
                (x.wrapping_mul(17) ^ y.wrapping_mul(31)) as u8,
                (x.wrapping_mul(47).wrapping_add(y.wrapping_mul(13))) as u8,
                (x.wrapping_mul(7) ^ y.wrapping_mul(53)) as u8,
            ])
        });
        let mut cursor = Cursor::new(Vec::new());
        image
            .write_to(&mut cursor, ImageFormat::Png)
            .expect("encode test PNG");
        let mut corrupt_png = cursor.into_inner();
        let idat_type_offset = corrupt_png
            .windows(4)
            .position(|window| window == b"IDAT")
            .expect("encoded PNG must contain IDAT");
        corrupt_png[idat_type_offset + 4] ^= 0xff;
        assert!(
            skia_safe::Image::from_encoded(skia_safe::Data::new_copy(&corrupt_png)).is_some(),
            "fixture must pass Skia's encoded-header check"
        );
        assert!(
            image::load_from_memory_with_format(&corrupt_png, ImageFormat::Png).is_err(),
            "fixture must fail strict PNG decoding"
        );

        let page_bounds = BoundingBox::new(0.0, 0.0, 96.0, 96.0);
        let tree = crate::paint::PageLayerTree::with_profile(
            96.0,
            96.0,
            LayerNode::leaf(
                page_bounds,
                None,
                vec![PaintOp::image(
                    BoundingBox::new(8.0, 8.0, 32.0, 32.0),
                    ImageNode::new(1, Some(corrupt_png)),
                    None,
                )],
            ),
            RenderProfile::Print,
        );

        let error = layer_trees_to_pdf(&[tree]).unwrap_err();
        assert!(
            error.contains("cannot decode image payload"),
            "unexpected error: {error}"
        );

        let malformed_gif = crate::paint::PageLayerTree::with_profile(
            96.0,
            96.0,
            LayerNode::leaf(
                page_bounds,
                None,
                vec![PaintOp::image(
                    BoundingBox::new(8.0, 8.0, 32.0, 32.0),
                    ImageNode::new(2, Some(b"GIF89a\x01\x00\x01\x00\x80\x00\x00".to_vec())),
                    None,
                )],
            ),
            RenderProfile::Print,
        );
        let error = layer_trees_to_pdf(&[malformed_gif]).unwrap_err();
        assert!(
            error.contains("cannot decode image payload"),
            "unexpected error: {error}"
        );

        let unsupported = crate::paint::PageLayerTree::with_profile(
            96.0,
            96.0,
            LayerNode::leaf(
                page_bounds,
                None,
                vec![PaintOp::image(
                    BoundingBox::new(8.0, 8.0, 32.0, 32.0),
                    ImageNode::new(3, Some(b"unrecognized image payload".to_vec())),
                    None,
                )],
            ),
            RenderProfile::Print,
        );
        let error = layer_trees_to_pdf(&[unsupported]).unwrap_err();
        assert!(
            error.contains("does not support image payload format application/octet-stream"),
            "unexpected error: {error}"
        );
    }

    #[cfg(feature = "native-skia")]
    #[test]
    fn skia_direct_pdf_rejects_known_lossy_shape_replay() {
        use crate::paint::{LayerNode, PaintOp, RenderProfile};
        use crate::renderer::render_tree::{BoundingBox, RectangleNode};
        use crate::renderer::{GradientFillInfo, ShapeStyle};

        // Type 2 now has bounded exact radial admission. The approximate
        // cone and SkSL square gradients remain unsupported by Direct PDF.
        for gradient_type in [3, 4] {
            let bbox = BoundingBox::new(0.0, 0.0, 96.0, 96.0);
            let gradient = GradientFillInfo {
                gradient_type,
                angle: 0,
                center_x: 50,
                center_y: 50,
                colors: vec![0x000000ff, 0x00ff0000],
                positions: vec![0.0, 1.0],
            };
            let tree = crate::paint::PageLayerTree::with_profile(
                96.0,
                96.0,
                LayerNode::leaf(
                    bbox,
                    None,
                    vec![PaintOp::rectangle(
                        bbox,
                        RectangleNode::new(0.0, ShapeStyle::default(), Some(Box::new(gradient))),
                    )],
                ),
                RenderProfile::Print,
            );

            let error = layer_trees_to_pdf(&[tree]).unwrap_err();
            assert!(error.contains("gradient fill"), "unexpected error: {error}");
            assert!(error.contains("use the svg backend"));
        }
    }

    #[cfg(feature = "native-skia")]
    #[test]
    fn skia_direct_pdf_raw_svg_fallback_is_strict_and_uses_requested_dpi() {
        use crate::paint::{LayerNode, PaintOp, RenderProfile};
        use crate::renderer::render_tree::{BoundingBox, RawSvgNode};

        let page_bounds = BoundingBox::new(0.0, 0.0, 96.0, 96.0);
        let svg_bounds = BoundingBox::new(8.0, 8.0, 32.0, 16.0);
        let tree_with_svg = |svg: &str| {
            crate::paint::PageLayerTree::with_profile(
                96.0,
                96.0,
                LayerNode::leaf(
                    page_bounds,
                    None,
                    vec![PaintOp::raw_svg(
                        svg_bounds,
                        RawSvgNode::new(svg.to_string()),
                    )],
                ),
                RenderProfile::Print,
            )
        };

        let invalid = layer_trees_to_pdf(&[tree_with_svg("<path")]).unwrap_err();
        assert!(invalid.contains("raw SVG raster fallback failed"));

        let options = DirectPdfExportOptions {
            raster_dpi: 192.0,
            ..Default::default()
        };
        let pdf = layer_trees_to_pdf_with_options(
            &[tree_with_svg(
                r##"<rect x="8" y="8" width="32" height="16" fill="#f00"/>"##,
            )],
            &options,
        )
        .unwrap();
        assert!(pdf.windows(9).any(|window| window == b"/Width 64"));
        assert!(pdf.windows(10).any(|window| window == b"/Height 32"));
    }
}