rhwp 0.9.1

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
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
//! SVG 렌더러 (2차 백엔드)
//!
//! 렌더 트리를 SVG 문자열로 변환한다.
//! 정적 출력(인쇄, PDF 변환 등)에 적합하다.

use super::composer::{
    char_overlap_display_text, char_overlap_size_ratio, decode_pua_overlap_number,
    expand_pua_render_text_in_style, pua_overlap_number_border, CharOverlapInfo,
};
pub(crate) use super::image_resolver::{
    bmp_bytes_to_png_bytes, detect_image_mime_type, pcx_bytes_to_png_bytes,
    real_picture_watermark_bytes_to_hancom_tone_png_bytes,
    real_picture_watermark_fill_bytes_to_hancom_tone_png_bytes, tiff_bytes_to_png_bytes,
    watermark_jpeg_bytes_to_hancom_baked_png_bytes,
};
use super::pua_oldhangul::map_pua_old_hangul;
use super::render_tree::{
    BoundingBox, FormObjectNode, ImageNode, PageBackgroundImage, PageRenderTree, PathNode,
    RenderNode, RenderNodeType, ShapeTransform, LEGACY_IMAGE_WATERMARK_OPACITY,
    REAL_PICTURE_WATERMARK_FILL_OPACITY, REAL_PICTURE_WATERMARK_PAGE_OPACITY,
};
use super::{
    boxed_pua_char_overlap_semantics, clamp_tab_leader_end_x, faux_bold_stroke_width,
    GradientFillInfo, LineStyle, PathCommand, PatternFillInfo, Renderer, ShapeStyle, StrokeDash,
    TextStyle,
};
use crate::paint::{PaintOp, TextDecorationKind};
use std::fmt::Write as _;

mod char_overlap;
#[cfg(not(target_arch = "wasm32"))]
mod italic_fonts;
mod pua_glyph;
mod stroke_pattern;

/// Hanyang-PUA 옛한글 코드포인트를 KS X 1026-1:2007 자모 시퀀스로 확장.
/// PUA 가 없으면 원본 문자열 그대로 반환 (allocation 없음).
fn expand_pua_old_hangul(text: &str) -> String {
    if !text.chars().any(|ch| map_pua_old_hangul(ch).is_some()) {
        return text.to_string();
    }
    let mut out = String::with_capacity(text.len() * 2);
    for ch in text.chars() {
        if let Some(jamos) = map_pua_old_hangul(ch) {
            out.extend(jamos.iter().copied());
        } else {
            out.push(ch);
        }
    }
    out
}
use super::layout::{is_halfwidth_cjk_quote, split_into_clusters};
use crate::model::style::{HatchStyle, ImageFillMode, UnderlineType};
use base64::Engine;

#[cfg(not(target_arch = "wasm32"))]
mod fallback_fonts;
#[cfg(not(target_arch = "wasm32"))]
mod font_file_lookup;
#[cfg(not(target_arch = "wasm32"))]
mod system_fonts;
#[cfg(not(target_arch = "wasm32"))]
mod webfont_subset;
#[cfg(all(test, not(target_arch = "wasm32")))]
use font_file_lookup::FontFileName;
#[cfg(not(target_arch = "wasm32"))]
use font_file_lookup::{
    find_font_file, find_font_file_for_chars, plan_svg_font_file_lookup,
    plan_svg_font_file_lookup_with_fallback, FontFileLookupPlan,
};

const TEXT_MARK_CLIP_RIGHT_PAD: f64 = 48.0;

/// Result of translating one canonical paint operation to SVG syntax.
pub(super) enum SvgPaintDisposition {
    Rendered,
    /// SVG intentionally selects the validated `TextRun` fallback for glyph-native variants.
    UnsupportedTextVariant,
}

/// SVG 폰트 임베딩 모드
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub enum FontEmbedMode {
    /// 폰트 임베딩 없음 (CSS font-family 체인만)
    #[default]
    None,
    /// @font-face + local() 참조만 (데이터 미포함)
    Style,
    /// 사용 글자만 서브셋 추출 + base64 임베딩
    Subset,
    /// 전체 폰트 base64 임베딩
    Full,
}

/// SVG 렌더러
pub struct SvgRenderer {
    /// SVG 출력 버퍼
    output: super::svg_buffer::SvgBuffer,
    /// 그라데이션 정의 버퍼 (<defs> 내부)
    defs: Vec<String>,
    /// 그라데이션 ID 카운터
    gradient_counter: u32,
    /// 클립/패턴 ID 카운터
    clip_counter: u32,
    /// <defs> 삽입 위치 (begin_page 후 기록)
    defs_insert_pos: usize,
    /// 페이지 폭
    width: f64,
    /// 페이지 높이
    height: f64,
    /// 문단부호(¶) 표시 여부
    pub show_paragraph_marks: bool,
    /// 조판부호 표시 여부 (개체 마커)
    pub show_control_codes: bool,
    /// 디버그 오버레이 표시 여부
    pub debug_overlay: bool,
    /// 편집 화면 전용 missing-picture placeholder 표시 여부.
    pub show_missing_picture_placeholder: bool,
    /// [#3375/#4379] `editor_only` 노드(빈 누름틀 안내문 등) 표시 판정의 단일 권위.
    ///
    /// 한컴은 편집 화면에서만 보여 주는 요소를 인쇄·PDF 에서는 내보내지 않는다. 이 판정은
    /// paint `LayerBuilder`(`paint/builder.rs`)의 `node.editor_only && !profile.shows_editor_visuals()`
    /// 와 **같은 술어**(`RenderProfile::shows_editor_visuals`)를 호출한다 — 예전에는 이 필드가
    /// 독립된 bool(`show_editor_only_nodes`)이라 두 경로가 각자 기본값을 들고 있었고, 한쪽만
    /// 고치면 조용히 갈라질 수 있었다(#4379).
    ///
    /// 기본값은 `RenderProfile::Screen`(`shows_editor_visuals() == true`) — 프로필 개념이
    /// 없던 legacy 경로(편집 화면 렌더)가 종전대로 트리를 그대로 그리던 동작과 동일하다.
    /// 프로필을 아는 layer 경로(`svg_layer.rs`)는 이 필드를 자신의 `RenderProfile` 로 그대로
    /// 대입한다.
    pub profile: crate::paint::RenderProfile,
    /// 디버그 오버레이용: 문단별 경계 수집 (pi → bbox)
    overlay_para_bounds: std::collections::HashMap<usize, OverlayBounds>,
    /// 디버그 오버레이용: 표 경계 수집
    overlay_table_bounds: Vec<OverlayTableInfo>,
    /// 디버그 오버레이용: 이미지 경계 수집
    overlay_image_bounds: Vec<OverlayImageInfo>,
    /// 디버그 오버레이용: vpos=0 리셋 위치 수집 (문단 첫 줄 제외)
    overlay_vpos_resets: Vec<OverlayVposReset>,
    /// 디버그 오버레이용: 표/머리말/꼬리말 내부 깊이 (셀 내·헤더 문단 제외)
    overlay_skip_depth: u32,
    /// 디버그 오버레이용: 현재 페이지의 메인 섹션 인덱스 (-1이면 미설정)
    overlay_page_section: i32,
    /// defs 내 중복 방지용 ID 집합 (화살표 마커, 이미지 효과 필터 등)
    defs_ids: std::collections::HashSet<String>,
    /// 폰트 임베딩 모드
    pub font_embed_mode: FontEmbedMode,
    /// 추가 폰트 탐색 경로
    pub font_paths: Vec<std::path::PathBuf>,
    pub(crate) source_font_coverage: super::pua_glyph::FontCoverage,
    #[cfg(not(target_arch = "wasm32"))]
    source_font_coverage_requests: std::collections::HashSet<(String, bool, bool)>,
    /// 사용된 폰트별 codepoint 수집 (font_family → codepoints)
    font_codepoints: std::collections::HashMap<String, std::collections::HashSet<char>>,
    /// 실제 Bold face가 필요한 폰트 family.
    ///
    /// 한컴 PDF는 `HCRBatang-Bold`처럼 regular와 별도 outline face를 사용한다.
    /// 일반 face 하나만 `@font-face`로 임베드하면 브라우저가 synthetic bold를
    /// 적용해 획 두께와 글리프 폭이 기준 PDF와 달라진다.
    font_bold_families: std::collections::HashSet<String>,
    font_italic_styles: std::collections::HashSet<(String, bool)>,
    /// [#4709] 배치에 쓴 내장 메트릭 face를 출력에 주석으로 남길지 (옵트인).
    ///
    /// 켜면 각 `<text>`에 `data-metric-font`, 루트 `<svg>`에 페이지에서 쓰인
    /// face 목록 `data-rhwp-metric-fonts`가 붙는다. 임베드 호스트가 폰트 설치
    /// 확인·대체 폰트 보정에 쓴다. 기본 꺼짐 — 골든/스냅샷 출력 불변.
    pub annotate_metric_font: bool,
    /// [#4709] 현재 페이지에서 배치에 쓰인 메트릭 face 수집 (루트 주석용).
    metric_faces: std::collections::BTreeSet<String>,
    /// [#6028] soft-wrap 줄의 마지막 텍스트 run 이 가진 줄-말미 공백 수.
    /// TextLine 진입 시 (해당 run 의 node id, 공백 수)로 세팅되고, 그 run 의
    /// draw_text 가 밑줄/취소선 길이에서 이 공백들을 제외한다 — 한글은 wrap 이
    /// 소비한 구분 공백을 줄에 남기지 않아 장식선이 마지막 글리프에서 끝난다
    /// (2307287 4쪽 실측). 문단 마지막 줄·강제 줄바꿈 줄의 밑줄 친 말미 공백
    /// (서명란, issue_157)은 저자 콘텐츠라 제외하지 않는다.
    soft_wrap_decoration_trim: Option<(u32, usize)>,
    forced_decoration_trim: Option<usize>,
    /// draw_text 한 회 한정 활성 트림 수 (위 필드에서 파생).
    active_decoration_trim: usize,
    /// Canonical sidecar replay reuses `draw_text_positioned` for decoration geometry while
    /// suppressing the mirrored base glyphs.
    suppress_text_glyphs: bool,
    /// [#6451] 이 run 의 **레이아웃 폭**(render tree bbox). 장식선(밑줄/취소선)은
    /// 작성기의 자체 글자 측정 대신 이 값을 쓴다.
    ///
    /// 두 측정은 미세하게 어긋난다 — 156514427 1쪽 밑줄에서 작성기는 run 끝을
    /// 372.520px 로 보는데 레이아웃은 다음 run 을 372.853px 에 놓아, 조각 사이에
    /// 0.333px(0.25pt) 실틈이 남았다. bbox 는 `101.9+271.0=372.9` 로 정확히 이어진다.
    active_decoration_width: Option<f64>,
    /// 직교 장치 선에만 raster 힌트를 전달한다. 그룹 변환을 벗어나면 이전 상태로 복원한다.
    axis_stroke_hint_allowed: bool,
    axis_stroke_hint_stack: Vec<bool>,
}

/// 디버그 오버레이용 문단 경계 정보
pub(super) struct OverlayBounds {
    pub(super) section_index: usize,
    pub(super) x: f64,
    pub(super) y: f64,
    pub(super) width: f64,
    pub(super) height: f64,
}

/// 디버그 오버레이용 vpos=0 리셋 마커
pub(super) struct OverlayVposReset {
    pub(super) section_index: usize,
    pub(super) para_index: usize,
    pub(super) line_index: u32,
    /// 줄 시작 y (px)
    pub(super) y: f64,
    /// 줄 시작 x (px)
    pub(super) x: f64,
    /// 줄 폭 (px)
    pub(super) width: f64,
}

/// 디버그 오버레이용 표 정보
pub(super) struct OverlayTableInfo {
    pub(super) section_index: usize,
    pub(super) para_index: usize,
    pub(super) control_index: usize,
    pub(super) x: f64,
    pub(super) y: f64,
    pub(super) width: f64,
    pub(super) height: f64,
    pub(super) row_count: u16,
    pub(super) col_count: u16,
}

/// 디버그 오버레이용 이미지 정보
pub(super) struct OverlayImageInfo {
    pub(super) section_index: usize,
    pub(super) para_index: usize,
    pub(super) control_index: usize,
    pub(super) x: f64,
    pub(super) y: f64,
    pub(super) width: f64,
    pub(super) height: f64,
}

pub(super) struct LayerDebugOverlayProjection {
    pub(super) paragraph_bounds: std::collections::HashMap<usize, OverlayBounds>,
    pub(super) table_bounds: Vec<OverlayTableInfo>,
    pub(super) image_bounds: Vec<OverlayImageInfo>,
    pub(super) vpos_resets: Vec<OverlayVposReset>,
    pub(super) page_section: i32,
}

impl SvgRenderer {
    pub fn new() -> Self {
        Self {
            output: Default::default(),
            defs: Vec::new(),
            gradient_counter: 0,
            clip_counter: 0,
            defs_insert_pos: 0,
            width: 0.0,
            height: 0.0,
            show_paragraph_marks: false,
            show_control_codes: false,
            debug_overlay: false,
            show_missing_picture_placeholder: false,
            profile: crate::paint::RenderProfile::Screen,
            overlay_para_bounds: std::collections::HashMap::new(),
            overlay_table_bounds: Vec::new(),
            overlay_image_bounds: Vec::new(),
            overlay_vpos_resets: Vec::new(),
            overlay_skip_depth: 0,
            overlay_page_section: -1,
            defs_ids: std::collections::HashSet::new(),
            font_embed_mode: FontEmbedMode::None,
            font_paths: Vec::new(),
            source_font_coverage: Default::default(),
            #[cfg(not(target_arch = "wasm32"))]
            source_font_coverage_requests: Default::default(),
            font_codepoints: std::collections::HashMap::new(),
            font_bold_families: std::collections::HashSet::new(),
            font_italic_styles: std::collections::HashSet::new(),
            annotate_metric_font: false,
            metric_faces: std::collections::BTreeSet::new(),
            soft_wrap_decoration_trim: None,
            forced_decoration_trim: None,
            active_decoration_trim: 0,
            suppress_text_glyphs: false,
            active_decoration_width: None,
            axis_stroke_hint_allowed: true,
            axis_stroke_hint_stack: Vec::new(),
        }
    }

    /// 생성된 SVG 문자열 반환
    pub fn output(&self) -> &str {
        &self.output
    }

    pub(crate) fn bound_output(
        &mut self,
        maximum: usize,
        reservation: std::sync::Arc<dyn crate::storage::Reservation>,
    ) {
        self.output.bounded(maximum, reservation);
    }

    pub(crate) fn check_output(&self) -> Result<(), crate::error::HwpError> {
        self.output.check()
    }

    pub(crate) fn insert_output_style(&mut self, style: &str) {
        if let Some(position) = self.output.find('>') {
            self.output.insert_str(position + 1, style);
        }
    }

    pub(crate) fn take_checked_output(&mut self) -> Result<String, crate::error::HwpError> {
        std::mem::take(&mut self.output).finish()
    }

    /// 수집된 폰트별 사용 글자 목록 반환
    pub fn font_codepoints(
        &self,
    ) -> &std::collections::HashMap<String, std::collections::HashSet<char>> {
        &self.font_codepoints
    }

    /// 문서 CharShape가 bold로 지정한 사용 폰트 family.
    pub fn font_bold_families(&self) -> &std::collections::HashSet<String> {
        &self.font_bold_families
    }

    /// 렌더 트리를 SVG로 렌더링
    pub fn render_tree(&mut self, tree: &PageRenderTree) {
        self.render_node(&tree.root);
    }

    /// Opens the SVG document consumed by direct `PageLayerTree` replay.
    pub(super) fn begin_layer_page(&mut self, width: f64, height: f64) {
        self.begin_page(width, height);
    }

    /// 공통 그룹의 좌표계만 직렬화한다. 자식의 논리 bbox는 다시 배치하지 않는다.
    pub(super) fn begin_layer_transform(&mut self, [a, b, c, d, e, f]: [f64; 6]) {
        self.axis_stroke_hint_stack
            .push(self.axis_stroke_hint_allowed);
        self.axis_stroke_hint_allowed &= (b == 0.0 && c == 0.0) || (a == 0.0 && d == 0.0);
        self.output.push_str(&format!(
            "<g transform=\"matrix({a} {b} {c} {d} {e} {f})\">\n"
        ));
    }

    pub(super) fn end_layer_transform(&mut self) {
        self.output.push_str("</g>\n");
        self.axis_stroke_hint_allowed = self.axis_stroke_hint_stack.pop().unwrap_or(true);
    }

    /// Closes the SVG document consumed by direct `PageLayerTree` replay.
    pub(super) fn end_layer_page(&mut self) {
        self.end_page();
    }

    /// Serializes one canonical paint operation without rebuilding semantic tree structure.
    ///
    /// The temporary `RenderNode` values below are leaf payload adapters for the mature SVG
    /// primitive writer. They never carry children, visibility, profile, clipping, or stacking;
    /// those decisions remain owned by `PageLayerTree` and `SvgLayerRenderer`.
    pub(super) fn render_layer_paint_op(
        &mut self,
        op: &PaintOp,
        source_node_id: Option<u32>,
    ) -> SvgPaintDisposition {
        if !op.glyph_paint_transform_is_valid() {
            return SvgPaintDisposition::UnsupportedTextVariant;
        }
        if let Some(t) = op.glyph_paint_transform() {
            self.output.push_str(&format!(
                "<g transform=\"matrix({} {} {} {} {} {})\">",
                t.a, t.b, t.c, t.d, t.e, t.f
            ));
            let disposition = self.render_layer_paint_op_untransformed(op, source_node_id);
            self.output.push_str("</g>");
            return disposition;
        }
        self.render_layer_paint_op_untransformed(op, source_node_id)
    }

    fn render_layer_paint_op_untransformed(
        &mut self,
        op: &PaintOp,
        source_node_id: Option<u32>,
    ) -> SvgPaintDisposition {
        let node_id = source_node_id.unwrap_or(0);
        match op {
            PaintOp::PageBackground { bbox, background } => self.render_layer_payload_node(
                node_id,
                RenderNodeType::PageBackground(background.as_ref().clone()),
                *bbox,
                false,
            ),
            PaintOp::TextRun { bbox, run, .. } => {
                // LayerBuilder publishes explicit ops for visuals that legacy TextRun mirrored.
                // Strip those mirrors so each canonical paint decision is serialized once.
                let mut base = run.as_ref().clone();
                base.char_overlap = None;
                base.style.tab_leaders.clear();
                base.style.underline = UnderlineType::None;
                base.style.strikethrough = false;
                base.style.emphasis_dot = 0;
                self.render_layer_payload_node(
                    node_id,
                    RenderNodeType::TextRun(base),
                    *bbox,
                    false,
                );
            }
            PaintOp::GlyphRun { .. } | PaintOp::GlyphOutline { .. } => {
                return SvgPaintDisposition::UnsupportedTextVariant;
            }
            PaintOp::CharOverlap { bbox, run, .. } => {
                let rotation = run.rotation;
                let mut overlap = run.as_ref().clone();
                overlap.rotation = 0.0;
                self.with_layer_text_rotation(rotation, *bbox, |renderer| {
                    renderer.render_layer_payload_node(
                        node_id,
                        RenderNodeType::TextRun(overlap),
                        *bbox,
                        false,
                    );
                });
            }
            PaintOp::TextControlMark { bbox, run, .. } => {
                let rotation = run.rotation;
                let mut mark = run.as_ref().clone();
                mark.rotation = 0.0;
                mark.char_overlap = None;
                mark.style.tab_leaders.clear();
                mark.style.underline = UnderlineType::None;
                mark.style.strikethrough = false;
                mark.style.emphasis_dot = 0;
                mark.style.shadow_type = 0;
                mark.style.shade_color = crate::model::color::NONE;
                self.with_layer_text_rotation(rotation, *bbox, |renderer| {
                    renderer.with_suppressed_text_glyphs(|renderer| {
                        renderer.render_layer_payload_node(
                            node_id,
                            RenderNodeType::TextRun(mark),
                            *bbox,
                            true,
                        );
                    });
                });
            }
            PaintOp::TabLeader { bbox, run, .. } => {
                let rotation = run.rotation;
                let mut leader = run.as_ref().clone();
                leader.rotation = 0.0;
                leader.char_overlap = None;
                leader.style.underline = UnderlineType::None;
                leader.style.strikethrough = false;
                leader.style.emphasis_dot = 0;
                leader.style.shadow_type = 0;
                leader.style.shade_color = crate::model::color::NONE;
                self.with_layer_text_rotation(rotation, *bbox, |renderer| {
                    renderer.with_suppressed_text_glyphs(|renderer| {
                        renderer.render_layer_payload_node(
                            node_id,
                            RenderNodeType::TextRun(leader),
                            *bbox,
                            false,
                        );
                    });
                });
            }
            PaintOp::TextDecoration {
                bbox,
                run,
                kind,
                trim_trailing_spaces,
                ..
            } => {
                let (bbox, run) = op.decoration_replay().expect("decoration replay");
                let rotation = run.rotation;
                let mut decoration = run.as_ref().clone();
                decoration.rotation = 0.0;
                decoration.char_overlap = None;
                decoration.style.tab_leaders.clear();
                decoration.style.shadow_type = 0;
                decoration.style.shade_color = crate::model::color::NONE;
                decoration.style.underline = if *kind == TextDecorationKind::Underline {
                    run.style.underline
                } else {
                    UnderlineType::None
                };
                decoration.style.strikethrough =
                    *kind == TextDecorationKind::Strikethrough && run.style.strikethrough;
                decoration.style.emphasis_dot = if *kind == TextDecorationKind::EmphasisDot {
                    run.style.emphasis_dot
                } else {
                    0
                };
                let previous_forced_trim = self.forced_decoration_trim;
                self.forced_decoration_trim = Some(*trim_trailing_spaces);
                self.with_layer_text_rotation(rotation, bbox, |renderer| {
                    renderer.with_suppressed_text_glyphs(|renderer| {
                        renderer.render_layer_payload_node(
                            node_id,
                            RenderNodeType::TextRun(decoration),
                            bbox,
                            false,
                        );
                    });
                });
                self.forced_decoration_trim = previous_forced_trim;
            }
            PaintOp::FootnoteMarker { bbox, marker } => self.render_layer_payload_node(
                node_id,
                RenderNodeType::FootnoteMarker(marker.as_ref().clone()),
                *bbox,
                false,
            ),
            PaintOp::Line { bbox, line } => self.render_layer_payload_node(
                node_id,
                RenderNodeType::Line(line.as_ref().clone()),
                *bbox,
                false,
            ),
            PaintOp::Rectangle { bbox, rect } => self.render_layer_payload_node(
                node_id,
                RenderNodeType::Rectangle(rect.as_ref().clone()),
                *bbox,
                false,
            ),
            PaintOp::Ellipse { bbox, ellipse } => self.render_layer_payload_node(
                node_id,
                RenderNodeType::Ellipse(ellipse.as_ref().clone()),
                *bbox,
                false,
            ),
            PaintOp::Path { bbox, path } => self.render_layer_payload_node(
                node_id,
                RenderNodeType::Path(path.as_ref().clone()),
                *bbox,
                false,
            ),
            PaintOp::Image {
                bbox,
                image,
                resolved,
            } => {
                let image = crate::renderer::image_resolver::image_node_with_resolved_payload(
                    image,
                    resolved.as_deref(),
                );
                self.render_layer_payload_node(node_id, RenderNodeType::Image(image), *bbox, false);
            }
            PaintOp::Equation { bbox, equation } => {
                self.render_layer_payload_node(
                    node_id,
                    RenderNodeType::Equation(equation.as_ref().clone()),
                    *bbox,
                    false,
                );
            }
            PaintOp::ControlLabel { bbox, label } => {
                self.render_layer_control_label(label, *bbox);
            }
            PaintOp::FormObject { bbox, form } => self.render_layer_payload_node(
                node_id,
                RenderNodeType::FormObject(form.as_ref().clone()),
                *bbox,
                false,
            ),
            PaintOp::Placeholder { bbox, placeholder } => self.render_layer_payload_node(
                node_id,
                RenderNodeType::Placeholder(placeholder.as_ref().clone()),
                *bbox,
                false,
            ),
            PaintOp::RawSvg { bbox, raw } => self.render_layer_payload_node(
                node_id,
                RenderNodeType::RawSvg(raw.as_ref().clone()),
                *bbox,
                false,
            ),
        }
        SvgPaintDisposition::Rendered
    }

    fn render_layer_payload_node(
        &mut self,
        node_id: u32,
        node_type: RenderNodeType,
        bbox: BoundingBox,
        emit_text_marks: bool,
    ) {
        let debug_overlay = self.debug_overlay;
        let show_control_codes = self.show_control_codes;
        let show_paragraph_marks = self.show_paragraph_marks;
        self.debug_overlay = false;
        self.show_control_codes = emit_text_marks && show_control_codes;
        self.show_paragraph_marks = emit_text_marks && show_paragraph_marks;
        self.render_node(&RenderNode::new(node_id, node_type, bbox));
        self.debug_overlay = debug_overlay;
        self.show_control_codes = show_control_codes;
        self.show_paragraph_marks = show_paragraph_marks;
    }

    fn with_suppressed_text_glyphs(&mut self, render: impl FnOnce(&mut Self)) {
        let previous = self.suppress_text_glyphs;
        self.suppress_text_glyphs = true;
        render(self);
        self.suppress_text_glyphs = previous;
    }

    fn with_layer_text_rotation(
        &mut self,
        rotation: f64,
        bbox: BoundingBox,
        render: impl FnOnce(&mut Self),
    ) {
        if rotation != 0.0 {
            let center_x = bbox.x + bbox.width / 2.0;
            let center_y = bbox.y + bbox.height / 2.0;
            self.output.push_str(&format!(
                "<g transform=\"rotate({rotation},{center_x},{center_y})\">\n"
            ));
        }
        render(self);
        if rotation != 0.0 {
            self.output.push_str("</g>\n");
        }
    }

    /// Opens a structural clip selected by the canonical layer tree.
    pub(super) fn begin_layer_clip(&mut self, clip: BoundingBox, id: &str) {
        self.defs.push(format!(
            "<clipPath id=\"{}\"><rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\"/></clipPath>\n",
            id, clip.x, clip.y, clip.width, clip.height,
        ));
        self.output
            .push_str(&format!("<g clip-path=\"url(#{})\">", id));
    }

    pub(super) fn begin_layer_path_clip(
        &mut self,
        paths: &[crate::model::text_clip::TextClipPath],
        id: &str,
    ) {
        use crate::model::text_clip::ClipCommand;
        for (index, path) in paths.iter().enumerate() {
            let mut d = String::new();
            for c in &path.commands {
                use std::fmt::Write;
                match *c {
                    ClipCommand::Move(x, y) => {
                        let _ = write!(d, "M{x} {y} ");
                    }
                    ClipCommand::Line(x, y) => {
                        let _ = write!(d, "L{x} {y} ");
                    }
                    ClipCommand::Cubic(a, b, c, d1, e, f) => {
                        let _ = write!(d, "C{a} {b} {c} {d1} {e} {f} ");
                    }
                    ClipCommand::Close => d.push_str("Z "),
                }
            }
            let rule = if path.even_odd { "evenodd" } else { "nonzero" };
            let name = format!("{id}-{index}");
            self.defs.push(format!(
                "<clipPath id=\"{name}\"><path d=\"{d}\" clip-rule=\"{rule}\"/></clipPath>"
            ));
            self.output
                .push_str(&format!("<g clip-path=\"url(#{name})\">"));
        }
    }

    pub(super) fn end_layer_clip(&mut self) {
        self.output.push_str("</g>\n");
    }

    fn render_layer_control_label(&mut self, label: &str, bounds: BoundingBox) {
        let font_size = 10.0;
        self.output.push_str(&format!(
            "<text x=\"{}\" y=\"{}\" font-size=\"{}\" fill=\"#CC3333\">{}</text>\n",
            bounds.x,
            bounds.y + font_size,
            font_size,
            escape_xml(label),
        ));
    }

    /// Accepts pre-projected diagnostic records for SVG serialization.
    pub(super) fn apply_layer_debug_overlay(&mut self, projection: LayerDebugOverlayProjection) {
        self.overlay_para_bounds = projection.paragraph_bounds;
        self.overlay_table_bounds = projection.table_bounds;
        self.overlay_image_bounds = projection.image_bounds;
        self.overlay_vpos_resets = projection.vpos_resets;
        self.overlay_page_section = projection.page_section;
    }

    /// [Issue #1167/#1197] 노드의 z-order plane 키 (작을수록 먼저=아래).
    /// SVG는 단일 스트림으로 출력하므로 웹/CanvasKit의 multi-layer 합성 순서를 직접
    /// 보존해야 한다:
    /// 페이지 배경(0) → 바탕쪽(1) → BehindText 객체(2) → 일반 Flow 콘텐츠(3)
    /// → InFrontOfText 객체(4).
    /// 페이지 배경(흰 바탕·테두리·배경 워터마크)은 반드시 가장 먼저 그려야 한다.
    /// 그러지 않으면 root 레벨에서 BehindText 워터마크가 PageBackground 보다 앞으로
    /// 정렬되어, 흰 배경 rect 가 워터마크를 덮어버린다(#1167 1차 회귀).
    /// 바탕쪽은 한컴의 "본문 뒤" 배경 성격이므로 BehindText 용지 기준 객체보다
    /// 먼저 그려야 한다. 그렇지 않으면 바탕쪽의 전체 페이지 그림이 #1197의 최종
    /// 표시용 BehindText 표를 다시 덮는다.
    /// #1197부터는 RenderNode.layer 가 있으면 표/도형도 이미지와 같은 plane 계약을 따른다.
    fn node_z_plane(node: &RenderNode) -> u8 {
        if matches!(&node.node_type, RenderNodeType::PageBackground(_)) {
            return 0;
        }
        if matches!(&node.node_type, RenderNodeType::MasterPage) {
            // 맨 위로 보내기 바탕쪽은 본문과 글 앞 개체 위에 그린다.
            return if node.layer.is_some_and(|layer| layer.master_front) {
                5
            } else {
                1
            };
        }
        if let Some(layer) = node.layer {
            if let Some(text_wrap) = layer.text_wrap {
                return match text_wrap {
                    crate::model::shape::TextWrap::BehindText => 2,
                    crate::model::shape::TextWrap::InFrontOfText => 4,
                    _ => 3,
                };
            }
        }
        match &node.node_type {
            RenderNodeType::Image(img) => match img.text_wrap {
                Some(crate::model::shape::TextWrap::BehindText) => 2,
                Some(crate::model::shape::TextWrap::InFrontOfText) => 4,
                _ => 3,
            },
            _ => 3,
        }
    }

    /// SVG 렌더 순서의 정렬키 `(plane, z_order, stable_index)`.
    ///
    /// [#4522] 이 키는 `LayoutEngine::paper_node_sort_key` 와 별개 구현이고, #4334 이후
    /// 의미가 갈라져 있다. 두 축 모두 실측했다 —
    /// `issue_4522_two_sort_keys_diverge_on_planes_and_on_the_third_element` 참고.
    ///
    /// **plane 은 합칠 수 없다.** SVG 는 `PageBackground`(0)와 바탕쪽(1)을 따로 갖는데
    /// `paper_node_sort_key` 에는 그 갈래가 없다. 그쪽 plane 을 쓰면 페이지 배경이
    /// BehindText 워터마크 뒤로 밀려 흰 배경 rect 가 워터마크를 덮는다 — #1167 회귀다.
    ///
    /// **세 번째 원소도 아직 합치지 못한다.** 패킹된 `stable_index` 는 `(para << 16) | ctrl`
    /// 이라 셀 경로 축이 없고, `DocPath` 로 바꾸면 셀 안 노드의 순서가 달라진다.
    /// 실제로 `samples/복학원서.hwp` 1쪽의 골든 SVG 가 바뀐다 — 셀 그룹 하나가 통째로
    /// 앞으로 이동한다(바이트 수는 같고 순서만 다르다). 어느 쪽이 한컴 정합인지는 한글
    /// 오라클 없이 정할 수 없어 측정만 남기고 교체하지 않았다. 교체하려면 그 골든을
    /// 어느 쪽으로 갱신할지부터 정해야 한다.
    ///
    /// 모듈 밖에서 부를 수 있게 열어 둔 것은 그 측정 때문이다 — 상태를 바꾸는
    /// test backdoor 가 아니라 순수 함수다.
    pub(crate) fn node_z_sort_key(node: &RenderNode) -> (u8, i32, u32) {
        let layer = node.layer;
        (
            Self::node_z_plane(node),
            layer.map(|l| l.z_order).unwrap_or(0),
            layer.map(|l| l.stable_index).unwrap_or(0),
        )
    }

    /// [Issue #1167/#1197] 자식 중 BehindText/InFrontOfText 객체가 섞여 있어 plane
    /// 재정렬이 필요한지. 대부분의 노드는 Flow 만 가지므로 정렬 비용을 피한다.
    pub(crate) fn children_need_plane_reorder(node: &RenderNode) -> bool {
        node.children.iter().any(|c| Self::node_z_plane(c) != 3)
    }

    /// 개별 노드를 SVG로 렌더링
    fn render_node(&mut self, node: &RenderNode) {
        if let Some(paths) = &node.paint_clip {
            let mut source = node.clone();
            source.paint_clip = None;
            self.begin_layer_path_clip(paths, &format!("source-text-{}", node.id));
            self.render_node(&source);
            for _ in paths {
                self.end_layer_clip();
            }
            return;
        }

        if !node.visible {
            return;
        }
        // [#3375/#4379] 편집 화면 전용 요소는 인쇄 등가 profile 에서 내보내지 않는다 —
        // paint LayerBuilder(`paint/builder.rs:75`)와 같은 술어를 호출한다.
        if node.editor_only && !self.profile.shows_editor_visuals() {
            return;
        }

        match &node.node_type {
            RenderNodeType::Page(page) => {
                self.begin_page(page.width, page.height);
            }
            RenderNodeType::PageBackground(bg) => {
                // 배경색 먼저 (이미지가 투명 부분을 가질 수 있으므로)
                if let Some(color) = bg.background_color {
                    let color_str = color_to_svg(color);
                    self.output.push_str(&format!(
                        "<rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" fill=\"{}\"/>\n",
                        node.bbox.x, node.bbox.y, node.bbox.width, node.bbox.height, color_str,
                    ));
                }
                // 그라데이션 (배경색 위에 덮음)
                if let Some(grad) = &bg.gradient {
                    let grad_id = self.create_gradient_def(
                        grad,
                        (node.bbox.x, node.bbox.y, node.bbox.width, node.bbox.height),
                    );
                    self.output.push_str(&format!(
                        "<rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" fill=\"url(#{})\"/>\n",
                        node.bbox.x, node.bbox.y, node.bbox.width, node.bbox.height, grad_id,
                    ));
                }
                // 이미지 (최상위)
                if let Some(img) = &bg.image {
                    self.render_page_background_image(img, &node.bbox);
                }
            }
            RenderNodeType::TextRun(run) => {
                // 폰트 임베딩: 사용된 폰트/글자 수집
                if self.font_embed_mode != FontEmbedMode::None && !run.style.font_family.is_empty()
                {
                    // SVG 본문에서 `font-weight="bold"`를 내보내는 것과 같은
                    // 조건을 쓴다. CharShape.bold 외에 family 이름에 명시된 Bold
                    // face도 실제 Bold outline을 선택해야 synthetic bold가 되지 않는다.
                    // 체인 전체를 한 face 이름으로 임베딩하면 CSS가 실제 선택하는
                    // 각 face에는 공급되지 않는다. 측정과 같은 선언 순서의 face를 모은다.
                    for family in run
                        .style
                        .font_family
                        .split(',')
                        .map(str::trim)
                        .filter(|s| !s.is_empty())
                    {
                        if run.style.is_visually_bold() {
                            self.font_bold_families.insert(family.to_string());
                        }
                        let codepoints =
                            self.font_codepoints.entry(family.to_string()).or_default();
                        // 그려지는 글자로 모은다 — 필드는 표시값이 나간다 (Task #3216).
                        for ch in run.display_or_text().chars() {
                            if !ch.is_control() {
                                codepoints.insert(ch);
                            }
                        }
                    }
                }
                if self.render_composed_overlap(node, run) {
                    // 원문 겹침의 모든 글자는 위 공통 결과로 출력했다.
                } else if let Some(ref overlap) = run.char_overlap {
                    // 글자겹침(CharOverlap) 렌더링: 각 문자에 테두리 도형 + 텍스트
                    self.draw_char_overlap(
                        &run.text,
                        &run.style,
                        overlap,
                        node.bbox.x,
                        node.bbox.y,
                        node.bbox.width,
                        node.bbox.height,
                    );
                } else if run.rotation != 0.0 {
                    // 회전 텍스트: bbox 중앙에 중앙 정렬 후 회전
                    let cx = node.bbox.x + node.bbox.width / 2.0;
                    let cy = node.bbox.y + node.bbox.height / 2.0;
                    let color = color_to_svg(run.style.color);
                    let font_size = run.style.effective_font_size();
                    let font_family = if run.style.font_family.is_empty() {
                        "sans-serif".to_string()
                    } else {
                        // [#3314] 요청 face → base family → generic 체인.
                        // [#3772] bold 는 ExtraLight 를 빼서 PDF 굵기를 지킨다.
                        super::render_font_family_chain_for_weight(
                            &run.style.font_family,
                            run.style.is_visually_bold(),
                        )
                    };
                    let mut attrs = format!("font-family=\"{}\" font-size=\"{}\" fill=\"{}\" text-anchor=\"middle\" dominant-baseline=\"central\"",
                        escape_xml(&font_family), font_size, color);
                    if let Some(w) = faux_bold_stroke_width(&run.style, font_size) {
                        attrs.push_str(&faux_bold_stroke_attr(w, &color));
                    } else if run.style.is_visually_bold() {
                        attrs.push_str(" font-weight=\"bold\"");
                    } else if run.style.is_medium_weight() {
                        attrs.push_str(" font-weight=\"500\"");
                    }
                    if run.style.italic {
                        attrs.push_str(&format!(
                            " font-style=\"{}\"",
                            super::text_italic::CSS_STYLE
                        ));
                    }
                    for c in run.display_or_text().chars() {
                        if c == ' ' {
                            continue;
                        }
                        self.output.push_str(&format!(
                            "<text x=\"{}\" y=\"{}\" {} transform=\"rotate({},{},{})\">{}</text>\n",
                            cx,
                            cy,
                            attrs,
                            run.rotation,
                            cx,
                            cy,
                            escape_xml(&c.to_string()),
                        ));
                    }
                } else {
                    self.active_decoration_trim = self.forced_decoration_trim.unwrap_or({
                        match self.soft_wrap_decoration_trim {
                            Some((id, trim)) if id == node.id => trim,
                            _ => 0,
                        }
                    });
                    // [#6451] 장식선은 레이아웃 폭을 따른다 — 작성기 자체 측정과
                    // 어긋나면 run 경계마다 실틈이 남는다.
                    self.active_decoration_width = Some(node.bbox.width);
                    self.draw_text_positioned(
                        run.metric_or_display_text(),
                        node.bbox.x,
                        node.bbox.y + run.baseline,
                        &run.style,
                        run.validated_layout_positions_for(run.display_or_text()),
                    );
                    self.active_decoration_trim = 0;
                    self.active_decoration_width = None;
                }
                if self.show_paragraph_marks || self.show_control_codes {
                    // 조판부호 마커 TextRun은 공백 기호 표시 건너뛰기
                    let is_marker = !matches!(
                        run.field_marker,
                        crate::renderer::render_tree::FieldMarkerType::None
                    );
                    let font_size = run.style.effective_font_size();
                    // 공백·탭 기호: 각 문자 위치에 오버레이
                    if !run.text.is_empty() && !is_marker {
                        let char_positions = run.replay_positions_for(&run.text);
                        let visual = super::text_direction::VisualTextPositions::for_style(
                            &run.text,
                            &char_positions,
                            &run.style,
                        );
                        let origin = |i: usize| {
                            visual
                                .as_ref()
                                .and_then(|p| p.span_origin(i, i + 1))
                                .unwrap_or(char_positions[i])
                        };
                        let mark_font_size = font_size * 0.5;
                        for (i, c) in run.text.chars().enumerate() {
                            if c == ' ' {
                                let cx = node.bbox.x + origin(i);
                                // ∨ 기호를 공백 영역 중앙 하단에 배치
                                let next_x = if i + 1 < char_positions.len() {
                                    cx + char_positions[i + 1] - char_positions[i]
                                } else {
                                    node.bbox.x + node.bbox.width
                                };
                                let mid_x = (cx + next_x) / 2.0 - mark_font_size * 0.25;
                                self.output.push_str(&format!(
                                    "<text x=\"{}\" y=\"{}\" font-size=\"{}\" fill=\"#0066FF\">\u{2228}</text>\n",
                                    mid_x, node.bbox.y + run.baseline, mark_font_size,
                                ));
                            } else if c == '\t' {
                                let cx = node.bbox.x + origin(i);
                                self.output.push_str(&format!(
                                    "<text x=\"{}\" y=\"{}\" font-size=\"{}\" fill=\"#0066FF\">\u{2192}</text>\n",
                                    cx, node.bbox.y + run.baseline, mark_font_size,
                                ));
                            }
                        }
                    }
                    // 하드 리턴·강제 줄바꿈 기호
                    if run.is_para_end || run.is_line_break_end {
                        let mark_x = if run.text.is_empty() {
                            node.bbox.x
                        } else {
                            node.bbox.x + node.bbox.width
                        };
                        let mark = if run.is_line_break_end {
                            "\u{2193}"
                        } else {
                            "\u{21B5}"
                        };
                        self.output.push_str(&format!(
                            "<text x=\"{}\" y=\"{}\" font-size=\"{}\" fill=\"#0066FF\">{}</text>\n",
                            mark_x,
                            node.bbox.y + run.baseline,
                            font_size,
                            mark,
                        ));
                    }
                }
            }
            RenderNodeType::FootnoteMarker(marker) => {
                if let Some(run) = marker.source_run.as_deref() {
                    self.render_node(&RenderNode::new(
                        node.id,
                        RenderNodeType::TextRun(run.clone()),
                        node.bbox,
                    ));
                    return;
                }
                let style = marker.paint_style();
                let sup_size = style.font_size;
                let color = color_to_svg(style.color);
                let font_family = if style.font_family.is_empty() {
                    "sans-serif"
                } else {
                    &style.font_family
                };
                let y = node.bbox.y + marker.baseline;
                self.output.push_str(&format!(
                    "<text x=\"{}\" y=\"{}\" font-family=\"{}\" font-size=\"{}\" fill=\"{}\">{}</text>\n",
                    node.bbox.x, y, escape_xml(font_family), sup_size, color, escape_xml(&marker.text),
                ));
            }
            RenderNodeType::Rectangle(rect) => {
                self.open_shape_transform(&rect.transform, &node.bbox);
                if rect.round_stroke_join {
                    self.output.push_str("<g stroke-linejoin=\"round\">");
                }
                self.draw_rect_with_gradient(
                    node.bbox.x,
                    node.bbox.y,
                    node.bbox.width,
                    node.bbox.height,
                    rect.corner_radius,
                    &rect.style,
                    rect.gradient.as_deref(),
                );
                if rect.round_stroke_join {
                    self.output.push_str("</g>");
                }
            }
            RenderNodeType::Line(line) => {
                self.open_shape_transform(&line.transform, &node.bbox);
                let axis_hint = self.axis_stroke_hint_allowed;
                self.axis_stroke_hint_allowed &= !line.transform.has_transform();
                for stroke in line.paint_strokes() {
                    self.draw_line(stroke.x1, stroke.y1, stroke.x2, stroke.y2, &stroke.style);
                }
                self.axis_stroke_hint_allowed = axis_hint;
            }
            RenderNodeType::Ellipse(ellipse) => {
                self.open_shape_transform(&ellipse.transform, &node.bbox);
                let cx = node.bbox.x + node.bbox.width / 2.0;
                let cy = node.bbox.y + node.bbox.height / 2.0;
                self.draw_ellipse_with_gradient(
                    cx,
                    cy,
                    node.bbox.width / 2.0,
                    node.bbox.height / 2.0,
                    &ellipse.style,
                    ellipse.gradient.as_deref(),
                );
            }
            RenderNodeType::Image(img) => {
                // [shot 05] 회전 90/270° 시 bbox extent swap — 이중회전 방지.
                // [#7193] 그림은 틀(node.bbox)에서 안쪽 여백을 뺀 자리에 그린다.
                let eff_bbox = img.transformed_paint_bbox(&node.bbox);
                if let Some(points) = img.source_clip_path(&node.bbox) {
                    let points = points
                        .iter()
                        .map(|p| format!("{},{}", p[0], p[1]))
                        .collect::<Vec<_>>()
                        .join(" ");
                    self.output.push_str(&format!(
                        "<defs><clipPath id=\"img-source-{}\"><polygon points=\"{}\"/></clipPath></defs><g clip-path=\"url(#img-source-{})\">\n",
                        node.id,points,node.id));
                }
                self.open_shape_transform(&img.transform, &eff_bbox);
                self.render_image_node(img, &eff_bbox);
            }
            RenderNodeType::Path(path) => {
                self.open_shape_transform(&path.transform, &node.bbox);
                self.draw_path_with_gradient(&path.commands, &path.style, path.gradient.as_deref());
                self.draw_path_arrow_markers(path);
            }
            RenderNodeType::Equation(eq) => {
                // 수식 SVG 조각을 bbox 위치에 배치
                // 저장 프레임은 흐름 예약 영역이고 글자 장평이 아니다. BaseUnit으로
                // 만든 공통 글자·장식 폭을 유지하며 압축 프레임의 세로 비율만 적용한다.
                let scale_y = super::equation::stored_vertical_scale(
                    node.bbox.height,
                    eq.layout_box.height,
                    eq.font_size,
                );
                let needs_scale = (scale_y - 1.0).abs() > 0.01;
                if needs_scale {
                    self.output.push_str(&format!(
                        "<g transform=\"translate({},{}) scale(1,{:.4})\">\n",
                        node.bbox.x, node.bbox.y, scale_y,
                    ));
                } else {
                    self.output.push_str(&format!(
                        "<g transform=\"translate({},{})\">\n",
                        node.bbox.x, node.bbox.y,
                    ));
                }
                self.output.push_str(&eq.svg_content);
                self.output.push_str("</g>\n");
                // 폰트 임베딩: 수식에서 사용된 글자 수집
                if self.font_embed_mode != FontEmbedMode::None {
                    // SVG <text> 요소마다 실제 사용하는 글꼴의 글자를 수집한다.
                    for segment in eq.svg_content.split("</text>") {
                        if let Some(start) = segment.rfind('>') {
                            let text = &segment[start + 1..];
                            let header = &segment[..start];
                            // 표시 조각이 선언한 실제 face를 공급한다. 구형 원본
                            // glyph를 영문이라는 이유로 다른 수학 face로 추정하지 않는다.
                            let family = header
                                .rsplit("<text")
                                .next()
                                .and_then(|attrs| {
                                    super::svg_fragment::find_svg_attr_value(attrs, "font-family")
                                })
                                .and_then(|families| families.split(',').next())
                                .map(|face| face.trim().trim_matches(['\'', '"']))
                                .filter(|face| !face.is_empty())
                                .unwrap_or_else(|| {
                                    if super::equation::text_has_cjk(text) {
                                        "Haansoft Batang"
                                    } else {
                                        "Latin Modern Math"
                                    }
                                });
                            self.font_codepoints
                                .entry(family.to_string())
                                .or_default()
                                .extend(text.chars());
                        }
                    }
                }
            }
            RenderNodeType::FormObject(form) => {
                self.render_form_object(form, &node.bbox);
            }
            RenderNodeType::RawSvg(r) => {
                if self.font_embed_mode != FontEmbedMode::None {
                    for usage in super::svg_fragment::svg_text_font_usage(&r.svg) {
                        if usage.bold {
                            self.font_bold_families.insert(usage.family.clone());
                        }
                        self.font_codepoints
                            .entry(usage.family)
                            .or_default()
                            .extend(usage.text.chars().filter(|ch| !ch.is_control()));
                    }
                }
                // Task #195 단계 8: OOXML 차트 SVG 조각 그대로 삽입
                self.output.push_str(&r.svg);
            }
            RenderNodeType::Placeholder(ph) => {
                // [Task #2225] 그림 미지정 placeholder 는 인쇄 등가 profile에서
                // 미출력하고 편집 profile에서만 표시한다.
                if matches!(
                    ph.kind,
                    crate::renderer::render_tree::PlaceholderKind::MissingPicture
                ) && !self.show_missing_picture_placeholder
                {
                    return;
                }
                // 그림 미지정은 라벨 없는 전용 표시다 — 한글 편집 화면과 같은 점선 테두리 +
                // 중앙의 그림-없음 아이콘. 차트/OLE 의 "라벨 박스"를 쓰면 빈 라벨만 남아
                // 한글과 달라진다.
                if matches!(
                    ph.kind,
                    crate::renderer::render_tree::PlaceholderKind::MissingPicture
                ) {
                    self.draw_missing_picture_placeholder(&node.bbox);
                    return;
                }
                // Task #195: 차트/OLE placeholder (점선 테두리 + 중앙 라벨)
                let cx = node.bbox.x + node.bbox.width / 2.0;
                let cy = node.bbox.y + node.bbox.height / 2.0;
                let font_size = (node.bbox.width.min(node.bbox.height) * 0.06).clamp(12.0, 28.0);
                self.output.push_str(&format!(
                    "<rect x=\"{:.2}\" y=\"{:.2}\" width=\"{:.2}\" height=\"{:.2}\" fill=\"{}\" stroke=\"{}\" stroke-width=\"1\" stroke-dasharray=\"6 3\"/>\n",
                    node.bbox.x, node.bbox.y, node.bbox.width, node.bbox.height,
                    color_to_svg(ph.fill_color), color_to_svg(ph.stroke_color),
                ));
                self.output.push_str(&format!(
                    "<text x=\"{:.2}\" y=\"{:.2}\" font-family=\"sans-serif\" font-size=\"{:.1}\" fill=\"{}\" text-anchor=\"middle\" dominant-baseline=\"central\">{}</text>\n",
                    cx, cy, font_size, color_to_svg(ph.stroke_color), escape_xml(&ph.label),
                ));
            }
            RenderNodeType::Body {
                clip_rect: Some(cr),
            } => {
                let clip_id = format!("body-clip-{}", node.id);
                let right_pad = if self.show_paragraph_marks || self.show_control_codes {
                    TEXT_MARK_CLIP_RIGHT_PAD
                } else {
                    0.0
                };
                self.defs.push(format!(
                    "<clipPath id=\"{}\"><rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\"/></clipPath>\n",
                    clip_id,
                    cr.x,
                    cr.y,
                    cr.width + right_pad,
                    cr.height,
                ));
                self.output
                    .push_str(&format!("<g clip-path=\"url(#{})\">", clip_id));
            }
            RenderNodeType::TableCell(ref tc) if tc.clip => {
                let clip_id = format!("cell-clip-{}", node.id);
                self.defs.push(format!(
                    "<clipPath id=\"{}\"><rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\"/></clipPath>\n",
                    clip_id, node.bbox.x, node.bbox.y, node.bbox.width, node.bbox.height,
                ));
                self.output
                    .push_str(&format!("<g clip-path=\"url(#{})\">", clip_id));
            }
            RenderNodeType::TextBox => {
                let clip_id = format!("textbox-clip-{}", node.id);
                self.defs.push(format!(
                    "<clipPath id=\"{}\"><rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\"/></clipPath>\n",
                    clip_id, node.bbox.x, node.bbox.y, node.bbox.width, node.bbox.height,
                ));
                self.output
                    .push_str(&format!("<g clip-path=\"url(#{})\">", clip_id));
            }
            _ => {}
        }

        // [#6028] soft-wrap 줄의 마지막 텍스트 run 을 찾아 줄-말미 공백 수를
        // 기록한다. 문단 마지막 줄(is_para_end)·강제 줄바꿈 줄(is_line_break_end)
        // 은 말미 공백이 저자 콘텐츠(밑줄 서명란 등)라 대상에서 뺀다.
        if matches!(&node.node_type, RenderNodeType::TextLine(_)) {
            self.soft_wrap_decoration_trim = node
                .children
                .iter()
                .rev()
                .find_map(|child| {
                    if let RenderNodeType::TextRun(run) = &child.node_type {
                        if run.text.chars().any(|ch| ch != ' ') {
                            if run.is_para_end || run.is_line_break_end {
                                return Some(None);
                            }
                            let trailing =
                                run.text.chars().rev().take_while(|ch| *ch == ' ').count();
                            if trailing > 0 {
                                return Some(Some((child.id, trailing)));
                            }
                            return Some(None);
                        }
                    }
                    None
                })
                .flatten();
        }

        // 디버그 오버레이: 문단/표 경계 수집 (셀 내부·머리말·꼬리말 제외)
        if self.debug_overlay {
            match &node.node_type {
                RenderNodeType::TextLine(tl) => {
                    if self.overlay_skip_depth == 0 {
                        // section_index가 없는 TextLine은 Shape 내부 등 비본문 요소 — 제외
                        if let (Some(pi), Some(si)) = (tl.para_index, tl.section_index) {
                            // 페이지 메인 섹션 자동 감지 (처음 등장하는 섹션이 메인)
                            if self.overlay_page_section == -1 {
                                self.overlay_page_section = si as i32;
                            }
                            // 페이지 메인 섹션이 아닌 섹션 문단은 오버레이에서 제외
                            // (구역 정의 섹션, 다른 섹션 나누기 문단 등)
                            if si as i32 != self.overlay_page_section {
                                // skip
                            } else {
                                // (section, para) 복합키로 섹션 간 구분
                                let key = si * 100000 + pi;
                                let entry =
                                    self.overlay_para_bounds
                                        .entry(key)
                                        .or_insert(OverlayBounds {
                                            section_index: si,
                                            x: node.bbox.x,
                                            y: node.bbox.y,
                                            width: node.bbox.width,
                                            height: node.bbox.height,
                                        });
                                // 기존 bounds 확장 (여러 줄이 하나의 문단)
                                let min_x = entry.x.min(node.bbox.x);
                                let min_y = entry.y.min(node.bbox.y);
                                let max_x =
                                    (entry.x + entry.width).max(node.bbox.x + node.bbox.width);
                                let max_y =
                                    (entry.y + entry.height).max(node.bbox.y + node.bbox.height);
                                entry.x = min_x;
                                entry.y = min_y;
                                entry.width = max_x - min_x;
                                entry.height = max_y - min_y;

                                // vpos=0 리셋 검출: 문단 첫 줄(line 0) 제외하고 vertical_pos == 0
                                if let (Some(li), Some(vp)) = (tl.line_index, tl.vpos) {
                                    if li > 0 && vp == 0 {
                                        self.overlay_vpos_resets.push(OverlayVposReset {
                                            section_index: si,
                                            para_index: pi,
                                            line_index: li,
                                            y: node.bbox.y,
                                            x: node.bbox.x,
                                            width: node.bbox.width,
                                        });
                                    }
                                }
                            }
                        }
                    }
                }
                RenderNodeType::Table(tbl) => {
                    if let (Some(pi), Some(ci)) = (tbl.para_index, tbl.control_index) {
                        if self.overlay_skip_depth == 0 {
                            let tbl_si = tbl.section_index.unwrap_or(0);
                            // 페이지 메인 섹션 자동 감지
                            if self.overlay_page_section == -1 {
                                self.overlay_page_section = tbl_si as i32;
                            }
                            if tbl_si as i32 == self.overlay_page_section {
                                self.overlay_table_bounds.push(OverlayTableInfo {
                                    section_index: tbl_si,
                                    para_index: pi,
                                    control_index: ci,
                                    x: node.bbox.x,
                                    y: node.bbox.y,
                                    width: node.bbox.width,
                                    height: node.bbox.height,
                                    row_count: tbl.row_count,
                                    col_count: tbl.col_count,
                                });
                                // 표를 포함하는 문단 bounds도 확장 (텍스트 없는 문단 처리)
                                let key = tbl_si * 100000 + pi;
                                let entry =
                                    self.overlay_para_bounds
                                        .entry(key)
                                        .or_insert(OverlayBounds {
                                            section_index: tbl_si,
                                            x: node.bbox.x,
                                            y: node.bbox.y,
                                            width: node.bbox.width,
                                            height: node.bbox.height,
                                        });
                                let min_x = entry.x.min(node.bbox.x);
                                let min_y = entry.y.min(node.bbox.y);
                                let max_x =
                                    (entry.x + entry.width).max(node.bbox.x + node.bbox.width);
                                let max_y =
                                    (entry.y + entry.height).max(node.bbox.y + node.bbox.height);
                                entry.x = min_x;
                                entry.y = min_y;
                                entry.width = max_x - min_x;
                                entry.height = max_y - min_y;
                            }
                        }
                    }
                    self.overlay_skip_depth += 1;
                }
                RenderNodeType::Image(img) => {
                    if let (Some(pi), Some(ci)) = (img.para_index, img.control_index) {
                        if self.overlay_skip_depth == 0 {
                            let img_si = img.section_index.unwrap_or(0);
                            if self.overlay_page_section == -1 {
                                self.overlay_page_section = img_si as i32;
                            }
                            if img_si as i32 == self.overlay_page_section {
                                self.overlay_image_bounds.push(OverlayImageInfo {
                                    section_index: img_si,
                                    para_index: pi,
                                    control_index: ci,
                                    x: node.bbox.x,
                                    y: node.bbox.y,
                                    width: node.bbox.width,
                                    height: node.bbox.height,
                                });
                            }
                        }
                    }
                }
                // 머리말/꼬리말/바탕쪽/각주/텍스트박스/그룹: body 외 영역 제외
                RenderNodeType::Header
                | RenderNodeType::Footer
                | RenderNodeType::MasterPage
                | RenderNodeType::FootnoteArea
                | RenderNodeType::TextBox
                | RenderNodeType::Group(_) => {
                    self.overlay_skip_depth += 1;
                }
                _ => {}
            }
        }

        // [Issue #1167] 자식을 z-order plane 순서로 순회한다.
        // SVG 는 후순위가 위로 합성되므로, BehindText 그림(워터마크)은 본문(Flow)
        // 보다 먼저, InFrontOfText 그림(직인 등)은 본문보다 나중에 그려야 한다.
        // PaintOp replay plane(background → behindText → flow → inFrontOfText)과
        // 동일 의미. 같은 plane 내부는 안정 정렬로 기존 트리 순서를 보존한다.
        // (PNG=native Skia / 웹캔버스=CanvasKit 는 PaintOp replay plane 으로 이미
        //  정정됨 — PR #1163 / #1017. 본 변경은 SVG 경로 정합.)
        if matches!(node.node_type, RenderNodeType::Column(_)) {
            // 본문은 LayerBuilder와 같은 흐름/앵커 순서를 소비한다.
            for child in crate::renderer::paint_order::children(node) {
                self.render_node(child);
            }
        } else if Self::children_need_plane_reorder(node) {
            let mut ordered: Vec<&RenderNode> = node.children.iter().collect();
            ordered.sort_by_key(|c| Self::node_z_sort_key(c));
            for child in ordered {
                self.render_node(child);
            }
        } else {
            for child in &node.children {
                self.render_node(child);
            }
        }

        // 디버그 오버레이: skip 깊이 복원
        if self.debug_overlay {
            match &node.node_type {
                RenderNodeType::Table(_)
                | RenderNodeType::Header
                | RenderNodeType::Footer
                | RenderNodeType::MasterPage
                | RenderNodeType::FootnoteArea
                | RenderNodeType::TextBox
                | RenderNodeType::Group(_) => {
                    self.overlay_skip_depth = self.overlay_skip_depth.saturating_sub(1);
                }
                _ => {}
            }
        }

        // 도형 변환 그룹 종료
        self.close_shape_transform(&node.node_type);
        if matches!(&node.node_type, RenderNodeType::Image(image) if image.source_rect.is_some()) {
            self.output.push_str("</g>\n");
        }

        // 조판부호 개체 마커 (붉은색 대괄호) — 조판부호 ON일 때만
        if self.show_control_codes {
            let label = node.control_code_label();
            if let Some(label) = label {
                let fs = 10.0; // 조판부호 고정 크기
                self.output.push_str(&format!(
                    "<text x=\"{}\" y=\"{}\" font-size=\"{}\" fill=\"#CC3333\">{}</text>\n",
                    node.bbox.x,
                    node.bbox.y + fs,
                    fs,
                    label,
                ));
            }
        }

        // 셀 클리핑 그룹 종료
        if matches!(&node.node_type, RenderNodeType::TableCell(tc) if tc.clip) {
            self.output.push_str("</g>\n");
        }

        // TextBox 클리핑 그룹 종료
        if matches!(node.node_type, RenderNodeType::TextBox) {
            self.output.push_str("</g>\n");
        }

        // Body 클리핑 그룹 종료
        if matches!(node.node_type, RenderNodeType::Body { clip_rect: Some(_) }) {
            self.output.push_str("</g>\n");
        }

        // 페이지 종료 태그
        if matches!(node.node_type, RenderNodeType::Page(_)) {
            self.end_page();
        }
    }

    /// 도형 변환(회전/대칭)이 있으면 `<g transform="...">` 래퍼를 연다.
    fn open_shape_transform(&mut self, transform: &ShapeTransform, bbox: &BoundingBox) {
        if !transform.has_transform() {
            return;
        }
        let cx = bbox.x + bbox.width / 2.0;
        let cy = bbox.y + bbox.height / 2.0;
        let mut parts = Vec::new();
        // [Task #1067] SVG transform 은 left-to-right 적용 (첫 transform 이 마지막 영향).
        // 한컴 정답지 시각 표준: 도형이 자체 좌표계 기준으로 먼저 회전 후 flip 적용.
        // SVG 에서 동일 결과 = "translate(flip) scale(-1,1) rotate(-θ)"
        // (flip 와 함께 회전 시 각도 부호 반전 필요).
        if transform.horz_flip {
            parts.push(format!("translate({},0) scale(-1,1)", cx * 2.0));
        }
        if transform.vert_flip {
            parts.push(format!("translate(0,{}) scale(1,-1)", cy * 2.0));
        }
        if transform.rotation != 0.0 {
            let effective_rotation = transform.reflected_rotation();
            parts.push(format!("rotate({},{},{})", effective_rotation, cx, cy));
        }
        self.output
            .push_str(&format!("<g transform=\"{}\">\n", parts.join(" ")));
    }

    /// 도형 변환 그룹을 닫는다 (open_shape_transform에 대응).
    fn close_shape_transform(&mut self, node_type: &RenderNodeType) {
        let transform = match node_type {
            RenderNodeType::Rectangle(r) => &r.transform,
            RenderNodeType::Line(l) => &l.transform,
            RenderNodeType::Ellipse(e) => &e.transform,
            RenderNodeType::Image(i) => &i.transform,
            RenderNodeType::Path(p) => &p.transform,
            _ => return,
        };
        if transform.has_transform() {
            self.output.push_str("</g>\n");
        }
    }

    /// 그라데이션 SVG 정의 생성, ID 반환
    fn create_gradient_def(
        &mut self,
        grad: &GradientFillInfo,
        bbox: (f64, f64, f64, f64),
    ) -> String {
        self.gradient_counter += 1;
        let id = format!("grad{}", self.gradient_counter);

        let (colors, positions) =
            super::linear_gradient_color_stops(grad, bbox.0, bbox.1, bbox.2, bbox.3);
        let stops = Self::build_gradient_stops(&GradientFillInfo {
            colors,
            positions,
            ..grad.clone()
        });

        let def = match grad.gradient_type {
            4 if bbox.2 > 0.0 && bbox.3 > 0.0 => {
                let (bx, by, bw, bh) = bbox;
                let (cx, cy, radius, cos, sin) =
                    super::square_gradient_geometry(grad, bx, by, bw, bh);
                let point = |u: f64, v: f64| {
                    (
                        cx + radius * (u * cos - v * sin),
                        cy + radius * (u * sin + v * cos),
                    )
                };
                let corners = [(1.0, -1.0), (1.0, 1.0), (-1.0, 1.0), (-1.0, -1.0)];
                let normals = [(1.0, 0.0), (0.0, 1.0), (-1.0, 0.0), (0.0, -1.0)];
                let outside = color_to_svg(*grad.colors.last().unwrap_or(&0));
                let mut pattern = format!("<pattern id=\"{id}\" patternUnits=\"userSpaceOnUse\" x=\"{bx}\" y=\"{by}\" width=\"{bw}\" height=\"{bh}\" viewBox=\"{bx} {by} {bw} {bh}\"><rect x=\"{bx}\" y=\"{by}\" width=\"{bw}\" height=\"{bh}\" fill=\"{outside}\"/>\n");
                // max(|회전 x|, |회전 y|)는 네 삼각형 안에서 각각 선형이다.
                // 각 면의 중심→변 색상 축을 공통 물리 좌표에서 만든다.
                for index in 0..4 {
                    let (ex, ey) = point(normals[index].0, normals[index].1);
                    let (ax, ay) = point(corners[index].0, corners[index].1);
                    let (bx, by) = point(corners[(index + 1) % 4].0, corners[(index + 1) % 4].1);
                    pattern.push_str(&format!("<linearGradient id=\"{id}s{index}\" gradientUnits=\"userSpaceOnUse\" x1=\"{cx}\" y1=\"{cy}\" x2=\"{ex}\" y2=\"{ey}\">{stops}</linearGradient><path d=\"M{cx} {cy}L{ax} {ay}L{bx} {by}Z\" fill=\"url(#{id}s{index})\"/>\n"));
                }
                pattern.push_str("</pattern>\n");
                pattern
            }
            2 => {
                // 원형 (Radial)
                if let Some((cx, cy, radius)) =
                    super::gradient_geometry::radial_circle(bbox, grad.center_x, grad.center_y)
                {
                    format!(
                        "<radialGradient id=\"{}\" gradientUnits=\"userSpaceOnUse\" cx=\"{}\" cy=\"{}\" r=\"{}\" fx=\"{}\" fy=\"{}\">\n{}</radialGradient>\n",
                        id, cx, cy, radius, cx, cy, stops,
                    )
                } else {
                    format!(
                        "<radialGradient id=\"{}\" cx=\"{}%\" cy=\"{}%\" r=\"50%\" fx=\"{}%\" fy=\"{}%\">\n{}</radialGradient>\n",
                        id, grad.center_x, grad.center_y, grad.center_x, grad.center_y, stops,
                    )
                }
            }
            _ => {
                // 선형 (Linear) — 원뿔과 치수를 알 수 없는 채우기는 기존 선형 근사.
                //
                // [#6845] 축은 **사용자 좌표계**로 낸다. `objectBoundingBox` 백분율은
                // 상자의 가로·세로를 각각 0~1 로 정규화하므로 가로세로비가 1 이 아니면
                // 각도가 눕는다 — 113424 7쪽(623.6×37.8px)에서 등색선 기울기가
                // 한/글 −0.365 인데 rhwp 는 +3.72 였다.
                let (bx, by, bw, bh) = bbox;
                if bw > 0.0 && bh > 0.0 {
                    let (x1, y1, x2, y2) =
                        super::linear_gradient_axis_for_fill(grad, bx, by, bw, bh);
                    format!(
                        "<linearGradient id=\"{}\" gradientUnits=\"userSpaceOnUse\" x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\">\n{}</linearGradient>\n",
                        id, x1, y1, x2, y2, stops,
                    )
                } else {
                    // 치수를 모르면 정규화 공간으로 물러난다(빈 상자 등).
                    let (x1, y1, x2, y2) = Self::angle_to_svg_coords(grad.angle);
                    format!(
                        "<linearGradient id=\"{}\" x1=\"{}%\" y1=\"{}%\" x2=\"{}%\" y2=\"{}%\">\n{}</linearGradient>\n",
                        id, x1, y1, x2, y2, stops,
                    )
                }
            }
        };

        self.defs.push(def);
        id
    }

    /// 패턴 채우기 SVG 정의 생성, ID 반환
    fn create_pattern_def(&mut self, info: &PatternFillInfo) -> String {
        self.clip_counter += 1;
        let id = format!("pat{}", self.clip_counter);
        let bg = color_to_svg(info.background_color);
        let fg = color_to_svg(info.pattern_color);
        let sz = info.tile_size;
        let stroke = sz / 8.0;
        // 독립 Print의 0~5 hatch: 쪽 원점에 고정한 8-dot/100dpi 무늬.
        let horizontal = format!("<path d=\"M0 0H{sz}M0 {sz}H{sz}\"/>");
        let vertical = format!("<path d=\"M0 0V{sz}M{sz} 0V{sz}\"/>");
        let rising = format!("<path d=\"M{sz} 0L0 {sz}\"/>");
        let falling = format!("<path d=\"M0 0L{sz} {sz}\"/>");
        let lines = match HatchStyle::from_pattern_type(info.pattern_type) {
            Some(HatchStyle::Horizontal) => horizontal,
            Some(HatchStyle::Vertical) => vertical,
            Some(HatchStyle::Falling) => falling,
            Some(HatchStyle::Rising) => rising,
            Some(HatchStyle::Cross) => format!("{horizontal}{vertical}"),
            Some(HatchStyle::DiagonalCross) => format!("{rising}{falling}"),
            None => String::new(),
        };
        let def = format!(
            "<pattern id=\"{id}\" patternUnits=\"userSpaceOnUse\" width=\"{sz}\" height=\"{sz}\"><rect width=\"{sz}\" height=\"{sz}\" fill=\"{bg}\"/><g fill=\"none\" stroke=\"{fg}\" stroke-width=\"{stroke}\">{lines}</g></pattern>\n"
        );
        self.defs.push(def);
        id
    }

    /// ShapeStyle에서 SVG fill 속성 문자열 생성
    fn build_fill_attr(
        &mut self,
        style: &ShapeStyle,
        gradient: Option<&GradientFillInfo>,
        bbox: (f64, f64, f64, f64),
    ) -> String {
        if let Some(grad) = gradient {
            let grad_id = self.create_gradient_def(grad, bbox);
            format!(" fill=\"url(#{})\"", grad_id)
        } else if let Some(ref pat) = style.pattern {
            let pat_id = self.create_pattern_def(pat);
            format!(" fill=\"url(#{})\"", pat_id)
        } else if let Some(fill) = style.fill_color {
            format!(" fill=\"{}\"", color_to_svg(fill))
        } else {
            " fill=\"none\"".to_string()
        }
    }

    /// 화살표 마커 SVG 정의 생성 (중복 시 기존 ID 반환)
    ///
    /// A marker replays the common arrow outline at the original endpoint.
    fn ensure_arrow_marker(
        &mut self,
        color: &str,
        stroke_width: f64,
        _line_len: f64,
        arrow: &super::ArrowStyle,
        arrow_size: u8,
        is_start: bool,
    ) -> String {
        let dir = if is_start { "s" } else { "e" };
        let id = format!(
            "mk-{:?}-{}-{}-{}-{:x}",
            arrow,
            dir,
            color.replace('#', ""),
            arrow_size,
            stroke_width.to_bits()
        );
        if !self.defs_ids.insert(id.clone()) {
            return id;
        }
        if let Some(head) = super::arrow::head(*arrow, stroke_width, arrow_size) {
            let (length, height) = super::arrow::dimensions(stroke_width, arrow_size);
            let direction = if is_start { -1.0 } else { 1.0 };
            let commands = head.at(0.0, 0.0, direction, 0.0);
            let d = svg_path_data(&commands);
            let left = if is_start { 0.0 } else { -length };
            let fill = if head.filled { color } else { "white" };
            let outline = if head.filled { "none" } else { color };
            let outline_width = (stroke_width * 0.3).max(0.5);
            self.defs.push(format!(
                "<marker id=\"{id}\" viewBox=\"{left} {} {length} {height}\" refX=\"0\" refY=\"0\" markerWidth=\"{length}\" markerHeight=\"{height}\" orient=\"auto\" markerUnits=\"userSpaceOnUse\" overflow=\"visible\"><path d=\"{}\" fill=\"{fill}\" stroke=\"{outline}\" stroke-width=\"{outline_width}\"/></marker>\n",
                -height / 2.0, d.trim()));
        }
        id
    }

    /// 그라데이션 색상 stop 목록 생성
    fn build_gradient_stops(grad: &GradientFillInfo) -> String {
        let mut stops = String::new();
        for (i, &color) in grad.colors.iter().enumerate() {
            let offset = if i < grad.positions.len() {
                grad.positions[i] * 100.0
            } else {
                let n = grad.colors.len();
                if n <= 1 {
                    0.0
                } else {
                    i as f64 / (n - 1) as f64 * 100.0
                }
            };
            stops.push_str(&format!(
                "<stop offset=\"{:.1}%\" stop-color=\"{}\"/>\n",
                offset,
                color_to_svg(color),
            ));
        }
        stops
    }

    /// 그라데이션을 포함한 사각형 그리기 (렌더 트리 전용)
    fn draw_rect_with_gradient(
        &mut self,
        x: f64,
        y: f64,
        w: f64,
        h: f64,
        corner_radius: f64,
        style: &ShapeStyle,
        gradient: Option<&GradientFillInfo>,
    ) {
        let mut attrs = format!("x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\"", x, y, w, h);

        if corner_radius > 0.0 {
            attrs.push_str(&format!(
                " rx=\"{}\" ry=\"{}\"",
                corner_radius, corner_radius
            ));
        }

        attrs.push_str(&self.build_fill_attr(style, gradient, (x, y, w, h)));

        if let Some(stroke) = style.stroke_color {
            attrs.push_str(&format!(
                " stroke=\"{}\" stroke-width=\"{}\"",
                color_to_svg(stroke),
                style.stroke_width
            ));
            stroke_pattern::append_attrs(&mut attrs, style.stroke_dash, style.stroke_width);
        }

        if style.opacity < 1.0 {
            attrs.push_str(&format!(" opacity=\"{:.3}\"", style.opacity));
        }

        self.output.push_str(&format!("<rect {}/>\n", attrs));
    }

    /// 그라데이션을 포함한 타원 그리기 (렌더 트리 전용)
    fn draw_ellipse_with_gradient(
        &mut self,
        cx: f64,
        cy: f64,
        rx: f64,
        ry: f64,
        style: &ShapeStyle,
        gradient: Option<&GradientFillInfo>,
    ) {
        let mut attrs = format!("cx=\"{}\" cy=\"{}\" rx=\"{}\" ry=\"{}\"", cx, cy, rx, ry);

        attrs.push_str(&self.build_fill_attr(
            style,
            gradient,
            (cx - rx, cy - ry, rx * 2.0, ry * 2.0),
        ));

        if let Some(stroke) = style.stroke_color {
            attrs.push_str(&format!(
                " stroke=\"{}\" stroke-width=\"{}\"",
                color_to_svg(stroke),
                style.stroke_width
            ));
        }

        if style.opacity < 1.0 {
            attrs.push_str(&format!(" opacity=\"{:.3}\"", style.opacity));
        }

        self.output.push_str(&format!("<ellipse {}/>\n", attrs));
    }

    /// 그라데이션을 포함한 패스 그리기 (렌더 트리 전용)
    fn draw_path_with_gradient(
        &mut self,
        commands: &[PathCommand],
        style: &ShapeStyle,
        gradient: Option<&GradientFillInfo>,
    ) {
        let d = svg_path_data(commands);

        let mut attrs = format!("d=\"{}\"", d.trim());

        attrs.push_str(&self.build_fill_attr(style, gradient, path_bbox(commands)));

        if let Some(stroke) = style.stroke_color {
            attrs.push_str(&format!(
                " stroke=\"{}\" stroke-width=\"{}\"",
                color_to_svg(stroke),
                style.stroke_width
            ));
            stroke_pattern::append_attrs(&mut attrs, style.stroke_dash, style.stroke_width);
        }

        self.output.push_str(&format!("<path {}/>\n", attrs));
    }

    /// HWP 각도(도) → SVG linearGradient 좌표 (x1%, y1%, x2%, y2%) 변환
    fn angle_to_svg_coords(angle: i16) -> (f64, f64, f64, f64) {
        let a = ((angle % 360 + 360) % 360) as f64;
        match a as i32 {
            0 => (0.0, 0.0, 0.0, 100.0),
            45 => (0.0, 0.0, 100.0, 100.0),
            90 => (0.0, 0.0, 100.0, 0.0),
            135 => (0.0, 100.0, 100.0, 0.0),
            180 => (0.0, 100.0, 0.0, 0.0),
            225 => (100.0, 100.0, 0.0, 0.0),
            270 => (100.0, 0.0, 0.0, 0.0),
            315 => (100.0, 0.0, 0.0, 100.0),
            _ => {
                let rad = a.to_radians();
                let sin = rad.sin();
                let cos = rad.cos();
                let x1 = 50.0 - sin * 50.0;
                let y1 = 50.0 - cos * 50.0;
                let x2 = 50.0 + sin * 50.0;
                let y2 = 50.0 + cos * 50.0;
                (x1, y1, x2, y2)
            }
        }
    }

    /// 이중선/삼중선 렌더링: 원래 선에 수직 방향으로 평행선들을 그림
    fn draw_multi_line(
        &mut self,
        x1: f64,
        y1: f64,
        x2: f64,
        y2: f64,
        total_width: f64,
        color: &str,
        line_type: &super::LineRenderType,
    ) {
        let dx = x2 - x1;
        let dy = y2 - y1;
        let len = (dx * dx + dy * dy).sqrt();
        if len < 0.001 {
            return;
        }

        // 수직 방향 단위벡터 (선의 법선)
        let nx = -dy / len;
        let ny = dx / len;

        // (width_ratio, offset_ratio) — offset은 선 중심으로부터의 거리 비율
        let lines: Vec<(f64, f64)> = match line_type {
            super::LineRenderType::Double => {
                // 같은 굵기 이중선: 각 선 30%, 간격 40%
                vec![(0.30, -0.35), (0.30, 0.35)]
            }
            super::LineRenderType::ThickThinDouble => {
                // 굵은선(위)-얇은선(아래): 굵은선 40%, 얇은선 20%, 간격 40%
                vec![(0.4, -0.30), (0.2, 0.40)]
            }
            super::LineRenderType::ThinThickDouble => {
                // 얇은선(위)-굵은선(아래): 얇은선 20%, 굵은선 40%, 간격 40%
                vec![(0.2, -0.40), (0.4, 0.30)]
            }
            super::LineRenderType::ThinThickThinTriple => {
                // 얇은-굵은-얇은 삼중선: 15%, 30%, 15%, 간격 20%×2
                vec![(0.15, -0.425), (0.30, 0.0), (0.15, 0.425)]
            }
            _ => return,
        };

        for (width_ratio, offset_ratio) in &lines {
            let w = total_width * width_ratio;
            let off = total_width * offset_ratio;
            let ox = nx * off;
            let oy = ny * off;
            self.output.push_str(&format!(
                "<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"{}\"/>\n",
                x1 + ox, y1 + oy, x2 + ox, y2 + oy, color, w,
            ));
        }
    }

    /// PageBackground/BorderFill 이미지를 fill_mode에 따라 렌더링한다.
    fn render_page_background_image(&mut self, img: &PageBackgroundImage, bbox: &BoundingBox) {
        // PageBackground RealPic 워터마크 프리셋은 한컴의 색상 있는 배경 워터마크에 맞춰
        // 색감 보정을 PNG 픽셀에 bake한 뒤 반투명으로 합성한다.
        let preserve_color_watermark = img.is_real_picture_watermark_tone_preset();
        // 쪽 배경의 밝기·대비는 그 자체로 워터마크 표식이 아니다. HWP3/HWP5의
        // 일반 배경 그림도 색조 값을 쓸 수 있으며, 이를 legacy opacity로 합성하면
        // 기준 PDF보다 지나치게 희게 사라진다. 검증된 RealPic 워터마크 프리셋만
        // 별도 반투명 합성을 적용한다.
        let detected_mime = detect_image_mime_type(&img.data);
        // BMP/PCX → PNG 재인코딩 (브라우저 호환성과 PCX white transparency 정합)
        let (render_bytes, render_mime): (std::borrow::Cow<[u8]>, &str) =
            if preserve_color_watermark {
                match real_picture_watermark_bytes_to_hancom_tone_png_bytes(&img.data) {
                    Some(png) => (std::borrow::Cow::Owned(png), "image/png"),
                    None => (std::borrow::Cow::Borrowed(&img.data[..]), detected_mime),
                }
            } else if detected_mime == "image/bmp" {
                match bmp_bytes_to_png_bytes(&img.data) {
                    Some(png) => (std::borrow::Cow::Owned(png), "image/png"),
                    None => (std::borrow::Cow::Borrowed(&img.data[..]), detected_mime),
                }
            } else if detected_mime == "image/x-pcx" {
                match pcx_bytes_to_png_bytes(&img.data) {
                    Some(png) => (std::borrow::Cow::Owned(png), "image/png"),
                    None => (std::borrow::Cow::Borrowed(&img.data[..]), detected_mime),
                }
            } else if detected_mime == "image/tiff" {
                match tiff_bytes_to_png_bytes(&img.data) {
                    Some(png) => (std::borrow::Cow::Owned(png), "image/png"),
                    None => (std::borrow::Cow::Borrowed(&img.data[..]), detected_mime),
                }
            } else if detected_mime == "application/postscript" {
                match crate::renderer::image_resolver::eps_renderable_bytes(&img.data) {
                    Some((mime, bytes)) => (std::borrow::Cow::Owned(bytes), mime),
                    None => (std::borrow::Cow::Borrowed(&img.data[..]), detected_mime),
                }
            } else {
                (std::borrow::Cow::Borrowed(&img.data[..]), detected_mime)
            };
        let (brightness, contrast) = img.display_brightness_contrast();
        let adjusted = (!preserve_color_watermark)
            .then(|| {
                crate::renderer::image_resolver::adjusted_picture_bytes(
                    &render_bytes,
                    img.effect,
                    brightness,
                    contrast,
                )
            })
            .flatten();
        let adjustments_baked = adjusted.is_some();
        let render_bytes = adjusted.as_deref().unwrap_or(&render_bytes);
        let render_mime = if adjustments_baked {
            "image/png"
        } else {
            render_mime
        };
        let base64_data = base64::engine::general_purpose::STANDARD.encode(render_bytes);
        let data_uri = format!("data:{};base64,{}", render_mime, base64_data);

        let effect_filter_id = if preserve_color_watermark || adjustments_baked {
            None
        } else {
            self.ensure_image_effect_filter(img.effect)
        };
        if let Some(ref fid) = effect_filter_id {
            self.output
                .push_str(&format!("<g filter=\"url(#{})\">\n", fid));
        }
        let bc_filter_id = if preserve_color_watermark || adjustments_baked {
            None
        } else {
            let (brightness, contrast) = img.display_brightness_contrast();
            self.ensure_brightness_contrast_filter(brightness, contrast)
        };
        if let Some(ref fid) = bc_filter_id {
            self.output
                .push_str(&format!("<g filter=\"url(#{})\">\n", fid));
        }
        // 일반 RealPic 쪽 배경의 색조 조정은 불투명으로 유지한다. 기존 비-RealPic
        // 워터마크(GrayScale/Pattern 등)는 legacy opacity 계약을 계속 따른다.
        let needs_watermark_opacity = preserve_color_watermark
            || (!matches!(img.effect, crate::model::image::ImageEffect::RealPic)
                && img.is_watermark());
        if needs_watermark_opacity {
            let opacity = if preserve_color_watermark {
                REAL_PICTURE_WATERMARK_PAGE_OPACITY
            } else {
                LEGACY_IMAGE_WATERMARK_OPACITY
            };
            self.output
                .push_str(&format!("<g opacity=\"{}\">\n", opacity));
        }

        match img.fill_mode {
            // Total(HWPX "TOTAL")은 바이너리 채우기 유형 5(크기에 맞추어)의 HWPX
            // 표기로, FitToSize 와 같은 의미다 — 영역 전체로 늘려 채운다.
            ImageFillMode::FitToSize | ImageFillMode::Total | ImageFillMode::None => {
                self.output.push_str(&format!(
                    "<image x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" preserveAspectRatio=\"none\" href=\"{}\"/>\n",
                    bbox.x, bbox.y, bbox.width, bbox.height, data_uri,
                ));
            }
            // 쪽 배경 None은 기존 늘려 채우기 계약을 유지한다.
            ImageFillMode::Zoom => {
                // [#6310] 칸/영역에 맞춰 종횡비를 지키며 축소(contain). TILE 원본 픽셀
                // 배치가 아니다.
                self.output.push_str(&format!(
                    "<image x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" preserveAspectRatio=\"xMidYMid meet\" href=\"{}\"/>\n",
                    bbox.x, bbox.y, bbox.width, bbox.height, data_uri,
                ));
            }
            ImageFillMode::TileAll => {
                self.render_tiled_image(&render_bytes, &data_uri, bbox, true, true, None);
            }
            ImageFillMode::TileHorzTop | ImageFillMode::TileHorzBottom => {
                self.render_tiled_image(&render_bytes, &data_uri, bbox, true, false, None);
            }
            ImageFillMode::TileVertLeft | ImageFillMode::TileVertRight => {
                self.render_tiled_image(&render_bytes, &data_uri, bbox, false, true, None);
            }
            _ => {
                self.render_positioned_image(&render_bytes, &data_uri, bbox, img.fill_mode, None);
            }
        }

        if needs_watermark_opacity {
            self.output.push_str("</g>\n");
        }
        if bc_filter_id.is_some() {
            self.output.push_str("</g>\n");
        }
        if effect_filter_id.is_some() {
            self.output.push_str("</g>\n");
        }
    }

    /// 이미지 노드를 fill_mode에 따라 렌더링한다.
    /// 한글 편집 화면의 "그림 없음" 표시 — 개체 영역 점선 테두리 + 중앙의 작은
    /// 그림-없음 아이콘(사선 그은 그림 픽토그램).
    ///
    /// 기하·색은 `web_canvas.rs::render_placeholder` 와 같은 값을 쓴다 — 같은 표시를
    /// 두 백엔드가 다른 모양으로 그리면 studio 화면과 SVG 내보내기가 갈라진다.
    /// 인쇄 등가 profile 에서는 호출부(`show_missing_picture_placeholder`)가 막는다.
    fn draw_missing_picture_placeholder(&mut self, bbox: &super::render_tree::BoundingBox) {
        self.output.push_str(&format!(
            "<rect x=\"{:.2}\" y=\"{:.2}\" width=\"{:.2}\" height=\"{:.2}\" fill=\"none\" stroke=\"#999999\" stroke-width=\"1\" stroke-dasharray=\"2 2\"/>
",
            bbox.x, bbox.y, bbox.width, bbox.height,
        ));
        let icon = (bbox.width.min(bbox.height) * 0.4).clamp(14.0, 36.0);
        let ix = bbox.x + (bbox.width - icon) / 2.0;
        let iy = bbox.y + (bbox.height - icon) / 2.0;
        // 아이콘 판 + 산 두 개 + 해 + 사선(그림 없음)
        self.output.push_str(&format!(
            "<rect x=\"{:.2}\" y=\"{:.2}\" width=\"{:.2}\" height=\"{:.2}\" fill=\"#ffffff\" stroke=\"#888888\" stroke-width=\"1\"/>
",
            ix,
            iy,
            icon,
            icon * 0.75,
        ));
        self.output.push_str(&format!(
            "<polyline points=\"{:.2},{:.2} {:.2},{:.2} {:.2},{:.2} {:.2},{:.2} {:.2},{:.2}\" fill=\"none\" stroke=\"#888888\" stroke-width=\"1\"/>
",
            ix + icon * 0.08,
            iy + icon * 0.62,
            ix + icon * 0.32,
            iy + icon * 0.30,
            ix + icon * 0.52,
            iy + icon * 0.62,
            ix + icon * 0.68,
            iy + icon * 0.42,
            ix + icon * 0.92,
            iy + icon * 0.62,
        ));
        self.output.push_str(&format!(
            "<circle cx=\"{:.2}\" cy=\"{:.2}\" r=\"{:.2}\" fill=\"none\" stroke=\"#888888\" stroke-width=\"1\"/>
",
            ix + icon * 0.72,
            iy + icon * 0.20,
            icon * 0.07,
        ));
        self.output.push_str(&format!(
            "<line x1=\"{:.2}\" y1=\"{:.2}\" x2=\"{:.2}\" y2=\"{:.2}\" stroke=\"#cc4444\" stroke-width=\"1.5\"/>
",
            ix,
            iy + icon * 0.75,
            ix + icon,
            iy,
        ));
    }

    fn render_image_node(&mut self, img: &ImageNode, bbox: &super::render_tree::BoundingBox) {
        if let Some(path) = super::pdf_stroke::project(img, *bbox) {
            self.draw_path_with_gradient(&path.commands, &path.style, None);
            return;
        }
        let interpolation = img.data.as_deref().and_then(|data| {
            let (width, height) = super::image_resolver::png_sampling::dimensions(data)?;
            let source = img.crop.map_or((width, height), |crop| {
                let (_, _, w, h) =
                    compute_image_crop_src(crop, img.original_size_hu, width, height);
                (w, h)
            });
            let frame = img.transformed_paint_bbox(bbox);
            // SVG's intrinsic page uses the renderer's 96-DPI coordinate system.
            super::image_resolver::png_sampling::magnification(
                super::image_resolver::png_sampling::interpolation(data),
                source,
                (frame.width, frame.height),
            )
        });
        if let Some(interpolate) = interpolation {
            let rendering = if interpolate { "auto" } else { "pixelated" };
            let _ = write!(self.output, "<g style=\"image-rendering:{rendering}\">");
        }
        self.render_image_node_with_sampling(img, bbox);
        if interpolation.is_some() {
            self.output.push_str("</g>");
        }
    }

    fn render_image_node_with_sampling(
        &mut self,
        img: &ImageNode,
        bbox: &super::render_tree::BoundingBox,
    ) {
        // 저장 자르기 선택이 비었으면 프레임만 점유하며 원본을 그리지 않는다.
        if img.crop.is_some_and(|(l, t, r, b)| r <= l || b <= t) {
            return;
        }
        // 공통 인쇄 계약: 그림 미지정과 미해결 연결 그림의 편집용 대체 표시는 생략.
        if img.is_nonprinting_picture_placeholder() && !self.show_missing_picture_placeholder {
            return;
        }
        // [Task #741] 빈 binary 데이터 (외부 file path 그림 등) 도 placeholder 처리.
        // 한컴 한글 2024 viewer 정합 — 외부 file 못 찾는 경우 점선 사각형 + 깨진 image 아이콘.
        let data = match img.data {
            Some(ref d) if !d.is_empty() => d,
            _ => {
                // 이미지 데이터 부재 (None 또는 빈 vec) — placeholder 표시
                self.output.push_str(&format!(
                    "<rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" fill=\"#f0f0f0\" stroke=\"#999999\" stroke-dasharray=\"4\"/>\n",
                    bbox.x, bbox.y, bbox.width, bbox.height,
                ));
                // 외부 file path 그림: file path 표시 (가독성)
                if let Some(ref path) = img.external_path {
                    let cx = bbox.x + bbox.width / 2.0;
                    let cy = bbox.y + bbox.height / 2.0;
                    let escaped = escape_xml(crate::model::image::external_picture_basename(path));
                    self.output.push_str(&format!(
                        "<text x=\"{}\" y=\"{}\" text-anchor=\"middle\" fill=\"#666666\" font-size=\"10\">[외부: {}]</text>\n",
                        cx, cy, escaped,
                    ));
                }
                return;
            }
        };

        // RealPic 워터마크 프리셋은 한컴의 색상 있는 배경 워터마크에 맞춰
        // 색감을 살린 뒤 반투명으로 합성한다. 표/셀 배경 fill은 쪽 배경보다
        // 더 투명하게 합성되는 샘플이 있어 opacity만 별도 프로파일을 사용한다.
        let preserve_color_watermark = img.is_real_picture_watermark_tone_preset();
        // [Issue #1156] 워터마크 판정 = 밝기·대비가 둘 다 0 이 아님 (effect 무관).
        let is_watermark_image = crate::renderer::image_resolver::is_watermark_image(img);
        let mime_type = detect_image_mime_type(data);

        // WMF → SVG 변환 (브라우저는 WMF를 렌더링할 수 없으므로 SVG로 변환)
        // BMP → PNG 변환 (브라우저는 SVG <image> 내부의 data:image/bmp 미지원)
        // PCX → PNG 변환 (브라우저는 PCX 포맷을 native 렌더링하지 못함, Task #514)
        let (render_data, render_mime, baked_watermark): (std::borrow::Cow<[u8]>, &str, bool) =
            if preserve_color_watermark {
                match real_picture_watermark_fill_bytes_to_hancom_tone_png_bytes(data) {
                    Some(png_bytes) => (std::borrow::Cow::Owned(png_bytes), "image/png", true),
                    None => (std::borrow::Cow::Borrowed(data), mime_type, false),
                }
            } else if mime_type == "image/x-wmf" {
                match convert_wmf_to_svg(data) {
                    Some(svg_bytes) => (std::borrow::Cow::Owned(svg_bytes), "image/svg+xml", false),
                    None => (std::borrow::Cow::Borrowed(data), mime_type, false),
                }
            } else if mime_type == "image/x-emf" {
                match crate::emf::convert_to_standalone_svg(data) {
                    Some(svg_bytes) => (std::borrow::Cow::Owned(svg_bytes), "image/svg+xml", false),
                    None => (std::borrow::Cow::Borrowed(data), mime_type, false),
                }
            } else if mime_type == "image/bmp" {
                match bmp_bytes_to_png_bytes(data) {
                    Some(png_bytes) => (std::borrow::Cow::Owned(png_bytes), "image/png", false),
                    None => (std::borrow::Cow::Borrowed(data), mime_type, false),
                }
            } else if mime_type == "image/x-pcx" {
                match pcx_bytes_to_png_bytes(data) {
                    Some(png_bytes) => (std::borrow::Cow::Owned(png_bytes), "image/png", false),
                    None => (std::borrow::Cow::Borrowed(data), mime_type, false),
                }
            } else if mime_type == "image/tiff" {
                match tiff_bytes_to_png_bytes(data) {
                    Some(png_bytes) => (std::borrow::Cow::Owned(png_bytes), "image/png", false),
                    None => (std::borrow::Cow::Borrowed(data), mime_type, false),
                }
            } else if mime_type == "application/postscript" {
                match crate::renderer::image_resolver::eps_renderable_bytes(data) {
                    Some((mime, bytes)) => (std::borrow::Cow::Owned(bytes), mime, false),
                    None => (std::borrow::Cow::Borrowed(data), mime_type, false),
                }
            } else if mime_type == "image/jpeg"
                && crate::renderer::image_resolver::jpeg_is_four_component(data)
            {
                // [#6310] 4성분(CMYK/YCCK) JPEG 은 PDF `/DeviceRGB` 선언과 성분 수가
                // 어긋나 행 보폭이 깨진다 — PNG(RGB)로 정규화해 싣는다.
                match crate::renderer::image_resolver::cmyk_jpeg_bytes_to_png_bytes(data) {
                    Some(png_bytes) => (std::borrow::Cow::Owned(png_bytes), "image/png", false),
                    None => (std::borrow::Cow::Borrowed(data), mime_type, false),
                }
            } else if is_watermark_image && mime_type == "image/jpeg" {
                match watermark_jpeg_bytes_to_hancom_baked_png_bytes(data) {
                    Some(png_bytes) => (std::borrow::Cow::Owned(png_bytes), "image/png", true),
                    None => (std::borrow::Cow::Borrowed(data), mime_type, false),
                }
            } else {
                (std::borrow::Cow::Borrowed(data), mime_type, false)
            };

        let adjusted = (!(baked_watermark || preserve_color_watermark))
            .then(|| {
                crate::renderer::image_resolver::adjusted_picture_bytes(
                    &render_data,
                    img.effect,
                    img.brightness,
                    img.contrast,
                )
            })
            .flatten();
        let adjustments_baked = adjusted.is_some();
        let render_data = adjusted.map_or(render_data, std::borrow::Cow::Owned);
        let render_mime = if adjustments_baked {
            "image/png"
        } else {
            render_mime
        };
        // 일반 raster 색조는 공통 helper가 확정한 픽셀을 사용한다.
        let effect_filter_id = if baked_watermark || preserve_color_watermark || adjustments_baked {
            None
        } else {
            self.ensure_image_effect_filter(img.effect)
        };
        if let Some(ref fid) = effect_filter_id {
            self.output
                .push_str(&format!("<g filter=\"url(#{})\">\n", fid));
        }
        let object_opacity = img.opacity.clamp(0.0, 1.0);
        if object_opacity < 1.0 {
            self.output
                .push_str(&format!("<g opacity=\"{:.3}\">\n", object_opacity));
        }
        // 밝기/대비 → SVG 필터 래핑
        // [Issue #677] 한컴 워터마크 효과 (effect != RealPic 이고 brightness/contrast 가
        // 비-zero) 는 저장값을 그대로 brightness/contrast 필터로 적용한다. JPEG 워터마크는
        // #976의 baked PNG 선보정이 성공하면 런타임 필터를 생략하고, RealPic 색상
        // 워터마크는 #975의 baked PNG 톤 보정으로 처리한다.
        let bc_filter_id = if baked_watermark || preserve_color_watermark || adjustments_baked {
            None
        } else {
            self.ensure_brightness_contrast_filter(img.brightness, img.contrast)
        };
        if let Some(ref fid) = bc_filter_id {
            self.output
                .push_str(&format!("<g filter=\"url(#{})\">\n", fid));
        }
        // 워터마크 반투명 영역. JPEG baked 워터마크는 이미 한컴 톤으로 픽셀화되어
        // 있으므로 추가 opacity를 적용하지 않는다.
        let needs_watermark_opacity =
            preserve_color_watermark || (is_watermark_image && !baked_watermark);
        if needs_watermark_opacity {
            let opacity = if preserve_color_watermark {
                REAL_PICTURE_WATERMARK_FILL_OPACITY
            } else {
                LEGACY_IMAGE_WATERMARK_OPACITY
            };
            self.output
                .push_str(&format!("<g opacity=\"{}\">\n", opacity));
        }

        let base64_data = base64::engine::general_purpose::STANDARD.encode(&*render_data);
        let data_uri = format!("data:{};base64,{}", render_mime, base64_data);

        let fill_mode = img.fill_mode.unwrap_or(ImageFillMode::FitToSize);
        let image_size = parse_image_dimensions(&render_data)
            .map(|(w, h)| (f64::from(w), f64::from(h)))
            .or_else(|| {
                (render_mime == "image/svg+xml")
                    .then(|| super::metafile_geometry::svg_viewport(&render_data))
                    .flatten()
            });
        let crop_reference = if mime_type == "image/x-wmf" {
            super::metafile_geometry::wmf_crop_reference(img.original_size_hu)
        } else {
            img.original_size_hu
        };

        match fill_mode {
            // [#7235] 채우기 유형 15(NONE): 한컴은 원래 픽셀 크기로 두지 않고 종횡비를
            // 지켜 칸에 맞춘다(Zoom 과 같은 배치).
            ImageFillMode::Zoom | ImageFillMode::None => {
                // contain 비율은 최종적으로 보이는 crop 영역으로 계산한다.
                // 맞춘 viewport 자체를 clip하여 잘려 나간 픽셀이 letterbox에 새지 않는다.
                if let (Some(crop), Some((iw, ih))) = (img.crop, image_size) {
                    let (sx, sy, sw, sh) = compute_image_crop_src(crop, crop_reference, iw, ih);
                    let scale = (bbox.width / sw).min(bbox.height / sh);
                    let (w, h) = (sw * scale, sh * scale);
                    self.output.push_str(&format!(
                        "<svg x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" viewBox=\"{} {} {} {}\" preserveAspectRatio=\"none\" overflow=\"hidden\"><image width=\"{}\" height=\"{}\" preserveAspectRatio=\"none\" href=\"{}\"/></svg>\n",
                        bbox.x + (bbox.width - w) / 2.0, bbox.y + (bbox.height - h) / 2.0,
                        w, h, sx, sy, sw, sh, iw, ih, data_uri,
                    ));
                } else {
                    self.output.push_str(&format!(
                    "<image x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" preserveAspectRatio=\"xMidYMid meet\" href=\"{}\"/>\n",
                    bbox.x, bbox.y, bbox.width, bbox.height, data_uri,
                ));
                }
            }
            ImageFillMode::FitToSize | ImageFillMode::Total => {
                // 그림 자르기: crop이 있으면 원본 이미지의 일부만 표시
                if let Some((cl, ct, cr, cb)) = img.crop {
                    if let Some((img_w, img_h)) = image_size {
                        let (src_x, src_y, src_w, src_h) =
                            compute_image_crop_src((cl, ct, cr, cb), crop_reference, img_w, img_h);
                        // 전체 이미지 대비 잘림이 있는지 확인
                        let is_cropped =
                            !image_source_is_full((src_x, src_y, src_w, src_h), img_w, img_h);
                        if is_cropped {
                            // SVG: 중첩 svg + viewBox로 crop 영역만 표시
                            self.output.push_str(&format!(
                                "<svg x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" viewBox=\"{} {} {} {}\" preserveAspectRatio=\"none\">\
                                <image width=\"{}\" height=\"{}\" preserveAspectRatio=\"none\" href=\"{}\"/></svg>\n",
                                bbox.x, bbox.y, bbox.width, bbox.height,
                                src_x, src_y, src_w, src_h,
                                img_w, img_h, data_uri,
                            ));
                        } else {
                            self.output.push_str(&format!(
                                "<image x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" preserveAspectRatio=\"none\" href=\"{}\"/>\n",
                                bbox.x, bbox.y, bbox.width, bbox.height, data_uri,
                            ));
                        }
                    } else {
                        // 이미지 크기 파싱 실패 → crop 무시
                        self.output.push_str(&format!(
                            "<image x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" preserveAspectRatio=\"none\" href=\"{}\"/>\n",
                            bbox.x, bbox.y, bbox.width, bbox.height, data_uri,
                        ));
                    }
                } else {
                    // crop 없음: 기존 동작
                    self.output.push_str(&format!(
                        "<image x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" preserveAspectRatio=\"none\" href=\"{}\"/>\n",
                        bbox.x, bbox.y, bbox.width, bbox.height, data_uri,
                    ));
                }
            }
            ImageFillMode::TileAll => {
                // 바둑판식으로-모두: 원래 크기로 전체 타일링
                self.render_tiled_image(
                    &render_data,
                    &data_uri,
                    bbox,
                    true,
                    true,
                    img.original_size,
                );
            }
            ImageFillMode::TileHorzTop | ImageFillMode::TileHorzBottom => {
                // 바둑판식으로-가로: 가로 방향만 타일링 (위 또는 아래 기준)
                self.render_tiled_image(
                    &render_data,
                    &data_uri,
                    bbox,
                    true,
                    false,
                    img.original_size,
                );
            }
            ImageFillMode::TileVertLeft | ImageFillMode::TileVertRight => {
                // 바둑판식으로-세로: 세로 방향만 타일링 (왼쪽 또는 오른쪽 기준)
                self.render_tiled_image(
                    &render_data,
                    &data_uri,
                    bbox,
                    false,
                    true,
                    img.original_size,
                );
            }
            _ => {
                // 배치 모드: 원래 크기대로 지정 위치에 배치
                self.render_positioned_image(
                    &render_data,
                    &data_uri,
                    bbox,
                    fill_mode,
                    img.original_size,
                );
            }
        }

        if needs_watermark_opacity {
            self.output.push_str("</g>\n");
        }
        if bc_filter_id.is_some() {
            self.output.push_str("</g>\n");
        }
        if object_opacity < 1.0 {
            self.output.push_str("</g>\n");
        }
        if effect_filter_id.is_some() {
            self.output.push_str("</g>\n");
        }
    }

    /// 그림 효과(ImageEffect)에 해당하는 SVG 필터를 defs에 보장하고 ID를 반환한다.
    /// RealPic(기본)은 필터가 필요 없으므로 None 반환.
    fn ensure_image_effect_filter(
        &mut self,
        effect: crate::model::image::ImageEffect,
    ) -> Option<String> {
        use crate::model::image::ImageEffect;
        let (id, def) = match effect {
            ImageEffect::RealPic => return None,
            ImageEffect::GrayScale => (
                "rhwp-img-grayscale",
                "<filter id=\"rhwp-img-grayscale\"><feColorMatrix type=\"matrix\" values=\"\
                    0.299 0.587 0.114 0 0 \
                    0.299 0.587 0.114 0 0 \
                    0.299 0.587 0.114 0 0 \
                    0 0 0 1 0\"/></filter>\n",
            ),
            ImageEffect::BlackWhite => (
                "rhwp-img-blackwhite",
                "<filter id=\"rhwp-img-blackwhite\">\
                    <feColorMatrix type=\"matrix\" values=\"\
                        0.299 0.587 0.114 0 0 \
                        0.299 0.587 0.114 0 0 \
                        0.299 0.587 0.114 0 0 \
                        0 0 0 1 0\"/>\
                    <feComponentTransfer>\
                        <feFuncR type=\"discrete\" tableValues=\"0 1\"/>\
                        <feFuncG type=\"discrete\" tableValues=\"0 1\"/>\
                        <feFuncB type=\"discrete\" tableValues=\"0 1\"/>\
                    </feComponentTransfer>\
                </filter>\n",
            ),
            // Pattern8x8은 SVG 필터로 표현하기 어려워 그레이스케일로 폴백
            ImageEffect::Pattern8x8 => (
                "rhwp-img-grayscale",
                "<filter id=\"rhwp-img-grayscale\"><feColorMatrix type=\"matrix\" values=\"\
                    0.299 0.587 0.114 0 0 \
                    0.299 0.587 0.114 0 0 \
                    0.299 0.587 0.114 0 0 \
                    0 0 0 1 0\"/></filter>\n",
            ),
        };
        if self.defs_ids.insert(id.to_string()) {
            self.defs.push(def.to_string());
        }
        Some(id.to_string())
    }

    /// 밝기/대비 조정용 SVG 필터를 defs에 보장하고 ID를 반환한다.
    /// 둘 다 0이면 필터 불필요 → None 반환.
    /// HWP 스펙은 brightness/contrast 를 -100..=100 으로 정의하므로 손상된 입력에 대비해 clamp 한다.
    fn ensure_brightness_contrast_filter(
        &mut self,
        brightness: i8,
        contrast: i8,
    ) -> Option<String> {
        let brightness = brightness.clamp(-100, 100);
        let contrast = contrast.clamp(-100, 100);
        if brightness == 0 && contrast == 0 {
            return None;
        }

        let id = format!("rhwp-img-bc-b{}c{}", brightness, contrast);

        // 밝기: intercept 오프셋으로 구현 (slope=1, intercept=brightness/100)
        // 대비: slope 조정으로 구현 (slope=(100+contrast)/100, intercept=0.5-0.5*slope)
        // 둘을 합성: slope=contrast_slope, intercept=contrast_intercept + brightness_offset
        let b = brightness as f64 / 100.0;
        let slope = (100.0 + contrast as f64) / 100.0;
        let intercept = (0.5 - 0.5 * slope) + b;

        let def = format!(
            "<filter id=\"{id}\">\
                <feComponentTransfer>\
                    <feFuncR type=\"linear\" slope=\"{slope:.4}\" intercept=\"{intercept:.4}\"/>\
                    <feFuncG type=\"linear\" slope=\"{slope:.4}\" intercept=\"{intercept:.4}\"/>\
                    <feFuncB type=\"linear\" slope=\"{slope:.4}\" intercept=\"{intercept:.4}\"/>\
                </feComponentTransfer>\
            </filter>\n"
        );
        if self.defs_ids.insert(id.clone()) {
            self.defs.push(def);
        }
        Some(id)
    }

    /// 이미지를 원래 크기로 지정 위치에 배치 (배치 모드)
    fn render_positioned_image(
        &mut self,
        data: &[u8],
        data_uri: &str,
        bbox: &super::render_tree::BoundingBox,
        fill_mode: ImageFillMode,
        original_size: Option<(f64, f64)>,
    ) {
        // 원본 크기: HWP shape_attr 기반(우선) 또는 이미지 픽셀 크기(폴백)
        let (img_width, img_height) = if let Some((ow, oh)) = original_size {
            (ow, oh)
        } else {
            match parse_image_dimensions(data) {
                Some((w, h)) => (w as f64, h as f64),
                None => {
                    // 크기 파싱 실패 시 meet으로 폴백
                    let par = match fill_mode {
                        ImageFillMode::Center => "xMidYMid meet",
                        ImageFillMode::CenterTop => "xMidYMin meet",
                        ImageFillMode::CenterBottom => "xMidYMax meet",
                        ImageFillMode::LeftCenter => "xMinYMid meet",
                        ImageFillMode::LeftTop => "xMinYMin meet",
                        ImageFillMode::LeftBottom => "xMinYMax meet",
                        ImageFillMode::RightCenter => "xMaxYMid meet",
                        ImageFillMode::RightTop => "xMaxYMin meet",
                        ImageFillMode::RightBottom => "xMaxYMax meet",
                        _ => "xMidYMid meet",
                    };
                    self.output.push_str(&format!(
                        "<image x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" preserveAspectRatio=\"{}\" href=\"{}\"/>\n",
                        bbox.x, bbox.y, bbox.width, bbox.height, par, data_uri,
                    ));
                    return;
                }
            }
        };

        // 배치 위치 계산
        let (ix, iy) = match fill_mode {
            ImageFillMode::LeftTop => (bbox.x, bbox.y),
            ImageFillMode::CenterTop => (bbox.x + (bbox.width - img_width) / 2.0, bbox.y),
            ImageFillMode::RightTop => (bbox.x + bbox.width - img_width, bbox.y),
            ImageFillMode::LeftCenter => (bbox.x, bbox.y + (bbox.height - img_height) / 2.0),
            ImageFillMode::Center => (
                bbox.x + (bbox.width - img_width) / 2.0,
                bbox.y + (bbox.height - img_height) / 2.0,
            ),
            ImageFillMode::RightCenter => (
                bbox.x + bbox.width - img_width,
                bbox.y + (bbox.height - img_height) / 2.0,
            ),
            ImageFillMode::LeftBottom => (bbox.x, bbox.y + bbox.height - img_height),
            ImageFillMode::CenterBottom => (
                bbox.x + (bbox.width - img_width) / 2.0,
                bbox.y + bbox.height - img_height,
            ),
            ImageFillMode::RightBottom => (
                bbox.x + bbox.width - img_width,
                bbox.y + bbox.height - img_height,
            ),
            _ => (bbox.x, bbox.y),
        };

        // 도형 영역으로 클리핑
        let clip_id = format!("fill-clip-{}", self.next_clip_id());
        self.defs.push(format!(
            "<clipPath id=\"{}\"><rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\"/></clipPath>\n",
            clip_id, bbox.x, bbox.y, bbox.width, bbox.height,
        ));
        self.output.push_str(&format!(
            "<g clip-path=\"url(#{})\"><image x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" preserveAspectRatio=\"none\" href=\"{}\"/></g>\n",
            clip_id, ix, iy, img_width, img_height, data_uri,
        ));
    }

    /// 이미지를 타일링 모드로 렌더링
    fn render_tiled_image(
        &mut self,
        data: &[u8],
        data_uri: &str,
        bbox: &super::render_tree::BoundingBox,
        tile_h: bool,
        tile_v: bool,
        original_size: Option<(f64, f64)>,
    ) {
        // 원본 크기: HWP shape_attr 기반(우선) 또는 이미지 픽셀 크기(폴백)
        let (img_width, img_height) = if let Some((ow, oh)) = original_size {
            (ow, oh)
        } else {
            match parse_image_dimensions(data) {
                Some((w, h)) => (w as f64, h as f64),
                None => {
                    // 크기 파싱 실패 시 전체 채우기로 폴백
                    self.output.push_str(&format!(
                        "<image x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" preserveAspectRatio=\"none\" href=\"{}\"/>\n",
                        bbox.x, bbox.y, bbox.width, bbox.height, data_uri,
                    ));
                    return;
                }
            }
        };

        let pat_id = format!("tile-pat-{}", self.next_clip_id());
        let pat_w = if tile_h { img_width } else { bbox.width };
        let pat_h = if tile_v { img_height } else { bbox.height };

        self.defs.push(format!(
            "<pattern id=\"{}\" x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" patternUnits=\"userSpaceOnUse\">\
             <image width=\"{}\" height=\"{}\" preserveAspectRatio=\"none\" href=\"{}\"/>\
             </pattern>\n",
            pat_id, bbox.x, bbox.y, pat_w, pat_h,
            img_width, img_height, data_uri,
        ));
        self.output.push_str(&format!(
            "<rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" fill=\"url(#{})\"/>\n",
            bbox.x, bbox.y, bbox.width, bbox.height, pat_id,
        ));
    }

    /// 고유 클립/패턴 ID 생성
    fn next_clip_id(&mut self) -> u32 {
        self.clip_counter += 1;
        self.clip_counter
    }

    /// 글자겹침(CharOverlap) 렌더링
    ///
    /// 각 문자를 테두리 도형(원/사각형) 안에 중앙 배치하여 렌더링한다.
    /// border_type: 0=없음, 1=원, 2=반전원, 3=사각형, 4=반전사각형
    /// 반전: 도형 채움(검정) + 흰 글자, 일반: 도형 테두리(검정) + 검정 글자
    ///
    /// 다자리 PUA 숫자 (2~3자리): 모든 문자를 하나의 원/사각형 안에 합쳐서 렌더링.
    /// border_type=0이고 PUA 겹침 숫자이면 원형(circle)으로 자동 렌더링.
    /// 한컴 방식: 장평 조절로 좁은 숫자를 하나의 도형 안에 배치.
    fn draw_char_overlap(
        &mut self,
        text: &str,
        style: &TextStyle,
        overlap: &CharOverlapInfo,
        bbox_x: f64,
        bbox_y: f64,
        bbox_w: f64,
        bbox_h: f64,
    ) {
        if overlap.empty_ink {
            return;
        }
        let font_size = style.effective_font_size();
        let chars: Vec<char> = text.chars().collect();
        if chars.is_empty() {
            return;
        }

        // PUA 다자리 숫자 디코딩 시도
        if let Some(number_str) = decode_pua_overlap_number(&chars) {
            let mut overlap = overlap.clone();
            if overlap.border_type == 0 {
                overlap.border_type = pua_overlap_number_border(&chars);
            }
            self.draw_char_overlap_combined(
                style,
                &overlap,
                &number_str,
                bbox_x,
                bbox_y,
                bbox_w,
                bbox_h,
            );
            return;
        }

        // 일반 CharOverlap 처리. 디코딩되지 않는 다중 PUA 조합도 한 컨트롤 안에서
        // 같은 중심에 겹쳐 그린다. table-vpos-01의 10/11/12 마커는
        // U+F02BA + U+F02C3/C4/C5 조합으로 저장되며, 나란히 그리면 숫자가
        // 사각형 밖으로 밀린다.
        let box_size = font_size;
        let boxed_pua = boxed_pua_char_overlap_semantics(&chars, overlap.border_type);
        let effective_border = boxed_pua
            .map(|(_, border_type)| border_type)
            .unwrap_or(overlap.border_type);

        let is_reversed = effective_border == 2 || effective_border == 4;
        let is_circle = effective_border == 1 || effective_border == 2;
        let is_rect = effective_border == 3 || effective_border == 4;

        // charSz 는 "테두리 내부" 글자 비율이므로 테두리를 안 그리면 적용하지 않는다 (#4085).
        let size_ratio = char_overlap_size_ratio(effective_border, overlap.inner_char_size);
        let inner_font_size = font_size * size_ratio;

        // 한컴은 동그라미 테두리도 글자색과 동일 색상으로 그림 (raw PDF 0 0 1 RG/rg).
        // reversed(반전)는 기존대로 검정 채움 + 흰 글자.
        let glyph_color = color_to_svg(style.color);
        let fill_color = if is_reversed { "#000000" } else { "none" };
        let stroke_color: &str = if is_reversed { "#000000" } else { &glyph_color };
        let text_color: &str = if is_reversed { "#FFFFFF" } else { &glyph_color };

        let font_family_str = if style.font_family.is_empty() {
            "sans-serif".to_string()
        } else {
            // [#3314] 요청 face → base family → generic 체인.
            // [#3772] bold 는 ExtraLight 를 빼서 PDF 굵기를 지킨다.
            super::render_font_family_chain_for_weight(&style.font_family, style.is_visually_bold())
        };
        let mut font_attrs = format!(
            "font-family=\"{}\" font-size=\"{:.2}\"",
            escape_xml(&font_family_str),
            inner_font_size
        );
        if let Some(w) = faux_bold_stroke_width(style, inner_font_size) {
            font_attrs.push_str(&faux_bold_stroke_attr(w, text_color));
        } else if style.is_visually_bold() {
            font_attrs.push_str(" font-weight=\"bold\"");
        } else if style.is_medium_weight() {
            font_attrs.push_str(" font-weight=\"500\"");
        }
        if style.italic {
            font_attrs.push_str(&format!(
                " font-style=\"{}\"",
                super::text_italic::CSS_STYLE
            ));
        }

        if chars.len() > 1 {
            let cx = bbox_x + bbox_w / 2.0;
            let cy = bbox_y + bbox_h / 2.0;

            if is_circle {
                let ry = box_size / 2.0;
                let rx = ry * 0.85;
                self.output.push_str(&format!(
                    "<ellipse cx=\"{:.2}\" cy=\"{:.2}\" rx=\"{:.2}\" ry=\"{:.2}\" fill=\"{}\" stroke=\"{}\" stroke-width=\"0.8\"/>\n",
                    cx, cy, rx, ry, fill_color, stroke_color,
                ));
            } else if is_rect {
                let rx = cx - box_size / 2.0;
                let ry = cy - box_size / 2.0;
                self.output.push_str(&format!(
                    "<rect x=\"{:.2}\" y=\"{:.2}\" width=\"{:.2}\" height=\"{:.2}\" fill=\"{}\" stroke=\"{}\" stroke-width=\"0.8\"/>\n",
                    rx, ry, box_size, box_size, fill_color, stroke_color,
                ));
            }

            for ch in chars.iter() {
                let display_str = char_overlap_display_text(*ch, is_circle || is_rect);
                self.output.push_str(&format!(
                    "<text x=\"{:.2}\" y=\"{:.2}\" fill=\"{}\" {} text-anchor=\"middle\" dominant-baseline=\"central\">{}</text>\n",
                    cx, cy, text_color, font_attrs, escape_xml(&display_str),
                ));
            }
            return;
        }

        for (i, ch) in chars.iter().enumerate() {
            let display_str = if let Some((number, _)) = boxed_pua {
                number.to_string()
            } else {
                char_overlap_display_text(*ch, is_circle || is_rect)
            };

            let cx = bbox_x + i as f64 * box_size + box_size / 2.0;
            let cy = bbox_y + bbox_h / 2.0;

            if is_circle {
                // 한컴 글자겹침은 세로로 긴 타원 (h/w ≈ 1.18). 한글 글리프 비율과 정합.
                let ry = box_size / 2.0;
                let rx = ry * 0.85;
                self.output.push_str(&format!(
                    "<ellipse cx=\"{:.2}\" cy=\"{:.2}\" rx=\"{:.2}\" ry=\"{:.2}\" fill=\"{}\" stroke=\"{}\" stroke-width=\"0.8\"/>\n",
                    cx, cy, rx, ry, fill_color, stroke_color,
                ));
            } else if is_rect {
                let rx = cx - box_size / 2.0;
                let ry = cy - box_size / 2.0;
                self.output.push_str(&format!(
                    "<rect x=\"{:.2}\" y=\"{:.2}\" width=\"{:.2}\" height=\"{:.2}\" fill=\"{}\" stroke=\"{}\" stroke-width=\"0.8\"/>\n",
                    rx, ry, box_size, box_size, fill_color, stroke_color,
                ));
            }

            self.output.push_str(&format!(
                "<text x=\"{:.2}\" y=\"{:.2}\" fill=\"{}\" {} text-anchor=\"middle\" dominant-baseline=\"central\">{}</text>\n",
                cx, cy, text_color, font_attrs, escape_xml(&display_str),
            ));
        }
    }

    /// PUA 다자리 숫자를 하나의 도형 안에 합쳐서 렌더링
    ///
    /// border_type=0이면 원형으로 자동 렌더링 (PUA 겹침 숫자는 원래 원문자)
    /// 장평 조절: textLength 속성으로 숫자 문자열을 도형 내부 폭에 맞춤
    fn draw_char_overlap_combined(
        &mut self,
        style: &TextStyle,
        overlap: &CharOverlapInfo,
        number_str: &str,
        bbox_x: f64,
        bbox_y: f64,
        bbox_w: f64,
        bbox_h: f64,
    ) {
        let font_size = style.effective_font_size();
        let box_size = font_size;

        // border_type=0이고 PUA 숫자이면 원형으로 자동 렌더링
        let effective_border = if overlap.border_type == 0 {
            1u8
        } else {
            overlap.border_type
        };
        let is_reversed = effective_border == 2 || effective_border == 4;
        let is_circle = effective_border == 1 || effective_border == 2;
        let is_rect = effective_border == 3 || effective_border == 4;

        // draw_char_overlap와 동일 규칙. 여기서는 effective_border 가 0이 아니므로
        // (border_type=0 → 원형 승격) 축소 게이트에 걸리지 않는다 (#4085).
        let size_ratio = char_overlap_size_ratio(effective_border, overlap.inner_char_size);
        let inner_font_size = font_size * size_ratio;

        let glyph_color = color_to_svg(style.color);
        let fill_color = if is_reversed { "#000000" } else { "none" };
        let stroke_color: &str = if is_reversed { "#000000" } else { &glyph_color };
        let text_color: &str = if is_reversed { "#FFFFFF" } else { &glyph_color };

        let font_family_str = if style.font_family.is_empty() {
            "sans-serif".to_string()
        } else {
            // [#3314] 요청 face → base family → generic 체인.
            // [#3772] bold 는 ExtraLight 를 빼서 PDF 굵기를 지킨다.
            super::render_font_family_chain_for_weight(&style.font_family, style.is_visually_bold())
        };
        let mut font_attrs = format!(
            "font-family=\"{}\" font-size=\"{:.2}\"",
            escape_xml(&font_family_str),
            inner_font_size
        );
        if let Some(w) = faux_bold_stroke_width(style, inner_font_size) {
            font_attrs.push_str(&faux_bold_stroke_attr(w, text_color));
        } else if style.is_visually_bold() {
            font_attrs.push_str(" font-weight=\"bold\"");
        } else if style.is_medium_weight() {
            font_attrs.push_str(" font-weight=\"500\"");
        }
        if style.italic {
            font_attrs.push_str(&format!(
                " font-style=\"{}\"",
                super::text_italic::CSS_STYLE
            ));
        }

        let cx = bbox_x + box_size / 2.0;
        let cy = bbox_y + bbox_h / 2.0;

        // 도형 렌더링 — 세로로 긴 타원 (한컴 정합, rx=ry*0.85)
        if is_circle {
            let ry = box_size / 2.0;
            let rx = ry * 0.85;
            self.output.push_str(&format!(
                "<ellipse cx=\"{:.2}\" cy=\"{:.2}\" rx=\"{:.2}\" ry=\"{:.2}\" fill=\"{}\" stroke=\"{}\" stroke-width=\"0.8\"/>\n",
                cx, cy, rx, ry, fill_color, stroke_color,
            ));
        } else if is_rect {
            let rx = cx - box_size / 2.0;
            let ry = cy - box_size / 2.0;
            self.output.push_str(&format!(
                "<rect x=\"{:.2}\" y=\"{:.2}\" width=\"{:.2}\" height=\"{:.2}\" fill=\"{}\" stroke=\"{}\" stroke-width=\"0.8\"/>\n",
                rx, ry, box_size, box_size, fill_color, stroke_color,
            ));
        }

        // 장평 조절: 숫자 자릿수에 따라 textLength로 폭 압축
        let text_width = box_size * 0.7; // 도형 내부 여백 고려
                                         // 다자리 숫자는 baseline을 살짝 올려 시각적 중앙 맞춤
        let text_y = cy - font_size * 0.08;
        self.output.push_str(&format!(
            "<text x=\"{:.2}\" y=\"{:.2}\" fill=\"{}\" {} text-anchor=\"middle\" dominant-baseline=\"central\" textLength=\"{:.2}\" lengthAdjust=\"spacingAndGlyphs\">{}</text>\n",
            cx, text_y, text_color, font_attrs, text_width, escape_xml(number_str),
        ));
    }

    /// 줄 기준으로 해소한 위 밑줄을 그린다.
    fn draw_top_underline(
        &mut self,
        x1: f64,
        baseline: f64,
        x2: f64,
        color: &str,
        geometry: &super::text_decoration::TopUnderlineGeometry,
        phase_delta: f64,
    ) {
        if x2 <= x1 {
            return;
        }
        for stroke in &geometry.strokes {
            let dash = stroke
                .dash
                .iter()
                .map(f64::to_string)
                .collect::<Vec<_>>()
                .join(" ");
            let y = baseline + stroke.offset;
            self.output.push_str(&format!(
                "<line x1=\"{x1}\" y1=\"{y}\" x2=\"{x2}\" y2=\"{y}\" stroke=\"{color}\" stroke-width=\"{}\" stroke-dasharray=\"{dash}\" stroke-dashoffset=\"{}\"/>\n",
                stroke.width, geometry.phase + phase_delta,
            ));
        }
        if let Some(dot) = &geometry.dots {
            let y = baseline + dot.offset;
            self.output.push_str(&format!(
                "<line x1=\"{x1}\" y1=\"{y}\" x2=\"{x2}\" y2=\"{y}\" stroke=\"{color}\" stroke-width=\"{}\" stroke-linecap=\"round\" stroke-dasharray=\"0 {}\" stroke-dashoffset=\"{}\"/>\n",
                dot.radius * 2.0, dot.step, geometry.phase + phase_delta,
            ));
        }
    }

    fn draw_line_shape(&mut self, x1: f64, y1: f64, x2: f64, y2: f64, color: &str, shape: u8) {
        match shape {
            7 => {
                // 이중선
                self.output.push_str(&format!(
                    "<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"0.7\"/>\n",
                    x1, y1 - 1.0, x2, y2 - 1.0, color));
                self.output.push_str(&format!(
                    "<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"0.7\"/>\n",
                    x1, y1 + 1.0, x2, y2 + 1.0, color));
            }
            8 => {
                // 가는+굵은 이중선
                self.output.push_str(&format!(
                    "<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"0.5\"/>\n",
                    x1, y1 - 1.2, x2, y2 - 1.2, color));
                self.output.push_str(&format!(
                    "<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"1.2\"/>\n",
                    x1, y1 + 0.8, x2, y2 + 0.8, color));
            }
            9 => {
                // 굵은+가는 이중선
                self.output.push_str(&format!(
                    "<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"1.2\"/>\n",
                    x1, y1 - 0.8, x2, y2 - 0.8, color));
                self.output.push_str(&format!(
                    "<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"0.5\"/>\n",
                    x1, y1 + 1.2, x2, y2 + 1.2, color));
            }
            10 => {
                // 삼중선
                self.output.push_str(&format!(
                    "<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"0.5\"/>\n",
                    x1, y1 - 1.5, x2, y2 - 1.5, color));
                self.output.push_str(&format!(
                    "<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"0.5\"/>\n",
                    x1, y1, x2, y2, color));
                self.output.push_str(&format!(
                    "<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"0.5\"/>\n",
                    x1, y1 + 1.5, x2, y2 + 1.5, color));
            }
            11 => {
                // 물결선
                let wave_h = 1.5;
                let wave_w = 6.0;
                let mut d = format!("M{:.2},{:.2}", x1, y1);
                let mut cx = x1;
                let mut up = true;
                while cx < x2 {
                    let next = (cx + wave_w).min(x2);
                    let cy = if up { y1 - wave_h } else { y1 + wave_h };
                    d.push_str(&format!(
                        " Q{:.2},{:.2} {:.2},{:.2}",
                        (cx + next) / 2.0,
                        cy,
                        next,
                        y1
                    ));
                    cx = next;
                    up = !up;
                }
                self.output.push_str(&format!(
                    "<path d=\"{}\" fill=\"none\" stroke=\"{}\" stroke-width=\"0.7\"/>\n",
                    d, color
                ));
            }
            12 => {
                // 이중물결선
                for offset in [-1.0f64, 1.0] {
                    let wy = y1 + offset;
                    let wave_h = 1.2;
                    let wave_w = 6.0;
                    let mut d = format!("M{:.2},{:.2}", x1, wy);
                    let mut cx = x1;
                    let mut up = true;
                    while cx < x2 {
                        let next = (cx + wave_w).min(x2);
                        let cy = if up { wy - wave_h } else { wy + wave_h };
                        d.push_str(&format!(
                            " Q{:.2},{:.2} {:.2},{:.2}",
                            (cx + next) / 2.0,
                            cy,
                            next,
                            wy
                        ));
                        cx = next;
                        up = !up;
                    }
                    self.output.push_str(&format!(
                        "<path d=\"{}\" fill=\"none\" stroke=\"{}\" stroke-width=\"0.5\"/>\n",
                        d, color
                    ));
                }
            }
            _ => {
                // 단선 (dasharray로 모양 표현)
                // 0=실선, 1=파선, 2=점선, 3=일점쇄선, 4=이점쇄선, 5=긴파선, 6=원형점선
                let dasharray = match shape {
                    1 => " stroke-dasharray=\"3 3\"",
                    2 => " stroke-dasharray=\"1 2\"",
                    3 => " stroke-dasharray=\"6 2 1 2\"",
                    4 => " stroke-dasharray=\"6 2 1 2 1 2\"",
                    5 => " stroke-dasharray=\"8 4\"",
                    6 => " stroke-dasharray=\"0.1 2.5\" stroke-linecap=\"round\"",
                    _ => "", // 0=실선
                };
                self.output.push_str(&format!(
                    "<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"1\"{}/>\n",
                    x1, y1, x2, y2, color, dasharray));
            }
        }
    }

    /// 양식 개체 SVG 렌더링
    fn render_form_object(&mut self, form: &FormObjectNode, bbox: &BoundingBox) {
        use super::form_appearance::{form_drawing, FormPrimitive};
        let drawing = form_drawing(form, *bbox);
        // 컨트롤은 자기 영역 밖을 그리지 않는다. 폭보다 긴 캡션은 영역 경계에서 잘린다.
        let clip_id = format!("form-clip-{}", self.next_clip_id());
        self.begin_layer_clip(*bbox, &clip_id);
        for primitive in drawing.primitives {
            match primitive {
                FormPrimitive::Rect { bbox: b, color } => self.output.push_str(&format!(
                    "<rect x=\"{:.3}\" y=\"{:.3}\" width=\"{:.3}\" height=\"{:.3}\" fill=\"{}\"/>\n",
                    b.x, b.y, b.width, b.height, escape_xml(&color))),
                FormPrimitive::Circle { x, y, radius, color } => self.output.push_str(&format!(
                    "<circle cx=\"{x:.3}\" cy=\"{y:.3}\" r=\"{radius:.3}\" fill=\"{}\"/>\n", escape_xml(&color))),
                FormPrimitive::Polyline { points, color, width, closed } => {
                    let points = points.iter().map(|p| format!("{:.3},{:.3}",p[0],p[1])).collect::<Vec<_>>().join(" ");
                    if closed { self.output.push_str(&format!("<polygon points=\"{points}\" fill=\"{}\"/>\n",escape_xml(&color))); }
                    else { self.output.push_str(&format!("<polyline points=\"{points}\" fill=\"none\" stroke=\"{}\" stroke-width=\"{width:.3}\"/>\n",escape_xml(&color))); }
                }
            }
        }
        if let Some(label) = drawing.label {
            if self.font_embed_mode != FontEmbedMode::None {
                self.font_codepoints
                    .entry(label.font_family.clone())
                    .or_default()
                    .extend(label.text.chars());
            }
            self.output.push_str(&format!(
                "<text x=\"{:.3}\" y=\"{:.3}\" font-size=\"{:.3}\" fill=\"{}\" font-family=\"{}\" font-weight=\"{}\" font-style=\"{}\">{}</text>\n",
                label.x, label.baseline, label.font_size, escape_xml(&label.color),
                escape_xml(&super::render_font_family_chain_for_weight(&label.font_family, label.bold)),
                if label.bold { "bold" } else { "normal" },
                if label.italic { super::text_italic::CSS_STYLE } else { "normal" }, escape_xml(&label.text)));
        }
        self.end_layer_clip();
    }

    fn place_debug_label(
        occupied: &mut Vec<(f64, f64, f64, f64)>,
        x: f64,
        preferred_y: f64,
        width: f64,
        height: f64,
        page_height: f64,
    ) -> f64 {
        fn overlaps(a: (f64, f64, f64, f64), b: (f64, f64, f64, f64)) -> bool {
            let pad = 1.0;
            let (ax, ay, aw, ah) = a;
            let (bx, by, bw, bh) = b;
            ax < bx + bw + pad && ax + aw + pad > bx && ay < by + bh + pad && ay + ah + pad > by
        }

        let min_y = 0.0;
        let max_y = (page_height - height).max(0.0);
        let preferred_y = preferred_y.clamp(min_y, max_y);
        let step = height + 2.0;

        for i in 0..64 {
            let distance = step * i as f64;
            for offset in if i == 0 {
                [0.0, f64::NAN]
            } else {
                [-distance, distance]
            } {
                if offset.is_nan() {
                    continue;
                }
                let candidate_y = preferred_y + offset;
                if candidate_y < min_y || candidate_y > max_y {
                    continue;
                }
                let candidate = (x, candidate_y, width, height);
                if !occupied
                    .iter()
                    .any(|&(ox, oy, ow, oh)| overlaps(candidate, (ox, oy, ow, oh)))
                {
                    occupied.push(candidate);
                    return candidate_y;
                }
            }
        }

        occupied.push((x, preferred_y, width, height));
        preferred_y
    }

    /// 디버그 오버레이: 문단/표 경계와 인덱스 라벨을 렌더링
    fn render_debug_overlay(&mut self) {
        self.output
            .push_str("<g id=\"debug-overlay\" opacity=\"0.7\">\n");

        // 색상 팔레트: 문단별 교대 색상
        let colors = [
            "#FF6B6B", "#4ECDC4", "#45B7D1", "#96CEB4", "#FFEAA7", "#DDA0DD", "#98D8C8", "#F7DC6F",
        ];
        let mut occupied_labels = Vec::new();

        // 문단 경계 렌더링
        let mut sorted_paras: Vec<_> = self.overlay_para_bounds.iter().collect();
        sorted_paras.sort_by_key(|&(pi, _)| *pi);

        for (key, bounds) in &sorted_paras {
            let pi = **key % 100000;
            let si = bounds.section_index;
            let color = colors[pi % colors.len()];
            let label = format!("s{}:pi={} y={:.1}", si, pi, bounds.y);
            // 경계 사각형 (점선)
            self.output.push_str(&format!(
                "<rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" fill=\"none\" stroke=\"{}\" stroke-width=\"0.5\" stroke-dasharray=\"3,2\"/>\n",
                bounds.x, bounds.y, bounds.width, bounds.height, color,
            ));
            // 라벨 (좌측 상단)
            let label_w = label.len() as f64 * 5.0 + 4.0;
            let label_h = 10.0;
            let label_y = Self::place_debug_label(
                &mut occupied_labels,
                bounds.x,
                bounds.y - label_h,
                label_w,
                label_h,
                self.height,
            );
            self.output.push_str(&format!(
                "<rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"10\" fill=\"{}\" rx=\"2\"/>\n",
                bounds.x, label_y, label_w, color,
            ));
            self.output.push_str(&format!(
                "<text x=\"{}\" y=\"{}\" font-family=\"monospace\" font-size=\"8\" fill=\"#fff\" font-weight=\"bold\">{}</text>\n",
                bounds.x + 2.0,
                label_y + label_h - 2.0,
                label,
            ));
        }

        // 표 경계 렌더링
        let table_bounds = std::mem::take(&mut self.overlay_table_bounds);
        for tbl in &table_bounds {
            // 표 경계 (빨간 점선)
            self.output.push_str(&format!(
                "<rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" fill=\"none\" stroke=\"#E74C3C\" stroke-width=\"1.0\" stroke-dasharray=\"5,3\"/>\n",
                tbl.x, tbl.y, tbl.width, tbl.height,
            ));
            // 표 라벨 (우측 상단)
            let label = format!(
                "s{}:pi={} ci={} {}x{} y={:.1}",
                tbl.section_index,
                tbl.para_index,
                tbl.control_index,
                tbl.row_count,
                tbl.col_count,
                tbl.y
            );
            let label_w = label.len() as f64 * 5.0 + 4.0;
            let label_x = (tbl.x + tbl.width - label_w).max(tbl.x);
            let label_h = 11.0;
            let label_y = Self::place_debug_label(
                &mut occupied_labels,
                label_x,
                tbl.y - label_h,
                label_w,
                label_h,
                self.height,
            );
            self.output.push_str(&format!(
                "<rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"11\" fill=\"#E74C3C\" rx=\"2\"/>\n",
                label_x, label_y, label_w,
            ));
            self.output.push_str(&format!(
                "<text x=\"{}\" y=\"{}\" font-family=\"monospace\" font-size=\"8\" fill=\"#fff\" font-weight=\"bold\">{}</text>\n",
                label_x + 2.0,
                label_y + label_h - 2.0,
                label,
            ));
        }
        self.overlay_table_bounds = table_bounds;

        // 이미지 경계 렌더링
        let image_bounds = std::mem::take(&mut self.overlay_image_bounds);
        for img in &image_bounds {
            self.output.push_str(&format!(
                "<rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" fill=\"none\" stroke=\"#7B61FF\" stroke-width=\"1.2\" stroke-dasharray=\"4,2\"/>\n",
                img.x, img.y, img.width, img.height,
            ));
            let label = format!(
                "s{}:pi={} ci={} image y={:.1}",
                img.section_index, img.para_index, img.control_index, img.y
            );
            let label_w = label.len() as f64 * 5.0 + 4.0;
            let label_h = 11.0;
            let label_y = Self::place_debug_label(
                &mut occupied_labels,
                img.x,
                img.y - label_h,
                label_w,
                label_h,
                self.height,
            );
            self.output.push_str(&format!(
                "<rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"11\" fill=\"#7B61FF\" rx=\"2\"/>\n",
                img.x, label_y, label_w,
            ));
            self.output.push_str(&format!(
                "<text x=\"{}\" y=\"{}\" font-family=\"monospace\" font-size=\"8\" fill=\"#fff\" font-weight=\"bold\">{}</text>\n",
                img.x + 2.0,
                label_y + label_h - 2.0,
                label,
            ));
        }
        self.overlay_image_bounds = image_bounds;

        // vpos=0 리셋 위치 마커 (앰버 가로 점선 + 라벨)
        let vpos_resets = std::mem::take(&mut self.overlay_vpos_resets);
        for rs in &vpos_resets {
            // 노란 가로선 (점선)
            self.output.push_str(&format!(
                "<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"#FFB300\" stroke-width=\"1.5\" stroke-dasharray=\"6,3\"/>\n",
                rs.x, rs.y, rs.x + rs.width, rs.y,
            ));
            // 라벨 (좌측, 가로선 위)
            let label = format!(
                "vpos-reset s{}:pi={}:line={}",
                rs.section_index, rs.para_index, rs.line_index
            );
            let label_w = label.len() as f64 * 5.0 + 4.0;
            let label_h = 11.0;
            let label_y = Self::place_debug_label(
                &mut occupied_labels,
                rs.x,
                rs.y - label_h,
                label_w,
                label_h,
                self.height,
            );
            self.output.push_str(&format!(
                "<rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"11\" fill=\"#FFB300\" rx=\"2\"/>\n",
                rs.x, label_y, label_w,
            ));
            self.output.push_str(&format!(
                "<text x=\"{}\" y=\"{}\" font-family=\"monospace\" font-size=\"8\" fill=\"#000\" font-weight=\"bold\">{}</text>\n",
                rs.x + 2.0,
                label_y + label_h - 2.0,
                label,
            ));
        }
        self.overlay_vpos_resets = vpos_resets;

        self.output.push_str("</g>\n");
    }
    /// [#6127] 한컴 합성 PUA 기호 벡터 합성 — web_canvas `draw_enclosed_pua` 와 같은
    /// 동봉 em 기하. 메트릭이 없는 다자리 네모 숫자는 상자 0.72em, 숫자 0.5em 폴백이다.
    fn draw_enclosed_pua(
        &mut self,
        glyph: super::EnclosedPua,
        x: f64,
        baseline_y: f64,
        style: &TextStyle,
        font_size: f64,
    ) {
        let inner_text = glyph.inner_text();
        if let Some(g) = super::enclosed_pua_geometry::geometry(glyph, font_size) {
            let faces = super::enclosed_pua_geometry::inner_faces(glyph);
            for face in &faces {
                self.font_codepoints
                    .entry((*face).to_string())
                    .or_default()
                    .extend(inner_text.chars());
            }
            let family = format!(
                "{},{}",
                faces
                    .iter()
                    .map(|face| format!("'{face}'"))
                    .collect::<Vec<_>>()
                    .join(","),
                super::render_font_family_chain_for_weight(
                    &style.font_family,
                    style.is_visually_bold()
                )
            );
            let color = color_to_svg(style.color);
            match g.frame_shape {
                super::enclosed_pua_geometry::FrameShape::Rect => self.output.push_str(&format!(
                    "<rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" fill=\"none\" stroke=\"{}\" stroke-width=\"{}\"/>\n",
                    x + g.frame_x, baseline_y + g.frame_y, g.frame_width, g.frame_height,
                    color, g.stroke_width)),
                super::enclosed_pua_geometry::FrameShape::Ellipse => self.output.push_str(&format!(
                    "<ellipse cx=\"{}\" cy=\"{}\" rx=\"{}\" ry=\"{}\" fill=\"none\" stroke=\"{}\" stroke-width=\"{}\"/>\n",
                    x + g.frame_x + g.frame_width / 2.0,
                    baseline_y + g.frame_y + g.frame_height / 2.0,
                    g.frame_width / 2.0, g.frame_height / 2.0, color, g.stroke_width)),
            }
            self.output.push_str(&format!(
                "<text transform=\"matrix({} 0 0 {} {} {})\" x=\"0\" y=\"0\" font-family=\"{}\" font-size=\"{}\" fill=\"{}\">{}</text>\n",
                g.inner_scale_x, g.inner_scale_y, x + g.inner_x,
                baseline_y + g.inner_y, escape_xml(&family), font_size, color,
                escape_xml(&inner_text)));
            return;
        }
        let box_size = (font_size * 0.72).max(1.0);
        let box_y = baseline_y - font_size * 0.76;
        let color = color_to_svg(style.color);
        let number_font_size = (font_size * 0.5).max(1.0);
        let font_family = if style.font_family.is_empty() {
            "sans-serif".to_string()
        } else {
            super::render_font_family_chain_for_weight(&style.font_family, style.is_visually_bold())
        };
        self.output.push_str(&format!(
            "<rect x=\"{:.2}\" y=\"{:.2}\" width=\"{:.2}\" height=\"{:.2}\" fill=\"none\" stroke=\"{}\" stroke-width=\"{:.2}\"/>\n",
            x,
            box_y,
            box_size,
            box_size,
            color,
            (font_size * 0.04).max(0.6),
        ));
        self.output.push_str(&format!(
            "<text x=\"{:.2}\" y=\"{:.2}\" font-family=\"{}\" font-size=\"{:.2}\" fill=\"{}\" text-anchor=\"middle\">{}</text>\n",
            x + box_size / 2.0,
            box_y + box_size * 0.72,
            escape_xml(&font_family),
            number_font_size,
            color,
            inner_text,
        ));
    }

    /// Connectors replay the shared endpoint-tangent outlines over their shaft.
    fn draw_path_arrow_markers(&mut self, path: &PathNode) {
        let Some(style) = &path.line_style else {
            return;
        };
        self.draw_arrow_heads(&super::arrow::connector_heads(path), style);
    }

    fn draw_arrow_heads(&mut self, heads: &[super::arrow::ArrowHead], style: &LineStyle) {
        for head in heads {
            self.draw_path(
                &head.commands,
                &ShapeStyle {
                    fill_color: Some(if head.filled { style.color } else { 0xFFFFFF }),
                    stroke_color: if head.filled { None } else { Some(style.color) },
                    stroke_width: (style.width * 0.3).max(0.5),
                    ..Default::default()
                },
            );
        }
    }
}

impl Renderer for SvgRenderer {
    fn begin_page(&mut self, width: f64, height: f64) {
        self.width = width;
        self.height = height;
        self.output.clear();
        self.defs.clear();
        self.defs_ids.clear();
        self.gradient_counter = 0;
        self.overlay_para_bounds.clear();
        self.overlay_table_bounds.clear();
        self.overlay_image_bounds.clear();
        self.overlay_vpos_resets.clear();
        self.overlay_skip_depth = 0;
        self.overlay_page_section = -1;
        self.metric_faces.clear();
        self.axis_stroke_hint_allowed = true;
        self.axis_stroke_hint_stack.clear();
        // xmlns:xlink 필수: SVG 가 <img> 로 로드될 때(예: blob URL 미리보기)
        // 엄격한 XML 파싱으로 인해 xmlns:xlink 미선언 시 <image xlink:href=...> 가 무시됨.
        self.output.push_str(&format!(
            "<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" width=\"{}\" height=\"{}\" viewBox=\"0 0 {} {}\">\n",
            width, height, width, height,
        ));
        self.defs_insert_pos = self.output.len();
    }

    fn end_page(&mut self) {
        // 디버그 오버레이 출력
        if self.debug_overlay {
            self.render_debug_overlay();
        }

        if !self.defs.is_empty() {
            let mut defs_block = String::from("<defs>\n");
            for def in &self.defs {
                defs_block.push_str(def);
            }
            defs_block.push_str("</defs>\n");
            self.output.insert_str(self.defs_insert_pos, &defs_block);
        }
        // [#4709] 루트 <svg>에 이 페이지 배치에 쓰인 메트릭 face 목록 주석 (옵트인).
        if self.annotate_metric_font && !self.metric_faces.is_empty() {
            if let Some(pos) = self.output.find('>') {
                let list = self
                    .metric_faces
                    .iter()
                    .cloned()
                    .collect::<Vec<_>>()
                    .join(",");
                self.output.insert_str(
                    pos,
                    &format!(" data-rhwp-metric-fonts=\"{}\"", escape_xml(&list)),
                );
            }
        }
        self.output.push_str("</svg>\n");
    }

    fn draw_text(&mut self, text: &str, x: f64, y: f64, style: &TextStyle) {
        self.draw_text_positioned(text, x, y, style, None);
    }

    fn draw_text_positioned(
        &mut self,
        text: &str,
        x: f64,
        y: f64,
        style: &TextStyle,
        layout_positions: Option<&[f64]>,
    ) {
        // [Task #1067] inline 컨트롤 placeholder (U+FFFC OBJECT REPLACEMENT CHARACTER) 를
        // 보이지 않게 처리. HWP/HWPX 의 inline 도형/표/그림 등 treat_as_char 컨트롤이
        // paragraph text 자체에 U+FFFC 로 표현됨 — 도형 path 는 별도 emit 되므로 본
        // placeholder character 는 시각적으로 invisible 해야 한다. 한컴 정답지 정합.
        let metric_source: String = text.chars().filter(|&c| c != '\u{FFFC}').collect();
        let text = metric_source.as_str();
        if text.is_empty() {
            return;
        }
        // [Task #509] 한컴은 폰트 지정과 상관없이 PUA 를 자체 처리. 지정 폰트에 글리프
        // 부재 시 한컴 내부 매핑이 발행. rhwp 도 동일 동작 모방 — 일반 텍스트도 PUA
        // 변환 적용 (PR #251 정합). 매핑 표는 한컴 PDF 정답지 기준.
        let text = &expand_pua_render_text_in_style(&text, style);
        // [Task #528] Hanyang-PUA 옛한글 → KS X 1026-1:2007 자모 시퀀스.
        // 한/글 2010 이전 옛한글 PUA 인코딩을 표준 자모로 변환 (KTUG 매핑).
        let text = &expand_pua_old_hangul(text);
        if self.font_embed_mode != FontEmbedMode::None && style.italic {
            for family in style
                .font_family
                .split(',')
                .map(str::trim)
                .filter(|s| !s.is_empty())
            {
                self.font_italic_styles
                    .insert((family.to_owned(), style.is_visually_bold()));
            }
        }
        self.prepare_pua_glyphs(text, style);
        let source_coverage = self.source_font_coverage.clone();

        let color = color_to_svg(style.color);
        let base_font_size = style.effective_font_size();
        // 위첨자/아래첨자는 레이아웃 advance 는 원래 run 기준으로 유지하고,
        // 실제 SVG glyph 크기와 baseline 만 Canvas/HTML 출력과 동일하게 조정한다.
        let (font_size, y) = style.script_draw_metrics(base_font_size, y);
        // [#2771] `textLength` 는 **실제로 그려지는** 글리프 폭에 맞춰야 한다.
        // char_positions 의 advance 는 본문(base) 크기 기준이므로, 0.7 배로 그려지는
        // 첨자에 그대로 넘기면 lengthAdjust="spacingAndGlyphs" 가 글리프를 1/0.7 배
        // 가로로 늘린다. 비첨자는 정확히 1.0 이라 기존 textLength 값이 불변이다.
        let script_advance_scale = style.script_advance_scale();
        let font_family = if style.font_family.is_empty() {
            "sans-serif".to_string()
        } else {
            // [#3314] 요청 face → base family → generic 체인.
            // [#3772] bold 는 ExtraLight 를 빼서 PDF 굵기를 지킨다.
            super::render_font_family_chain_for_weight(&style.font_family, style.is_visually_bold())
        };
        let old_hangul_font_family = format!("'RHWP Old Hangul',{}", font_family);

        // HFT와 TrueType의 장평 변환을 같은 스타일 계약에서 소비한다.
        let (font_size, ratio) = style.ratio_draw_params(font_size);
        let has_ratio = style.has_horizontal_ratio();

        // 공통 스타일 속성 구성 (fill 제외 — 그림자/원본에서 각각 설정)
        // [#7151] 합성 볼드는 굵기를 획으로 명시한다 — 색이 fill 과 같아야 하므로
        // 속성 자체는 fill 을 아는 `attrs_for_cluster` 에서 붙인다.
        // 외곽선 글자는 채우지 않고 윤곽만 긋는다. 합성 볼드 획과 겹치지 않게 그 획은 끈다.
        let outline_attrs = style.text_paint.is_none().then(|| super::stroke_pattern::char_outline_stroke(style.outline_type)).flatten().map(
            |(width, intervals)| {
                let mut attrs = format!(
                    " stroke=\"{color}\" stroke-width=\"{width:.2}\" stroke-linecap=\"round\" stroke-linejoin=\"round\""
                );
                if !intervals.is_empty() {
                    let pattern: Vec<String> = intervals.iter().map(|v| format!("{v:.2}")).collect();
                    attrs.push_str(&format!(" stroke-dasharray=\"{}\"", pattern.join(" ")));
                }
                attrs
            },
        );
        let faux_bold_stroke =
            faux_bold_stroke_width(style, font_size).filter(|_| outline_attrs.is_none());
        let mut base_attrs = format!("font-size=\"{}\"", font_size);
        if faux_bold_stroke.is_none() {
            if style.is_visually_bold() {
                base_attrs.push_str(" font-weight=\"bold\"");
            } else if style.is_medium_weight() {
                base_attrs.push_str(" font-weight=\"500\"");
            }
        }
        if style.italic {
            base_attrs.push_str(&format!(
                " font-style=\"{}\"",
                super::text_italic::CSS_STYLE
            ));
        }
        // [#4709] 옵트인: 이 run 의 배치 폭을 계산한 내장 메트릭 face 주석.
        // 임베드 호스트가 함초롬 등 미설치 폰트의 자간 불일치를 보정할 근거.
        if self.annotate_metric_font {
            if let Some(face) = crate::renderer::font_metrics_data::layout_metric_face_name(
                &style.font_family,
                style.is_visually_bold(),
                style.italic,
            ) {
                base_attrs.push_str(&format!(" data-metric-font=\"{}\"", escape_xml(&face)));
                self.metric_faces.insert(face);
            }
        }
        let italic_face = |cluster_str: &str| {
            if !style.italic {
                return None;
            }
            let glyph = pua_glyph::display(&source_coverage, cluster_str, style);
            if source_coverage
                .glyph(&style.font_family, cluster_str)
                .is_none()
                && super::contains_old_hangul_jamo(&glyph)
            {
                return None;
            }
            source_coverage
                .text_faces
                .select(&font_family, &glyph, style.is_visually_bold(), true)
        };
        let attrs_for_cluster = |cluster_str: &str, fill: &str| {
            let glyph = pua_glyph::display(&source_coverage, cluster_str, style);
            let measured_family =
                super::measured_glyph_supplier::family(style, cluster_str).map(|family| {
                    super::render_font_family_chain_for_weight(family, style.is_visually_bold())
                });
            let cluster_font_family = if source_coverage
                .glyph(&style.font_family, cluster_str)
                .is_none()
                && super::contains_old_hangul_jamo(&glyph)
            {
                &old_hangul_font_family
            } else {
                measured_family.as_ref().unwrap_or(&font_family)
            };
            let face = italic_face(cluster_str);
            let selected_family = face.as_ref().map(|face| format!("'{}'", face.family));
            let attrs = face.as_ref().map_or_else(
                || base_attrs.clone(),
                |face| {
                    base_attrs.replace(
                        super::text_italic::CSS_STYLE,
                        if face.slanted { "italic" } else { "normal" },
                    )
                },
            );
            format!(
                "font-family=\"{}\" {} fill=\"{}\"{}",
                escape_xml(selected_family.as_deref().unwrap_or(cluster_font_family)),
                attrs,
                if style.text_paint.is_some_and(|p| !p.paint.fill) { "none" } else { fill },
                style.text_paint.map_or_else(
                    || faux_bold_stroke.map_or_else(String::new, |w| faux_bold_stroke_attr(w, fill)),
                    |p| format!(" stroke=\"{}\" stroke-width=\"{}\" stroke-linejoin=\"{}\" stroke-miterlimit=\"{}\" fill-opacity=\"{}\" stroke-opacity=\"{}\" paint-order=\"fill stroke\"{}",
                        color_to_svg(p.paint.stroke_color), if p.width == 0.0 { 1.0 } else { p.width },
                        match p.paint.line_join { 1 => "round", 2 => "bevel", _ => "miter" },
                        f64::from(p.paint.miter_limit_milli) / 1000.0,
                        f64::from(p.paint.fill_alpha) / 255.0, f64::from(p.paint.stroke_alpha) / 255.0,
                        if p.width == 0.0 { " vector-effect=\"non-scaling-stroke\"" } else { "" })),
            )
        };

        let symbol_sources = super::implicit_symbol::sources(&metric_source, text);
        // 클러스터 단위 렌더링: 옛한글 자모 조합 시퀀스를 하나의 <text>로 묶음
        let metric_text = super::composer::display_projection_metric_text(
            &metric_source,
            text,
            style.literal_soft_hyphen,
        );
        let char_positions =
            super::replay_positions_or_compute(metric_text, style, layout_positions);
        let visual_positions =
            super::text_direction::VisualTextPositions::for_style(text, &char_positions, style);
        let cluster_x = |index: usize, cluster: &str| {
            visual_positions
                .as_ref()
                .and_then(|p| p.span_origin(index, index + cluster.chars().count()))
                .unwrap_or(char_positions[index])
        };
        let clusters = if visual_positions.is_some() {
            super::contextual_text::coalesce(split_into_clusters(text))
        } else {
            split_into_clusters(text)
        };

        // 형광펜 배경 (CharShape.shade_color 기반 — web_canvas.rs와 동일 로직)
        if !self.suppress_text_glyphs
            && crate::model::color::char_shade(style.shade_color).is_some()
        {
            let text_width = *char_positions.last().unwrap_or(&0.0);
            if text_width > 0.0 {
                let spans = visual_positions
                    .as_ref()
                    .map(|p| p.segments(text.chars().count()))
                    .unwrap_or_else(|| vec![(0.0, text_width)]);
                for (left, right) in spans {
                    self.output.push_str(&format!(
                        "<rect x=\"{:.4}\" y=\"{:.4}\" width=\"{:.4}\" height=\"{:.4}\" fill=\"{}\"/>\n",
                        x + left, y - font_size, right-left, font_size*1.2, color_to_svg(style.shade_color)));
                }
            }
        }

        // Task #257: `·`(U+00B7) 를 <text> 대신 <circle> 로 렌더한다.
        //
        // 폰트 대체(휴먼명조→Batang 등)로 각 폰트의 `·` 글리프 LSB 와 글리프
        // 폭이 달라, rhwp 의 metric DB 기반 advance 계산과 실제 브라우저 렌더
        // 위치가 어긋난다. 한글 문서에서 `·` 의 시각적 의미는 "두 글자 사이의
        // 중앙 점" 이므로 폰트 비의존 벡터 도형으로 직접 그린다.
        //
        //   cx = advance box 수평 중앙
        //   cy = baseline(y) − font_size × MIDDLE_DOT_CY_OFFSET_EM  (CJK x-height 중앙)
        //   r  = font_size × MIDDLE_DOT_RADIUS_EM  (한글 COM PDF 실측, #2999)
        let advance_in = |positions: &[f64], char_idx: usize, cluster_str: &str| -> f64 {
            let n = cluster_str.chars().count();
            let end = char_idx + n;
            if end < positions.len() {
                positions[end] - positions[char_idx]
            } else {
                0.0
            }
        };
        let cluster_advance =
            |char_idx: usize, cluster_str: &str| advance_in(&char_positions, char_idx, cluster_str);
        // 글리프 폭(`textLength`)은 커닝 전 advance에 맞춘다. 자리와 `·` 중앙은 char_positions를 따른다.
        let fit_positions =
            super::glyph_fit_positions(metric_text, style, layout_positions, &char_positions);
        let glyph_advance =
            |char_idx: usize, cluster_str: &str| advance_in(&fit_positions, char_idx, cluster_str);
        let is_middle_dot = super::render_tree::is_vector_middle_dot;
        let dot_radius = font_size * super::render_tree::MIDDLE_DOT_RADIUS_EM;
        let dot_cy_offset = -font_size * super::render_tree::MIDDLE_DOT_CY_OFFSET_EM;

        // 연속 하이픈은 기본적으로 저장 글자 위치마다 낱글자로 그린다(#5804).
        // 원 글꼴의 획이 저장 간격보다 넓어 실선으로 겹치는 경우에만 아래에서
        // 낱글자별 짧은 획으로 그린다. 한 줄 전체를 밑줄로 대체하지 않는다.

        // 그림자 렌더링 (원본 아래에 오프셋된 그림자색 텍스트)
        if !self.suppress_text_glyphs && style.shadow_type > 0 {
            let shadow_color = color_to_svg(style.shadow_color);
            for [dx, dy] in crate::paint::text_shadow::offsets(style) {
                for (char_idx, cluster_str) in clusters.iter() {
                    let painted = visual_positions
                        .as_ref()
                        .map(|p| p.mirrored(cluster_str, *char_idx))
                        .unwrap_or(std::borrow::Cow::Borrowed(cluster_str.as_str()));
                    let cluster_str = painted.as_ref();
                    // 공백의 저장 전진폭·장식은 유지하되 글꼴의 잘못된 NBSP 윤곽선은 그리지 않는다.
                    if super::text_glyph_visibility::is_nonprinting_cluster(cluster_str) {
                        continue;
                    }
                    if cluster_str == "․" {
                        if let Some(ink) =
                            super::render_tree::fullwidth_onepoint_ink(style, font_size)
                        {
                            self.output.push_str(&format!(
                            "<ellipse cx=\"{:.4}\" cy=\"{:.4}\" rx=\"{:.4}\" ry=\"{:.4}\" fill=\"{}\"/>\n",
                            x + char_positions[*char_idx] + ink.center_x + dx,
                            y - ink.above_baseline + dy, ink.radius_x, ink.radius_y, shadow_color));
                            continue;
                        }
                    }
                    if let Some((cx, cy, rx, ry)) =
                        super::implicit_symbol::ink(symbol_sources.as_deref(), *char_idx, style)
                    {
                        self.output.push_str(&format!(
                            "<ellipse cx=\"{:.4}\" cy=\"{:.4}\" rx=\"{rx:.4}\" ry=\"{ry:.4}\" fill=\"{shadow_color}\"/>\n",
                            x + cluster_x(*char_idx, cluster_str) + cx + dx, y + cy + dy,
                        ));
                        continue;
                    }
                    if is_middle_dot(cluster_str) {
                        let adv = cluster_advance(*char_idx, cluster_str);
                        let cx = x + cluster_x(*char_idx, cluster_str) + adv / 2.0 + dx;
                        let cy = y + dot_cy_offset + dy;
                        self.output.push_str(&format!(
                            "<circle cx=\"{:.4}\" cy=\"{:.4}\" r=\"{:.4}\" fill=\"{}\"/>\n",
                            cx, cy, dot_radius, shadow_color,
                        ));
                        continue;
                    }
                    let char_x = x + cluster_x(*char_idx, cluster_str) + dx;
                    let char_y = y + dy;
                    let length_attrs = svg_cluster_text_length_attrs(
                        cluster_str,
                        glyph_advance(*char_idx, cluster_str),
                        style,
                        script_advance_scale,
                        ratio,
                    );
                    let shadow_attrs = attrs_for_cluster(cluster_str, &shadow_color);
                    let skew = italic_face(cluster_str)
                        .filter(|face| !face.slanted)
                        .map_or(0.0, |_| super::text_italic::SKEW_X);
                    if has_ratio || skew != 0.0 {
                        let transform = if skew == 0.0 {
                            format!("scale({ratio:.4},1)")
                        } else {
                            format!("matrix({ratio:.4} 0 {} 1 0 0)", ratio * skew)
                        };
                        self.output.push_str(&format!(
                            "<text transform=\"translate({},{}) {}\" {}{}>{}</text>\n",
                            char_x,
                            char_y,
                            transform,
                            shadow_attrs,
                            length_attrs,
                            escape_xml(&pua_glyph::display(&source_coverage, cluster_str, style)),
                        ));
                    } else {
                        self.output.push_str(&format!(
                            "<text x=\"{}\" y=\"{}\" {}{}>{}</text>\n",
                            char_x,
                            char_y,
                            shadow_attrs,
                            length_attrs,
                            escape_xml(&pua_glyph::display(&source_coverage, cluster_str, style)),
                        ));
                    }
                }
            }
        }

        // 원본 텍스트 렌더링. Canonical decoration/leader sidecars reuse the exact
        // positioning calculation below without repainting their TextRun mirror.
        if !self.suppress_text_glyphs {
            for (char_idx, cluster_str) in clusters.iter() {
                let painted = visual_positions
                    .as_ref()
                    .map(|p| p.mirrored(cluster_str, *char_idx))
                    .unwrap_or(std::borrow::Cow::Borrowed(cluster_str.as_str()));
                let cluster_str = painted.as_ref();
                // 공백의 저장 전진폭·장식은 유지하되 글꼴의 잘못된 NBSP 윤곽선은 그리지 않는다.
                if super::text_glyph_visibility::is_nonprinting_cluster(cluster_str) {
                    continue;
                }
                if cluster_str == "-" {
                    if let Some((start, end, y_offset, stroke)) =
                        super::overlapping_dash_leader_segment(
                            text,
                            style,
                            *char_idx,
                            &char_positions,
                            font_size,
                        )
                    {
                        let char_x = x + cluster_x(*char_idx, cluster_str);
                        self.output.push_str(&format!(
                            "<line x1=\"{:.4}\" y1=\"{:.4}\" x2=\"{:.4}\" y2=\"{:.4}\" stroke=\"{}\" stroke-width=\"{:.4}\"/>\n",
                            char_x + start,
                            y + y_offset,
                            char_x + end,
                            y + y_offset,
                            color,
                            stroke,
                        ));
                        // 가시 획은 분리하되 검색 가능한 원문 하이픈은 남긴다.
                        self.output.push_str(&format!(
                            "<text x=\"{:.4}\" y=\"{:.4}\" font-size=\"{}\" fill=\"{}\" fill-opacity=\"0\">-</text>\n",
                            char_x, y, font_size, color,
                        ));
                        continue;
                    }
                }
                // [#6127] 한컴 합성 PUA 기호(사각 안 숫자 등) 평문 폴백 — web_canvas
                // (`draw_enclosed_pua`)와 동일한 bounded vector 합성. raw PUA 를
                // 흘리면 함초롬 확장 글꼴이 없는 소비자(브라우저·PyMuPDF)에서 빈칸이
                // 된다(2599643 "②⓪⓪" 소실). CharOverlap 경로의 #4158 합성과 같은
                // 의미이고, 백엔드 간 패리티를 맞춘다.
                if cluster_str.chars().count() == 1 {
                    if let Some(glyph) = cluster_str.chars().next().and_then(super::enclosed_pua) {
                        let char_x = x + cluster_x(*char_idx, cluster_str);
                        self.draw_enclosed_pua(glyph, char_x, y, style, font_size);
                        continue;
                    }
                }
                if let Some((cx, cy, rx, ry)) =
                    super::implicit_symbol::ink(symbol_sources.as_deref(), *char_idx, style)
                {
                    let char_x = x + cluster_x(*char_idx, cluster_str);
                    if style.emboss || style.engrave {
                        let offset = (font_size / 20.0).max(1.0);
                        let (upper, lower) = if style.emboss {
                            ("#ffffff", "#808080")
                        } else {
                            ("#808080", "#ffffff")
                        };
                        for (delta, fill) in [(-offset, upper), (offset, lower)] {
                            self.output.push_str(&format!(
                                "<ellipse cx=\"{:.4}\" cy=\"{:.4}\" rx=\"{rx:.4}\" ry=\"{ry:.4}\" fill=\"{fill}\"/>\n",
                                char_x + cx + delta, y + cy + delta,
                            ));
                        }
                    }
                    let fill = if outline_attrs.is_some() {
                        "none"
                    } else {
                        &color
                    };
                    let attrs = attrs_for_cluster(cluster_str, fill);
                    let outline = outline_attrs.as_deref().unwrap_or("");
                    self.output.push_str(&format!(
                        "<ellipse cx=\"{:.4}\" cy=\"{:.4}\" rx=\"{rx:.4}\" ry=\"{ry:.4}\" {attrs}{outline}/>\n",
                        char_x + cx, y + cy,
                    ));
                    self.output.push_str(&format!(
                        "<text x=\"{char_x:.4}\" y=\"{y:.4}\" fill-opacity=\"0\">{}</text>\n",
                        escape_xml(cluster_str),
                    ));
                    continue;
                }
                if let Some((cx, cy, rx, ry)) =
                    super::legacy_hft_bullet_geometry(cluster_str, style)
                {
                    let char_x = x + cluster_x(*char_idx, cluster_str);
                    self.output.push_str(&format!(
                        "<ellipse cx=\"{:.4}\" cy=\"{:.4}\" rx=\"{:.4}\" ry=\"{:.4}\" fill=\"{}\"/>\n",
                        char_x + cx, y + cy, rx, ry, color,
                    ));
                    self.output.push_str(&format!(
                        "<text x=\"{:.4}\" y=\"{:.4}\" fill-opacity=\"0\">{cluster_str}</text>\n",
                        char_x, y,
                    ));
                    continue;
                }
                if cluster_str == "․" {
                    if let Some(ink) = super::render_tree::fullwidth_onepoint_ink(style, font_size)
                    {
                        let origin = x + char_positions[*char_idx];
                        self.output.push_str(&format!(
                            "<ellipse cx=\"{:.4}\" cy=\"{:.4}\" rx=\"{:.4}\" ry=\"{:.4}\" fill=\"{}\"/>\n",
                            origin + ink.center_x, y - ink.above_baseline, ink.radius_x, ink.radius_y, color));
                        // 원문 문자·오프셋과 검색 가능성을 보존한다.
                        self.output.push_str(&format!("<text x=\"{origin:.4}\" y=\"{y:.4}\" font-size=\"{font_size}\" fill-opacity=\"0\">․</text>\n"));
                        continue;
                    }
                }
                if is_middle_dot(cluster_str) {
                    let adv = cluster_advance(*char_idx, cluster_str);
                    let cx = x + cluster_x(*char_idx, cluster_str) + adv / 2.0;
                    let cy = y + dot_cy_offset;
                    self.output.push_str(&format!(
                        "<circle cx=\"{:.4}\" cy=\"{:.4}\" r=\"{:.4}\" fill=\"{}\"/>\n",
                        cx, cy, dot_radius, color,
                    ));
                    // Task #257 은 폰트별 LSB 편차를 피하려고 `·` 를 벡터로 그린다. 그
                    // 부작용으로 이 문자가 **출력 텍스트 스트림에서 사라져** PDF 검색과
                    // 스크린리더에서 누락된다 (10k 표본 300건 실측: 문서의 38.0% 가
                    // U+00B7 을 전량 소실). 보이지 않는 텍스트를 같은 자리에 겹쳐
                    // 추출만 복구한다 — 그려지는 것은 위 원 그대로이므로 시각 회귀 없음.
                    self.output.push_str(&format!(
                        "<text x=\"{:.4}\" y=\"{:.4}\" font-size=\"{}\" fill=\"{}\" \
                         fill-opacity=\"0\"{}>{}</text>\n",
                        x + cluster_x(*char_idx, cluster_str),
                        y,
                        font_size,
                        color,
                        svg_cluster_text_length_attrs(
                            cluster_str,
                            adv,
                            style,
                            script_advance_scale,
                            ratio,
                        ),
                        escape_xml(cluster_str),
                    ));
                    continue;
                }
                let char_x = x + cluster_x(*char_idx, cluster_str);
                let length_attrs = svg_cluster_text_length_attrs(
                    cluster_str,
                    glyph_advance(*char_idx, cluster_str),
                    style,
                    script_advance_scale,
                    ratio,
                );
                let common_attrs = match &outline_attrs {
                    Some(stroke) => attrs_for_cluster(cluster_str, "none") + stroke,
                    None => attrs_for_cluster(cluster_str, &color),
                };
                let glyph_text = pua_glyph::display(&source_coverage, cluster_str, style);
                let skew = italic_face(cluster_str)
                    .filter(|face| !face.slanted)
                    .map_or(0.0, |_| super::text_italic::SKEW_X);
                if has_ratio || skew != 0.0 {
                    let transform = if skew == 0.0 {
                        format!("scale({ratio:.4},1)")
                    } else {
                        format!("matrix({ratio:.4} 0 {} 1 0 0)", ratio * skew)
                    };
                    self.output.push_str(&format!(
                        "<text transform=\"translate({},{}) {}\" {}{}>{}</text>\n",
                        char_x,
                        y,
                        transform,
                        common_attrs,
                        length_attrs,
                        escape_xml(&glyph_text),
                    ));
                } else {
                    self.output.push_str(&format!(
                        "<text x=\"{}\" y=\"{}\" {}{}>{}</text>\n",
                        char_x,
                        y,
                        common_attrs,
                        length_attrs,
                        escape_xml(&glyph_text),
                    ));
                }
            }
        }

        // 밑줄 처리 — [#5730] 아래 밑줄은 기준선 + 0.17em (한글 2022 프로브 실측,
        // 6개 크기 선형). 종전 고정 +2.0px 은 큰 글꼴에서 디센더를 가로질렀다.
        // 이중/삼중선(shape 7~10)의 선별 위치·굵기도 em 비례 실측표를 따른다.
        // [#6028] soft-wrap 줄-말미 공백은 장식선(밑줄/취소선)에서 제외 —
        // 한글은 wrap 이 소비한 구분 공백을 줄에 남기지 않아 선이 마지막
        // 글리프에서 끝난다(2307287 4쪽: rhwp 밑줄이 글자 끝 +6.5~9.8pt 로
        // 표 오른쪽 괘선 밖까지 나감, 한글은 -1.2pt 안). active 트림은
        // TextLine 진입부가 soft-wrap 줄의 마지막 텍스트 run 에만 배정한다.
        let decoration_width = {
            let trailing = text.chars().rev().take_while(|ch| *ch == ' ').count();
            let trim = self.active_decoration_trim.min(trailing);
            // [#6451] 트림이 없으면 **레이아웃 폭**(render tree bbox)을 그대로 쓴다 —
            // run 경계가 정확히 맞아 밑줄이 한 줄로 이어진다. 작성기 자체 측정은
            // 레이아웃 advance 와 0.3px 남짓 어긋나 조각 사이에 실틈을 남긴다.
            // 트림이 있으면 말미 공백을 글자 단위로 걷어내야 하므로 #6028 계산을 쓴다.
            match self.active_decoration_width {
                Some(w) if trim == 0 => w,
                _ => {
                    let n = text.chars().count();
                    char_positions
                        .get(n - trim)
                        .copied()
                        .unwrap_or_else(|| *char_positions.last().unwrap_or(&0.0))
                }
            }
        };
        let decoration_end = text.chars().count()
            - self
                .active_decoration_trim
                .min(text.chars().rev().take_while(|ch| *ch == ' ').count());
        let segments = visual_positions
            .as_ref()
            .map(|p| p.segments(decoration_end))
            .unwrap_or_else(|| vec![(0.0, decoration_width)]);
        for (left, right) in segments {
            let x = x + left;
            let decoration_width = right - left;
            if !matches!(style.underline, UnderlineType::None) {
                let text_width = decoration_width;
                // 밑줄 색은 CHAR_SHAPE 의 **고정 위치 필수 필드**다(doc_info.rs 의
                // text_color 바로 뒤). COLORREF 0 은 "미지정"이 아니라 **검정**이므로
                // sentinel 로 쓸 수 없다 — 종전 `!= 0` 검사는 문서가 명시한 검정 밑줄을
                // 글자색으로 바꿔 그렸다(hwpx_sample2 12쪽: 정답지 검정 25개 vs
                // rhwp 글자색 #082108 24개). 저장값을 그대로 쓴다.
                let ul_color = color_to_svg(style.underline_color);
                let top = crate::renderer::text_decoration::underline_geometry(style, font_size);
                let multi =
                    crate::renderer::text_decoration::underline_multi_lines(style.underline_shape)
                        .filter(|_| style.underline != UnderlineType::Top);
                if let Some(top) = top {
                    self.draw_top_underline(x, y, x + text_width, &ul_color, &top, left);
                } else if let Some(lines) = multi {
                    for (dy_em, width_em) in lines {
                        let ly = y + font_size * dy_em;
                        self.output.push_str(&format!(
                        "<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"{:.2}\"/>\n",
                        x,
                        ly,
                        x + text_width,
                        ly,
                        ul_color,
                        (font_size * width_em).max(0.3),
                    ));
                    }
                } else {
                    let ul_y = match style.underline {
                        UnderlineType::Top => y - font_size + 1.0,
                        _ => {
                            y + font_size
                                * crate::renderer::text_decoration::UNDERLINE_BASELINE_RATIO
                        }
                    };
                    self.draw_line_shape(
                        x,
                        ul_y,
                        x + text_width,
                        ul_y,
                        &ul_color,
                        style.underline_shape,
                    );
                }
            }

            // 취소선 처리
            if style.strikethrough {
                let text_width = decoration_width;
                let strike_y = y - font_size * 0.3;
                let st_color = if style.strike_color != 0 {
                    color_to_svg(style.strike_color)
                } else {
                    color.to_string()
                };
                self.draw_line_shape(
                    x,
                    strike_y,
                    x + text_width,
                    strike_y,
                    &st_color,
                    style.strike_shape,
                );
            }
        }
        if let Some(geometry) = super::emphasis::geometry(text, &char_positions, style, font_size) {
            if self.font_embed_mode != FontEmbedMode::None {
                self.font_codepoints
                    .entry(geometry.font_family.to_owned())
                    .or_default()
                    .extend(geometry.browser_text.chars());
                if geometry.bold {
                    self.font_bold_families
                        .insert(geometry.font_family.to_owned());
                }
            }
            for position in &geometry.positions {
                self.output.push_str(&format!(
                    "<text transform=\"translate({} {}) matrix({} 0 {} 1 0 0)\" x=\"{}\" y=\"0\" font-family=\"{}\" font-size=\"{}\" font-weight=\"{}\" font-style=\"normal\" fill=\"{}\" text-anchor=\"{}\" xml:space=\"preserve\">{}</text>\n",
                    x + position, y + geometry.baseline_offset, geometry.ratio,
                    geometry.skew_x * geometry.ratio, geometry.browser_offset,
                    geometry.font_family, geometry.font_size, if geometry.bold { "bold" } else { "normal" },
                    color, if geometry.browser_align_end { "end" } else { "start" }, geometry.browser_text,
                ));
            }
        }

        // 탭 리더(채움 기호) 렌더링
        for leader in &style.tab_leaders {
            if leader.fill_type == 0 {
                continue;
            }
            let lx1 = x + leader.start_x;
            let leader_end_x = clamp_tab_leader_end_x(text, &char_positions, leader, font_size);
            let lx2 = x + leader_end_x;
            let ly = y - font_size * 0.35; // 글자 세로 중앙 (베이스라인에서 x-height 절반)
                                           // 채울 모양 12종: 0=없음, 1=실선, 2=파선, 3=점선, 4=일점쇄선,
                                           // 5=이점쇄선, 6=긴파선, 7=원형점선, 8=이중실선,
                                           // 9=얇고굵은이중선, 10=굵고얇은이중선, 11=얇고굵고얇은삼중선
            match leader.fill_type {
                1 => {
                    // 실선
                    self.output.push_str(&format!(
                        "<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"0.5\"/>\n",
                        lx1, ly, lx2, ly, color,
                    ));
                }
                2 => {
                    // 파선 - - -
                    self.output.push_str(&format!(
                        "<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"0.5\" stroke-dasharray=\"3 3\"/>\n",
                        lx1, ly, lx2, ly, color,
                    ));
                }
                3 => {
                    if let Some(dots) =
                        super::tab_leader::dot_geometry(font_size, leader.start_x, leader_end_x)
                    {
                        for center in dots.centers {
                            self.output.push_str(&format!(
                                "<circle cx=\"{:.6}\" cy=\"{:.6}\" r=\"{:.6}\" fill=\"{}\"/>\n",
                                x + center,
                                ly,
                                dots.radius,
                                color,
                            ));
                        }
                        continue;
                    }
                    // 점선 ··· — round cap 으로 원형 점 표현 (한컴 동등).
                    // 두께·간격은 폰트 크기를 따른다 — 고정값은 목차 점선을 가는
                    // 실선으로 보이게 했다(#5698 계열, 상수 근거는 render_tree).
                    let (w, dash, gap) = super::render_tree::tab_dot_leader_stroke(font_size);
                    self.output.push_str(&format!(
                        "<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"{:.3}\" stroke-dasharray=\"{:.3} {:.3}\" stroke-linecap=\"round\"/>\n",
                        lx1, ly, lx2, ly, color, w, dash, gap,
                    ));
                }
                4 => {
                    // 일점쇄선 -·-·
                    self.output.push_str(&format!(
                        "<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"0.5\" stroke-dasharray=\"6 2 1 2\"/>\n",
                        lx1, ly, lx2, ly, color,
                    ));
                }
                5 => {
                    // 이점쇄선 -··-··
                    self.output.push_str(&format!(
                        "<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"0.5\" stroke-dasharray=\"6 2 1 2 1 2\"/>\n",
                        lx1, ly, lx2, ly, color,
                    ));
                }
                6 => {
                    // 긴파선 ── ──
                    self.output.push_str(&format!(
                        "<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"0.5\" stroke-dasharray=\"8 4\"/>\n",
                        lx1, ly, lx2, ly, color,
                    ));
                }
                7 => {
                    // 원형점선 ●●●
                    let (w, dash, gap) = super::render_tree::tab_circle_leader_stroke();
                    self.output.push_str(&format!(
                        "<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"{:.3}\" stroke-dasharray=\"{:.3} {:.3}\" stroke-linecap=\"round\"/>\n",
                        lx1, ly, lx2, ly, color, w, dash, gap,
                    ));
                }
                8 => {
                    // 이중실선 ═══
                    self.output.push_str(&format!(
                        "<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"0.3\"/>\n\
                         <line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"0.3\"/>\n",
                        lx1, ly - 1.0, lx2, ly - 1.0, color,
                        lx1, ly + 1.0, lx2, ly + 1.0, color,
                    ));
                }
                9 => {
                    // 얇고 굵은 이중선
                    self.output.push_str(&format!(
                        "<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"0.3\"/>\n\
                         <line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"0.8\"/>\n",
                        lx1, ly - 1.2, lx2, ly - 1.2, color,
                        lx1, ly + 0.8, lx2, ly + 0.8, color,
                    ));
                }
                10 => {
                    // 굵고 얇은 이중선
                    self.output.push_str(&format!(
                        "<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"0.8\"/>\n\
                         <line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"0.3\"/>\n",
                        lx1, ly - 0.8, lx2, ly - 0.8, color,
                        lx1, ly + 1.2, lx2, ly + 1.2, color,
                    ));
                }
                11 => {
                    // 얇고 굵고 얇은 삼중선
                    self.output.push_str(&format!(
                        "<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"0.3\"/>\n\
                         <line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"0.8\"/>\n\
                         <line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"0.3\"/>\n",
                        lx1, ly - 2.0, lx2, ly - 2.0, color,
                        lx1, ly, lx2, ly, color,
                        lx1, ly + 2.0, lx2, ly + 2.0, color,
                    ));
                }
                _ => {
                    // 알 수 없는 타입: 점선 폴백
                    self.output.push_str(&format!(
                        "<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"0.5\" stroke-dasharray=\"1 2\"/>\n",
                        lx1, ly, lx2, ly, color,
                    ));
                }
            }
        }
    }

    fn draw_rect(
        &mut self,
        x: f64,
        y: f64,
        w: f64,
        h: f64,
        corner_radius: f64,
        style: &ShapeStyle,
    ) {
        self.draw_rect_with_gradient(x, y, w, h, corner_radius, style, None);
    }

    fn draw_line(&mut self, x1: f64, y1: f64, x2: f64, y2: f64, style: &LineStyle) {
        let color = color_to_svg(style.color);
        let width = if style.width > 0.0 { style.width } else { 1.0 };

        // 이중선/삼중선 처리: 여러 평행선으로 렌더링
        match style.line_type {
            super::LineRenderType::Double
            | super::LineRenderType::ThinThickDouble
            | super::LineRenderType::ThickThinDouble
            | super::LineRenderType::ThinThickThinTriple => {
                self.draw_multi_line(x1, y1, x2, y2, width, &color, &style.line_type);
                self.draw_arrow_heads(&super::arrow::line_heads((x1, y1, x2, y2), style), style);
                return;
            }
            _ => {}
        }

        let dx = x2 - x1;
        let dy = y2 - y1;
        let line_len = (dx * dx + dy * dy).sqrt();

        // Keep original endpoints, including when the head is longer than the shaft.
        let lx1 = x1;
        let ly1 = y1;
        let lx2 = x2;
        let ly2 = y2;
        let mut marker_start_attr = String::new();
        let mut marker_end_attr = String::new();

        if line_len > 0.0 {
            if style.start_arrow != super::ArrowStyle::None {
                let marker_id = self.ensure_arrow_marker(
                    &color,
                    width,
                    line_len,
                    &style.start_arrow,
                    style.start_arrow_size,
                    true,
                );
                marker_start_attr = format!(" marker-start=\"url(#{})\"", marker_id);
            }
            if style.end_arrow != super::ArrowStyle::None {
                let marker_id = self.ensure_arrow_marker(
                    &color,
                    width,
                    line_len,
                    &style.end_arrow,
                    style.end_arrow_size,
                    false,
                );
                marker_end_attr = format!(" marker-end=\"url(#{})\"", marker_id);
            }
        }

        let mut attrs = format!(
            "x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"{}\" stroke-width=\"{}\"",
            lx1, ly1, lx2, ly2, color, width,
        );
        if self.axis_stroke_hint_allowed
            && !style.preserve_fractional_position
            && style.dash_pattern.is_none()
        {
            let source = super::render_tree::LineNode::new(x1, y1, x2, y2, style.clone());
            let raster = super::raster_stroke::raster_line_geometry(
                &source,
                [1.0, 0.0, 0.0, 1.0, 0.0, 0.0],
                self.profile,
                width,
            );
            if raster.4 > width {
                // 원본 벡터 좌표·선폭은 그대로 두고 Print의 가는 직교선에만
                // 브라우저의 장치 픽셀 coverage 처리를 요청한다.
                attrs.push_str(" shape-rendering=\"crispEdges\"");
            }
        }
        if let Some(intervals) = &style.dash_pattern {
            attrs.push_str(&format!(
                " stroke-dasharray=\"{}\"",
                intervals
                    .iter()
                    .map(|v| v.to_string())
                    .collect::<Vec<_>>()
                    .join(" ")
            ));
        } else {
            stroke_pattern::append_attrs(&mut attrs, style.dash, width);
        }
        attrs.push_str(&marker_start_attr);
        attrs.push_str(&marker_end_attr);
        self.output.push_str(&format!("<line {}/>\n", attrs));
    }

    fn draw_ellipse(&mut self, cx: f64, cy: f64, rx: f64, ry: f64, style: &ShapeStyle) {
        self.draw_ellipse_with_gradient(cx, cy, rx, ry, style, None);
    }

    fn draw_image(&mut self, data: &[u8], x: f64, y: f64, w: f64, h: f64) {
        let mime_type = detect_image_mime_type(data);
        let (render_data, render_mime): (std::borrow::Cow<[u8]>, &str) =
            if mime_type == "image/x-wmf" {
                match convert_wmf_to_svg(data) {
                    Some(svg_bytes) => (std::borrow::Cow::Owned(svg_bytes), "image/svg+xml"),
                    None => (std::borrow::Cow::Borrowed(data), mime_type),
                }
            } else if mime_type == "image/x-emf" {
                match crate::emf::convert_to_standalone_svg(data) {
                    Some(svg_bytes) => (std::borrow::Cow::Owned(svg_bytes), "image/svg+xml"),
                    None => (std::borrow::Cow::Borrowed(data), mime_type),
                }
            } else if mime_type == "image/x-pcx" {
                match pcx_bytes_to_png_bytes(data) {
                    Some(png_bytes) => (std::borrow::Cow::Owned(png_bytes), "image/png"),
                    None => (std::borrow::Cow::Borrowed(data), mime_type),
                }
            } else if mime_type == "image/bmp" {
                match bmp_bytes_to_png_bytes(data) {
                    Some(png_bytes) => (std::borrow::Cow::Owned(png_bytes), "image/png"),
                    None => (std::borrow::Cow::Borrowed(data), mime_type),
                }
            } else if mime_type == "image/tiff" {
                match tiff_bytes_to_png_bytes(data) {
                    Some(png_bytes) => (std::borrow::Cow::Owned(png_bytes), "image/png"),
                    None => (std::borrow::Cow::Borrowed(data), mime_type),
                }
            } else if mime_type == "application/postscript" {
                match crate::renderer::image_resolver::eps_renderable_bytes(data) {
                    Some((mime, bytes)) => (std::borrow::Cow::Owned(bytes), mime),
                    None => (std::borrow::Cow::Borrowed(data), mime_type),
                }
            } else {
                (std::borrow::Cow::Borrowed(data), mime_type)
            };
        let base64_data = base64::engine::general_purpose::STANDARD.encode(&*render_data);
        let data_uri = format!("data:{};base64,{}", render_mime, base64_data);
        self.output.push_str(&format!(
            "<image x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" preserveAspectRatio=\"none\" href=\"{}\"/>\n",
            x, y, w, h, data_uri,
        ));
    }

    fn draw_path(&mut self, commands: &[PathCommand], style: &ShapeStyle) {
        self.draw_path_with_gradient(commands, style, None);
    }
}

/// [#6845] 패스 명령이 지나는 점들의 외접 상자.
///
/// 그러데이션 축을 사용자 좌표계로 내려면 도형의 치수가 필요한데, 패스는 사각형·타원과
/// 달리 호출부가 상자를 들고 있지 않다. 곡선 제어점까지 포함한 근사 상자로 충분하다 —
/// 축은 상자를 덮기만 하면 되고, 램프의 기울기는 각도가 정한다.
fn path_bbox(commands: &[PathCommand]) -> (f64, f64, f64, f64) {
    let (mut min_x, mut min_y) = (f64::INFINITY, f64::INFINITY);
    let (mut max_x, mut max_y) = (f64::NEG_INFINITY, f64::NEG_INFINITY);
    let mut see = |x: f64, y: f64| {
        min_x = min_x.min(x);
        min_y = min_y.min(y);
        max_x = max_x.max(x);
        max_y = max_y.max(y);
    };
    for cmd in commands {
        match *cmd {
            PathCommand::MoveTo(x, y) | PathCommand::LineTo(x, y) => see(x, y),
            PathCommand::CurveTo(x1, y1, x2, y2, x, y) => {
                see(x1, y1);
                see(x2, y2);
                see(x, y);
            }
            PathCommand::ArcTo(_, _, _, _, _, x, y) => see(x, y),
            PathCommand::ClosePath => {}
        }
    }
    if min_x.is_finite() && min_y.is_finite() && max_x > min_x && max_y > min_y {
        (min_x, min_y, max_x - min_x, max_y - min_y)
    } else {
        // 점 하나뿐이거나 한 축이 0 인 패스 — 정규화 공간 폴백으로 넘긴다.
        (0.0, 0.0, 0.0, 0.0)
    }
}

/// `fill` 과 같은 색으로 합성 볼드 획을 준다 — PDF `2 Tr` 과 같은 채움 후 획.
fn faux_bold_stroke_attr(width: f64, fill: &str) -> String {
    format!(" stroke=\"{}\" stroke-width=\"{:.3}\"", fill, width)
}

fn color_to_svg(color: u32) -> String {
    let b = (color >> 16) & 0xFF;
    let g = (color >> 8) & 0xFF;
    let r = color & 0xFF;
    format!("#{:02x}{:02x}{:02x}", r, g, b)
}

fn svg_text_length_attrs(
    cluster_str: &str,
    cluster_advance: f64,
    scale_x: f64,
    fit_narrow_hangul: bool,
) -> String {
    if !fit_narrow_hangul
        && !cluster_str.chars().any(|ch| {
            ch.is_ascii_alphanumeric()
                    || is_halfwidth_cjk_quote(ch)
                    // PUA 책괄호의 반각 원본 전진과 리터럴 전각 흰 겹낫표는
                    // 같은 표시 Unicode라도 각자의 측정 결과에 맞춰 그린다.
                    || matches!(ch, '\u{300E}' | '\u{300F}')
        })
    {
        return String::new();
    }
    if !cluster_advance.is_finite() || cluster_advance <= 0.0 {
        return String::new();
    }
    let scale_x = if scale_x.is_finite() && scale_x.abs() > 0.0001 {
        scale_x.abs()
    } else {
        1.0
    };
    let text_length = cluster_advance / scale_x;
    format!(
        " textLength=\"{:.4}\" lengthAdjust=\"spacingAndGlyphs\"",
        text_length
    )
}

fn svg_cluster_text_length_attrs(
    cluster_str: &str,
    layout_cluster_advance: f64,
    style: &TextStyle,
    script_advance_scale: f64,
    scale_x: f64,
) -> String {
    let Some(glyph_advance) = style.glyph_fit_advance(layout_cluster_advance) else {
        return String::new();
    };
    // Proportional Hangul metrics can be much narrower than the browser fallback.
    // Fit without moving origins; uniform Hangul metrics may also be below one em.
    let mut chars = cluster_str.chars();
    let fit_narrow_hangul = chars.next().is_some_and(|ch| {
        ('\u{ac00}'..='\u{d7a3}').contains(&ch)
            && chars.next().is_none()
            && style.letter_spacing == 0.0
            && super::font_metrics_data::find_metric(
                style
                    .font_family
                    .split(',')
                    .next()
                    .unwrap_or("")
                    .trim()
                    .trim_matches('\''),
                style.is_visually_bold(),
                style.italic,
            )
            .is_some_and(|found| {
                found.metric.get_width(ch).is_some_and(|width| {
                    width > 0
                        && width < found.metric.em_size
                        && found.metric.hangul.is_some_and(|hangul| {
                            hangul
                                .widths
                                .iter()
                                .any(|&other| other > 0 && other != width)
                        })
                })
            })
    });
    svg_text_length_attrs(
        cluster_str,
        glyph_advance * script_advance_scale,
        scale_x,
        fit_narrow_hangul,
    )
}

/// XML 특수문자 이스케이프
fn escape_xml(s: &str) -> String {
    let mut result = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '&' => result.push_str("&amp;"),
            '<' => result.push_str("&lt;"),
            '>' => result.push_str("&gt;"),
            '"' => result.push_str("&quot;"),
            '\'' => result.push_str("&apos;"),
            // XML 1.0 허용 문자: #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
            // 그 외(제어문자, U+FFFE, U+FFFF 등)는 제거
            '\u{09}' | '\u{0A}' | '\u{0D}' => result.push(c),
            '\u{20}'..='\u{D7FF}' | '\u{E000}'..='\u{FFFD}' | '\u{10000}'..='\u{10FFFF}' => {
                result.push(c)
            }
            _ => {} // XML 무효 문자 제거
        }
    }
    result
}

/// WMF 바이트를 SVG로 변환한다. 실패 시 None 반환.
pub(crate) fn convert_wmf_to_svg(data: &[u8]) -> Option<Vec<u8>> {
    use crate::wmf::converter::{SVGPlayer, WMFConverter};
    let player = SVGPlayer::new();
    let converter = WMFConverter::new(data, player);
    let fallback = converter.run().ok()?;
    // 표준 WMFC만 복원한다. 알 수 없는 escape나 불완전한 EMF+를 부분 표시하지 않는다.
    if let Some(emf) = crate::parser::ole_container::emf_from_wmf_comment_chunks(data) {
        if let Some(viewport) = super::metafile_geometry::svg_viewport(&fallback) {
            if let Some(svg) = crate::emf::emfplus::convert_supported(&emf, viewport) {
                return Some(svg);
            }
        }
    }
    Some(fallback)
}

/// A source-pixel difference is real content, even when it is only one pixel.
/// In a two-pixel pattern tile it can select half the image. Compare the source
/// window itself; display scale and pixel rounding do not erase that selection.
pub(crate) fn image_source_is_full(source: (f64, f64, f64, f64), width: f64, height: f64) -> bool {
    source == (0.0, 0.0, width, height)
}

/// 이미지 데이터에서 픽셀 크기(width, height)를 파싱한다.
/// HWP `pic.crop` 좌표로부터 SVG `viewBox` 에 쓸 원본 픽셀 단위
/// source rect (x, y, w, h) 를 계산한다.
///
/// `crop_reference_size`(`imgDim`)가 있으면 문서가 보존한 전체 좌표 범위를
/// 디코딩 이미지 크기에 대응시킨다. 없으면 zero-origin 끝점의 후보를
/// 같은 등방 단위로 환산한다(적응 폴백) — imgDim 을
/// 보존하지 않는 구형 HWP5 의 비-96dpi 스캔 그림은 crop 단위가 75 HU/px 가
/// 아니어서, 고정 75 룰은 src 를 과소 계산해 그림을 확대·절단한다(#3239).
/// 둘 다 쓸 수 없을 때만 [Task #477] 표준 75 HU/px 를 쓴다.
/// `shape_attr.orgSz`는 개체 크기라서 crop 좌표 기준으로 사용하면 안 된다.
pub(crate) fn compute_image_crop_src(
    crop_hu: (i32, i32, i32, i32),
    crop_reference_size: Option<(u32, u32)>,
    img_w_px: f64,
    img_h_px: f64,
) -> (f64, f64, f64, f64) {
    let (cl, ct, cr, cb) = crop_hu;
    // 원본 좌표가 전체 영역과 같다면 실수 환산 오차로 잘림으로 판정하지 않는다.
    // 실제 가장자리 자르기는 원본 단위에서 구별해 그대로 환산한다.
    if let Some((width, height)) = crop_reference_size {
        if width > 0
            && height > 0
            && img_w_px.is_finite()
            && img_w_px > 0.0
            && img_h_px.is_finite()
            && img_h_px > 0.0
            && cl == 0
            && ct == 0
            && i64::from(cr) == i64::from(width)
            && i64::from(cb) == i64::from(height)
        {
            return (0.0, 0.0, img_w_px, img_h_px);
        }
    }
    const HU_PER_PX: f64 = 75.0;
    let (scale_x, scale_y) = crop_reference_size
        .filter(|(w, h)| *w > 0 && *h > 0 && img_w_px > 0.0 && img_h_px > 0.0)
        .map(|(w, h)| (w as f64 / img_w_px, h as f64 / img_h_px))
        .filter(|(sx, sy)| sx.is_finite() && sy.is_finite() && *sx > 0.0 && *sy > 0.0)
        .or_else(|| {
            // A zero start does not establish that the opposite edge is the full
            // image extent: right/bottom-only cropping also starts at zero.
            // Without an explicit reference, HWPUNIT coordinates must retain one
            // isotropic scale. Use the smallest common scale which fits the
            // available zero-origin extents in the decoded image. Independent
            // axis scales would expand a shortened edge back to the full image.
            // Nonzero starts do not provide a full-extent candidate (#7015).
            // If neither axis provides one, retain the standard 75 HU/px fallback.
            let axis_scale = |crop_start: i32, crop_end: i32, img_px: f64| {
                (crop_start == 0 && crop_end > 0 && img_px > 0.0)
                    .then(|| crop_end as f64 / img_px)
                    .filter(|scale| scale.is_finite() && *scale > 0.0)
            };
            match (axis_scale(cl, cr, img_w_px), axis_scale(ct, cb, img_h_px)) {
                (Some(sx), Some(sy)) => {
                    let scale = sx.max(sy);
                    Some((scale, scale))
                }
                (Some(scale), None) | (None, Some(scale)) => Some((scale, scale)),
                (None, None) => None,
            }
        })
        .unwrap_or((HU_PER_PX, HU_PER_PX));
    let src_x = cl as f64 / scale_x;
    let src_y = ct as f64 / scale_y;
    let src_w = (cr - cl) as f64 / scale_x;
    let src_h = (cb - ct) as f64 / scale_y;
    (src_x, src_y, src_w, src_h)
}

pub(crate) fn parse_image_dimensions(data: &[u8]) -> Option<(u32, u32)> {
    if data.len() < 24 {
        return None;
    }

    // PNG: IHDR 청크에서 크기 읽기 (바이트 16-23)
    if data.starts_with(&[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]) {
        let w = u32::from_be_bytes([data[16], data[17], data[18], data[19]]);
        let h = u32::from_be_bytes([data[20], data[21], data[22], data[23]]);
        return Some((w, h));
    }

    // JPEG: SOF 마커에서 크기 읽기
    if data.starts_with(&[0xFF, 0xD8, 0xFF]) {
        let mut i = 2;
        while i + 9 < data.len() {
            if data[i] != 0xFF {
                i += 1;
                continue;
            }
            let marker = data[i + 1];
            // SOF0-SOF3 (0xC0-0xC3), SOF5-SOF7 (0xC5-0xC7),
            // SOF9-SOF11 (0xC9-0xCB), SOF13-SOF15 (0xCD-0xCF)
            if (marker >= 0xC0 && marker <= 0xCF)
                && marker != 0xC4
                && marker != 0xC8
                && marker != 0xCC
            {
                let h = u16::from_be_bytes([data[i + 5], data[i + 6]]) as u32;
                let w = u16::from_be_bytes([data[i + 7], data[i + 8]]) as u32;
                if w > 0 && h > 0 {
                    return Some((w, h));
                }
            }
            let seg_len = u16::from_be_bytes([data[i + 2], data[i + 3]]) as usize;
            i += 2 + seg_len;
        }
        return None;
    }

    // GIF: 바이트 6-9
    if data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a") {
        let w = u16::from_le_bytes([data[6], data[7]]) as u32;
        let h = u16::from_le_bytes([data[8], data[9]]) as u32;
        return Some((w, h));
    }

    // BMP: 바이트 18-25
    if data.starts_with(&[0x42, 0x4D]) && data.len() >= 26 {
        let w = u32::from_le_bytes([data[18], data[19], data[20], data[21]]);
        let h = i32::from_le_bytes([data[22], data[23], data[24], data[25]]);
        return Some((w, h.unsigned_abs()));
    }

    super::svg_fragment::svg_intrinsic_pixel_dimensions(data)
}

/// 폰트명 → local() 별칭 매핑 (한글명 + 영문명)
fn font_local_aliases(font_family: &str) -> Vec<&'static str> {
    match font_family {
        // 설치 파일의 한글 family와 영문 이름은 같은 나눔고딕 프로그램이다.
        "나눔고딕" | "NanumGothic" => vec!["나눔고딕", "NanumGothic"],
        "함초롬바탕" => vec!["함초롬바탕", "HCR Batang"],
        "함초롬돋움" => vec!["함초롬돋움", "HCR Dotum"],
        "함초롱바탕" => vec!["함초롱바탕", "HCR Batang"],
        "함초롱돋움" => vec!["함초롱돋움", "HCR Dotum"],
        "한컴바탕" => vec!["한컴바탕", "Haansoft Batang"],
        "한컴돋움" => vec!["Haansoft Dotum", "한컴돋움", "함초롬돋움", "HCR Dotum"],
        // 설치본의 한글 family와 영문 full name을 함께 연결한다.
        "한컴 고딕" | "Hancom Gothic" => {
            vec!["한컴 고딕", "Hancom Gothic", "Hancom Gothic Regular"]
        }
        "한컴 윤고딕 240" | "Haan YGodic 240" => {
            vec!["한컴 윤고딕 240", "Haan YGodic 240"]
        }
        "한컴 윤고딕 250" | "Haan YGodic 250" => {
            vec!["한컴 윤고딕 250", "Haan YGodic 250"]
        }
        "맑은 고딕" => vec!["맑은 고딕", "Malgun Gothic"],
        "바탕" => vec!["바탕", "Batang"],
        "돋움" => vec!["돋움", "Dotum"],
        "돋움체" | "DotumChe" => vec!["돋움체", "DotumChe"],
        "굴림" => vec!["굴림", "Gulim"],
        "굴림체" => vec!["굴림체", "GulimChe"],
        "바탕체" => vec!["바탕체", "BatangChe"],
        "궁서" => vec!["궁서", "Gungsuh"],
        "궁서체" => vec!["궁서체", "GungsuhChe"],
        // 원본 한양중고딕의 outline 프로그램을 먼저 공급한다. 한컴 버전만으로
        // HCR 대체를 가정하면 HFT 선언과 Type3 출력의 획·폭을 바꾸게 된다.
        // 명시 대체는 FontEnvironment가 결정하며 HCR은 원 face 부재 시 폴백이다.
        "한양중고딕" => vec![
            "한양중고딕",
            "HY중고딕",
            "HYGothic-Medium",
            "HCR Dotum",
            "함초롬돋움",
        ],
        "HY중고딕" => vec!["HY중고딕", "HYGothic-Medium"],
        // HMKMM.TTF 같은 legacy 휴먼명조 배포본은 EBDT bitmap strike를 포함하며,
        // Blink/Chrome이 local face를 선택하고도 표준 한글을 .notdef(□)로 그릴 수 있다.
        // SVG 좌표는 이미 조판 결과로 고정되어 있으므로 portable outline serif를 먼저
        // 선택하고, native face는 해당 환경에서 대체글꼴이 없을 때만 마지막에 시도한다.
        "휴먼명조" => vec![
            // 한컴 2020 PDF가 이 legacy face를 HCR Batang으로 출력한다. HMKMM을
            // 선택하면 EBDT와 한컴 출력 폭 차이가 함께 발생하므로 HCR을 첫 후보로 둔다.
            "HCR Batang",
            "함초롬바탕",
            "Batang",
            "바탕",
            "AppleMyungjo",
            "Noto Serif CJK KR",
            "휴먼명조",
            "HumanMyeongJo",
        ],
        // HMKMG.TTF도 HMKMM과 같은 EBDT 혼합 배포본이며 Chrome에서 local face를
        // 선택한 뒤 표준 한글을 전부 .notdef로 그리는 것이 확인됐다. style SVG의
        // 고정 좌표는 유지하고 outline sans를 먼저 사용한다.
        "휴먼고딕" => vec![
            "Malgun Gothic",
            "맑은 고딕",
            "Apple SD Gothic Neo",
            "Noto Sans KR ExtraLight",
            "Noto Sans KR",
            "Pretendard",
            "휴먼고딕",
        ],
        // H2MJSM.TTF의 실제 family/full name은 아래 두 이름이며 정상 outline이다.
        // 휴먼명조의 EBDT 문제를 이 face까지 확대해 원 글꼴 fidelity를 잃지 않는다.
        "한양신명조" => vec!["한양신명조", "HY신명조", "HYSinMyeongJo-Medium"],
        "HY신명조" => vec!["HY신명조", "HYSinMyeongJo-Medium"],
        // [#6171] H2GTRE.TTF / H2MJRE.TTF 도 한양신명조와 같은 정상 outline 배포본이라
        // 원 face 를 먼저 쓴다. arm 이 없어 `vec![]` 를 돌려주던 탓에 `@font-face` src 가
        // `local("한양견고딕")` 한 줄이 되어, 레지스트리에 `HY견고딕`으로 등록된 설치본을
        // 찾지 못했다. family/full name 은 Windows 글꼴 실측(H2GTRE.TTF=`HYGothic-Extra`,
        // H2MJRE.TTF=`HYMyeongJo-Extra`).
        "한양견고딕" => vec!["한양견고딕", "HY견고딕", "HYGothic-Extra"],
        "HY견고딕" => vec!["HY견고딕", "HYGothic-Extra"],
        "한양견명조" => vec!["한양견명조", "HY견명조", "HYMyeongJo-Extra"],
        "HY견명조" => vec!["HY견명조", "HYMyeongJo-Extra"],
        _ => vec![],
    }
}

/// 폰트명 → 실제 Bold face의 local() 별칭.
///
/// `@font-face`를 원 family명으로 다시 선언하는 SVG 경로에서는 CSS의
/// `font-weight="bold"`만으로 시스템의 sibling bold face를 자동 선택하지 못한다.
/// 한컴 2020 PDF가 쓴 full name을 명시해 synthetic bold를 피한다.
fn font_local_bold_aliases(font_family: &str) -> Vec<&'static str> {
    match font_family {
        "나눔고딕" | "NanumGothic" => vec!["NanumGothicBold", "나눔고딕 Bold"],
        "한컴바탕" | "Haansoft Batang" => vec!["Haansoft Batang Bold"],
        "함초롬바탕" | "함초롱바탕" | "휴먼명조" => {
            vec!["HCR Batang Bold", "함초롬바탕 Bold"]
        }
        "함초롬돋움" | "함초롱돋움" | "한컴돋움" | "한양중고딕" | "HY중고딕" =>
        {
            vec!["HCR Dotum Bold", "함초롬돋움 Bold"]
        }
        "한컴 고딕" | "Hancom Gothic" => vec!["Hancom Gothic Bold", "한컴 고딕 Bold"],
        "맑은 고딕" | "Malgun Gothic" => vec!["Malgun Gothic Bold", "맑은 고딕 Bold"],
        _ => vec![],
    }
}

/// 폰트명 → 알려진 파일명 매핑 (HWP/한컴/MS 폰트)
fn known_font_filenames(font_name: &str) -> Vec<&'static str> {
    match font_name {
        // 기존 KoPub의 name table에 있는 한글/영문 face와 실제 배포
        // 파일명을 연결한다. KoPub World는 별도 family이므로 포함하지 않는다.
        "KoPub돋움체"
        | "KoPubDotum"
        | "KoPub Dotum"
        | "KoPub돋움체 Light"
        | "KoPubDotum Light"
        | "KoPub Dotum Light"
        | "KoPubDotumLight" => vec![
            "KoPub Dotum Light.ttf",
            "KoPubDotum-Light.ttf",
            "KoPubDotumLight.ttf",
        ],
        "KoPub돋움체 Medium" | "KoPubDotum Medium" | "KoPub Dotum Medium" | "KoPubDotumMedium" =>
        {
            vec![
                "KoPub Dotum Medium.ttf",
                "KoPubDotum-Medium.ttf",
                "KoPubDotumMedium.ttf",
            ]
        }
        "KoPub돋움체 Bold" | "KoPubDotum Bold" | "KoPub Dotum Bold" | "KoPubDotumBold" => {
            vec![
                "KoPub Dotum Bold.ttf",
                "KoPubDotum-Bold.ttf",
                "KoPubDotumBold.ttf",
            ]
        }
        "KoPub바탕체"
        | "KoPubBatang"
        | "KoPub Batang"
        | "KoPub바탕체 Light"
        | "KoPubBatang Light"
        | "KoPub Batang Light"
        | "KoPubBatangLight" => vec![
            "KoPub Batang Light.ttf",
            "KoPubBatang-Light.ttf",
            "KoPubBatangLight.ttf",
        ],
        "KoPub바탕체 Medium"
        | "KoPubBatang Medium"
        | "KoPub Batang Medium"
        | "KoPubBatangMedium" => vec![
            "KoPub Batang Medium.ttf",
            "KoPubBatang-Medium.ttf",
            "KoPubBatangMedium.ttf",
        ],
        "KoPub바탕체 Bold" | "KoPubBatang Bold" | "KoPub Batang Bold" | "KoPubBatangBold" => {
            vec![
                "KoPub Batang Bold.ttf",
                "KoPubBatang-Bold.ttf",
                "KoPubBatangBold.ttf",
            ]
        }
        "나눔고딕" | "NanumGothic" => vec!["NanumGothic.ttf"],
        // 실제 설치 face가 있어도 파일명 누락으로 Noto를 원 family에 내장하지 않는다.
        "한컴 고딕" | "Hancom Gothic" => vec!["Hancom Gothic Regular.ttf"],
        // 한컴 PDF의 함초롬바탕은 HCR Batang이다. HBATANG.TTF는 다른
        // Haansoft Batang이므로 HCR 설치 파일을 먼저 찾는다 (#7265 시각 대조).
        "함초롬바탕" | "함초롱바탕" => {
            vec!["HANBatang.ttf", "hamchob-r.ttf", "HBATANG.TTF"]
        }
        // 이름 테이블에서 확인한 영문 face도 실제 설치 파일을 찾는다.
        // HCR과 Haansoft는 다른 글꼴이므로 서로의 파일로 대신하지 않는다.
        "HCR Batang" => vec!["HANBatang.ttf", "hamchob-r.ttf"],
        "HCR Dotum" => vec!["HANDotum.ttf", "hamchod-r.ttf"],
        "Haansoft Batang" => vec!["HBATANG.TTF"],
        "Haansoft Dotum" => vec!["HDOTUM.TTF"],
        "한컴바탕" => vec!["HBATANG.TTF"],
        "함초롬돋움" | "함초롱돋움" | "한컴돋움" => {
            vec!["hamchod-r.ttf", "HDOTUM.TTF"]
        }
        "HY헤드라인M" | "HYHeadLine M" => vec!["H2HDRM.TTF"],
        "HY중고딕" | "HYGothic-Medium" => vec!["H2GTRM.TTF"],
        // 한컴 Windows 설치본의 이름 테이블은 한글 face와 아래 파일명을
        // 연결한다. 실제 face를 공급해도 영문 파일명 때문에 대체 글꼴을 고르면 안 된다.
        "한컴 윤고딕 230" | "Haan YGodic 230" => vec!["HANYGO230.ttf"],
        "한컴 윤고딕 240" | "Haan YGodic 240" => vec!["HANYGO240.ttf"],
        "한컴 윤고딕 250" | "Haan YGodic 250" => vec!["HANYGO250.ttf"],
        // local()와 Full embed는 같은 원본 프로그램 우선순위를 사용한다.
        "한양중고딕" => vec!["H2GTRM.TTF", "HANDotum.ttf", "HDOTUM.TTF"],
        // [#6171] 한컴 Windows 설치본의 실제 파일명은 형제 항목(H2GTRM/H2MJSM)과 같은
        // `H2*` 계열이다 — Windows 글꼴 레지스트리 실측:
        //   HY견고딕 → H2GTRE.TTF(family `HYGothic-Extra`)
        //   HY견명조 → H2MJRE.TTF(family `HYMyeongJo-Extra`)
        // 종전의 `HYGTRE.TTF`·`HYMJRE.TTF` 는 이 PC 에 존재하지 않아 full embed 가
        // 매번 실패했다. 다른 배포본에 그 이름이 있을 수 있으므로 뒤 후보로 남긴다.
        "HY견고딕" | "HYGothic-Extra" | "한양견고딕" => vec!["H2GTRE.TTF", "HYGTRE.TTF"],
        "HY그래픽" | "HYGraphic-Medium" => vec!["HYGPRM.TTF"],
        "HY견명조" | "HYMyeongJo-Extra" | "한양견명조" => vec!["H2MJRE.TTF", "HYMJRE.TTF"],
        // [#2430] 한양신명조: 종전 HY신명조 치환과 동일 임베드 유지.
        // (휴먼명조는 아래 기존 전용 arm 이 담당)
        "HY신명조" | "한양신명조" => {
            vec!["H2MJSM.TTF", "HYSNMJ.TTF", "hamchob-r.ttf"]
        }
        "HyhwpEQ" | "HYhwpEQ" => vec!["HYHWPEQ.TTF", "hyhwpeq.ttf"],
        "Latin Modern Math" => vec![
            "latinmodern-math.otf",
            "LatinModernMath-Regular.otf",
            "lmmath-regular.otf",
        ],
        // Windows의 실제 파일명으로 영문 face를 찾아 Full 출력에 공급한다.
        "Palatino Linotype" => vec!["pala.ttf"],
        "맑은 고딕" | "Malgun Gothic" => vec!["malgun.ttf", "MalgunGothic.ttf"],
        "바탕" | "Batang" => vec!["batang.ttc", "BATANG.TTC", "hamchob-r.ttf"],
        "돋움" | "Dotum" => vec![
            "dotum.ttc",
            "DOTUM.TTC",
            "gulim.ttc",
            "GULIM.TTC",
            "hamchod-r.ttf",
        ],
        "돋움체" | "DotumChe" => vec!["gulim.ttc", "GULIM.TTC", "dotum.ttc", "DOTUM.TTC"],
        "굴림" | "Gulim" => vec!["gulim.ttc", "GULIM.TTC", "hamchod-r.ttf"],
        "궁서" | "Gungsuh" => vec!["gungsuh.ttc", "GUNGSUH.TTC", "hamchob-r.ttf"],
        "굴림체" | "GulimChe" => vec!["gulim.ttc", "hamchod-r.ttf"],
        "바탕체" | "BatangChe" => vec!["batang.ttc", "hamchob-r.ttf"],
        // 정상 Windows 한컴 출력의 원 face는 휴먼명조다. EBDT 혼합 배포본도
        // 임베드 사본에서 outline을 보존하므로 원 face를 대체 face보다 먼저 찾는다.
        "휴먼명조" | "HumanMyeongJo" => {
            vec!["HMKMM.TTF", "HANBatang.ttf", "HBATANG.TTF", "hamchob-r.ttf"]
        }
        // 휴먼고딕도 원본 윤곽선을 공급한다. EBDT 혼합 파일은 공통 임베드
        // 정규화가 비트맵 strike만 제외하므로 local 대체 글꼴로 바꿀 필요가 없다.
        "휴먼고딕" | "HumanGothic" => vec!["HMKMG.TTF"],
        "새바탕" | "새돋움" | "새굴림" | "새궁서" => {
            vec!["hamchob-r.ttf", "hamchod-r.ttf"]
        }
        _ => vec![],
    }
}

/// 폰트명 → 한컴 2020 출력과 대응되는 Bold TTF 후보.
///
/// regular 파일에 CSS `font-weight: bold`를 적용하면 Blink가 합성 굵기를 만든다.
/// HWP 2020 PDF는 HCR의 실제 Bold face를 내장하므로, portable SVG도 같은 face를
/// 별도 선언해야 글리프 폭과 획 두께가 유지된다.
fn known_bold_font_filenames(font_name: &str) -> Vec<&'static str> {
    match font_name {
        "KoPub돋움체"
        | "KoPubDotum"
        | "KoPub Dotum"
        | "KoPub돋움체 Bold"
        | "KoPubDotum Bold"
        | "KoPub Dotum Bold"
        | "KoPubDotumBold" => vec![
            "KoPub Dotum Bold.ttf",
            "KoPubDotum-Bold.ttf",
            "KoPubDotumBold.ttf",
        ],
        "KoPub바탕체"
        | "KoPubBatang"
        | "KoPub Batang"
        | "KoPub바탕체 Bold"
        | "KoPubBatang Bold"
        | "KoPub Batang Bold"
        | "KoPubBatangBold" => vec![
            "KoPub Batang Bold.ttf",
            "KoPubBatang-Bold.ttf",
            "KoPubBatangBold.ttf",
        ],
        "나눔고딕" | "NanumGothic" => vec!["NanumGothicBold.ttf"],
        "한컴 고딕" | "Hancom Gothic" => vec!["Hancom Gothic Bold.ttf"],
        "한컴바탕" | "Haansoft Batang" => vec!["HBATANGB.TTF"],
        "함초롬바탕" | "함초롱바탕" | "휴먼명조" => {
            vec!["HANBatangB.ttf", "HBATANGB.TTF"]
        }
        "함초롬돋움" | "함초롱돋움" | "한컴돋움" | "한양중고딕" | "HY중고딕" =>
        {
            vec!["HANDotumB.ttf", "HDOTUMB.TTF", "H2GTRB.TTF"]
        }
        "Palatino Linotype" => vec!["palab.ttf"],
        "맑은 고딕" | "Malgun Gothic" => vec!["malgunbd.ttf", "MalgunGothicBold.ttf"],
        _ => vec![],
    }
}

/// Task #1224: 한국어 고딕(돋움/고딕/굴림) 계열의 오픈소스 대체 폰트 파일명.
///
/// 한컴/MS 저작권 고딕(한컴돋움·Haansoft Dotum·맑은 고딕·돋움·굴림 등) 파일 부재 시
/// 임베딩의 **최후 후보**로 사용한다. 현 폴백(Noto Sans CJK KR Regular)은 한컴 돋움보다
/// 획이 +43% 두꺼워(페이지 밀도 0.378 vs 0.265) 본문이 과도하게 굵게 렌더되므로, 획 두께가
/// 한컴 돋움에 근접한 Noto Sans KR ExtraLight(rsvg 페이지 밀도 0.277)로 교정한다
/// (`ttfs/opensource/`).
///
/// serif(바탕/명조/궁서)·라틴 폰트에는 적용하지 않는다(시각 정합과 무관). 실제 저작권
/// 폰트가 탐색 경로에 있으면 그쪽이 우선한다(대체는 탐색 경로 말단의 `ttfs/opensource/`).
///
/// SVG 부분집합은 Unicode cmap과 웹 조판 정보를 보존한다. 설치된 원 프로그램과
/// 최후 후보의 선택 순서는 부분집합 생성 여부와 별개다.
#[cfg(not(target_arch = "wasm32"))]
fn korean_gothic_substitute(font_name: &str) -> Option<&'static str> {
    let lower = font_name.to_ascii_lowercase();
    let is_gothic = font_name.contains("돋움")
        || font_name.contains("고딕")
        || font_name.contains("굴림")
        || lower.contains("dotum")
        || lower.contains("gothic")
        || lower.contains("gulim");
    if is_gothic {
        Some("NotoSansKR-ExtraLight.ttf")
    } else {
        None
    }
}

/// 형식4 cmap의 마지막 비문자 U+FFFF가 잘못된 글리프 번호를 가리키면
/// 임베드 사본에서만 missingGlyph로 연결한다. 정상 문자·유효한 종료 매핑은 보존한다.
/// OpenType cmap 사양: https://learn.microsoft.com/en-us/typography/opentype/spec/cmap
fn svg_cmap_terminal_missing_glyph(data: &[u8], glyph_count: u16) -> std::borrow::Cow<'_, [u8]> {
    let read = |offset: usize| {
        data.get(offset..offset.checked_add(2)?)
            .map(|bytes| u16::from_be_bytes(bytes.try_into().unwrap()))
    };
    let Some(count) = read(2).filter(|_| read(0) == Some(0)) else {
        return std::borrow::Cow::Borrowed(data);
    };
    let mut repaired = None;
    for index in 0..usize::from(count) {
        let record = 4 + index * 8;
        let Some(bytes) = data.get(record + 4..record + 8) else {
            return std::borrow::Cow::Borrowed(data);
        };
        let offset = u32::from_be_bytes(bytes.try_into().unwrap()) as usize;
        if read(offset) != Some(4) {
            continue;
        }
        let Some(length) = offset.checked_add(2).and_then(read).map(usize::from) else {
            continue;
        };
        let Some(segments) = offset
            .checked_add(6)
            .and_then(read)
            .filter(|n| *n > 0 && n % 2 == 0)
        else {
            continue;
        };
        let segments = usize::from(segments) / 2;
        let Some(subtable) = offset
            .checked_add(length)
            .and_then(|end| data.get(offset..end))
        else {
            continue;
        };
        if subtable.len() < 16 + segments * 8 {
            continue;
        }
        let end_code = offset + 14 + (segments - 1) * 2;
        let start_code = end_code + segments * 2 + 2;
        let delta = start_code + segments * 2;
        let range_offset = delta + segments * 2;
        if read(end_code) == Some(u16::MAX)
            && read(start_code) == Some(u16::MAX)
            && read(range_offset) == Some(0)
            && read(delta).is_some_and(|d| u16::MAX.wrapping_add(d) >= glyph_count)
        {
            let copy = repaired.get_or_insert_with(|| data.to_vec());
            // U+FFFF + 1은 u16 모듈러 연산으로 글리프0이 된다.
            copy[delta..delta + 2].copy_from_slice(&1u16.to_be_bytes());
        }
    }
    repaired.map_or(std::borrow::Cow::Borrowed(data), std::borrow::Cow::Owned)
}

/// 윤곽선이 있는 TrueType의 선택 face를 브라우저에서 읽을 수 있는 사본으로 만든다.
///
/// 휴먼명조 같은 EBDT/EBLC 혼합 글꼴은 Chrome에서 해당 크기의 한글이 두부가
/// 될 수 있다. 정상 문자 매핑·glyph ID·윤곽선·advance는 그대로 복사한다.
/// 종료 비문자의 잘못된 매핑만 바로잡고 비트맵 strike를 제외한다. 비트맵만
/// 있는 사용 글리프는 원본을 유지하며 문서/디스크 입력은 바꾸지 않는다.
fn svg_outline_font_data<'a>(
    data: &'a [u8],
    chars: &std::collections::HashSet<char>,
) -> std::borrow::Cow<'a, [u8]> {
    svg_outline_font_face_data(data, chars, 0, false)
}

/// collection의 이름·스타일이 일치하는 face를 휴대 가능한 독립 sfnt로 공급한다.
/// 찾지 못한 이름을 첫 face에 연결하지 않으며, 일반 파일의 대체 정책은 보존한다.
#[cfg(not(target_arch = "wasm32"))]
fn svg_selected_font_data<'a>(
    data: &'a [u8],
    font_name: &str,
    chars: &std::collections::HashSet<char>,
) -> Option<std::borrow::Cow<'a, [u8]>> {
    if data.get(..4) != Some(b"ttcf") {
        return Some(svg_outline_font_data(data, chars));
    }
    let count = ttf_parser::fonts_in_collection(data)?;
    if count > 256 {
        return None;
    }
    let aliases = font_local_aliases(font_name);
    for requested in std::iter::once(font_name).chain(aliases.iter().copied()) {
        for index in 0..count {
            let Ok(face) = ttf_parser::Face::parse(data, index) else {
                continue;
            };
            if face.is_bold() || face.is_italic() {
                continue;
            }
            let matches = face.names().into_iter().any(|name| {
                matches!(name.name_id, 1 | 4 | 6 | 16)
                    && name
                        .to_string()
                        .or_else(|| std::str::from_utf8(name.name).ok().map(str::to_owned))
                        .is_some_and(|name| name.eq_ignore_ascii_case(requested))
            });
            if matches {
                let selected = svg_outline_font_face_data(data, chars, index, true);
                // 독립 sfnt를 만들지 못한 collection은 local()로 남긴다.
                return matches!(selected, std::borrow::Cow::Owned(_)).then_some(selected);
            }
        }
    }
    None
}

fn svg_outline_font_face_data<'a>(
    data: &'a [u8],
    chars: &std::collections::HashSet<char>,
    face_index: u32,
    extract_collection: bool,
) -> std::borrow::Cow<'a, [u8]> {
    if let Some(program) =
        crate::renderer::text_font_presentation::ordinary_text_font_program(data, face_index)
    {
        return std::borrow::Cow::Owned(
            svg_outline_font_face_data_impl(&program, chars, 0, false).into_owned(),
        );
    }
    svg_outline_font_face_data_impl(data, chars, face_index, extract_collection)
}

fn svg_outline_font_face_data_impl<'a>(
    data: &'a [u8],
    chars: &std::collections::HashSet<char>,
    face_index: u32,
    extract_collection: bool,
) -> std::borrow::Cow<'a, [u8]> {
    let original = || std::borrow::Cow::Borrowed(data);
    // collection 테이블 오프셋은 파일 전체 기준이며, 선택 face 헤더만 다르다.
    let sfnt_offset = if data.get(..4) == Some(b"ttcf") {
        let Some(position) = (face_index as usize)
            .checked_mul(4)
            .and_then(|v| v.checked_add(12))
        else {
            return original();
        };
        let Some(offset) = data.get(position..position + 4) else {
            return original();
        };
        u32::from_be_bytes(offset.try_into().unwrap()) as usize
    } else {
        0
    };
    let Some(header) = sfnt_offset
        .checked_add(12)
        .and_then(|end| data.get(sfnt_offset..end))
    else {
        return original();
    };
    if !matches!(header.get(..4), Some(b"\0\x01\0\0" | b"true")) {
        return original();
    }
    let Ok(face) = ttf_parser::Face::parse(data, face_index) else {
        return original();
    };
    let mut outline_count = 0;
    for ch in chars.iter().filter(|ch| !ch.is_whitespace()) {
        // cmap 부재 문자는 기존 CSS fallback이 담당한다. 비트맵 전용 글리프는
        // 제거할 수 없으며, 윤곽선 없는 글꼴 전체를 바꾸지도 않는다.
        if let Some(glyph) = face.glyph_index(*ch) {
            if face.glyph_bounding_box(glyph).is_none() {
                return original();
            }
            outline_count += 1;
        }
    }
    if outline_count == 0 || data.len() < 12 {
        return original();
    }
    let table_count = usize::from(u16::from_be_bytes([header[4], header[5]]));
    let Some(directory) = data.get(sfnt_offset + 12..sfnt_offset + 12 + table_count * 16) else {
        return original();
    };
    let mut tables = Vec::with_capacity(table_count);
    let mut has_bitmap = false;
    let mut repaired_cmap = false;
    for record in directory.chunks_exact(16) {
        if matches!(&record[..4], b"EBDT" | b"EBLC") {
            has_bitmap = true;
            continue;
        }
        let offset = u32::from_be_bytes(record[8..12].try_into().unwrap()) as usize;
        let length = u32::from_be_bytes(record[12..16].try_into().unwrap()) as usize;
        let Some(bytes) = offset
            .checked_add(length)
            .and_then(|end| data.get(offset..end))
        else {
            return original();
        };
        let bytes = if &record[..4] == b"cmap" {
            svg_cmap_terminal_missing_glyph(bytes, face.number_of_glyphs())
        } else {
            std::borrow::Cow::Borrowed(bytes)
        };
        repaired_cmap |= matches!(bytes, std::borrow::Cow::Owned(_));
        tables.push((&record[..4], bytes));
    }
    if (!has_bitmap && !repaired_cmap && !extract_collection)
        || !tables
            .iter()
            .any(|(tag, bytes)| *tag == b"head" && bytes.len() >= 12)
    {
        return original();
    }
    // sfnt의 검색 헤더·테이블 checksum·head 전체 checksum을 새 오프셋에 맞춘다.
    let count = tables.len() as u16;
    // 검색 헤더의 u16 범위와 원본 크기를 넘는 테이블 복사량은 수용하지 않는다.
    if count > u16::MAX / 16
        || tables
            .iter()
            .try_fold(12 + tables.len() * 16, |size, (_, bytes)| {
                size.checked_add(bytes.len().next_multiple_of(4))
            })
            .is_none_or(|size| size > data.len())
    {
        return original();
    }
    let power = 1u16 << (15 - count.leading_zeros());
    let mut result = vec![0u8; 12 + tables.len() * 16];
    result[..4].copy_from_slice(&header[..4]);
    result[4..6].copy_from_slice(&count.to_be_bytes());
    result[6..8].copy_from_slice(&(power * 16).to_be_bytes());
    result[8..10].copy_from_slice(&(15 - power.leading_zeros() as u16).to_be_bytes());
    result[10..12].copy_from_slice(&(count * 16 - power * 16).to_be_bytes());
    let checksum = |bytes: &[u8]| {
        bytes.chunks(4).fold(0u32, |sum, chunk| {
            let mut word = [0; 4];
            word[..chunk.len()].copy_from_slice(chunk);
            sum.wrapping_add(u32::from_be_bytes(word))
        })
    };
    let mut head_adjustment = 0;
    for (index, (tag, bytes)) in tables.iter().enumerate() {
        let offset = result.len();
        result.extend_from_slice(bytes.as_ref());
        result.resize(result.len().next_multiple_of(4), 0);
        if *tag == b"head" {
            head_adjustment = offset + 8;
            result[head_adjustment..head_adjustment + 4].fill(0);
        }
        let sum = checksum(&result[offset..offset + bytes.len()]);
        let record = &mut result[12 + index * 16..28 + index * 16];
        record[..4].copy_from_slice(tag);
        record[4..8].copy_from_slice(&sum.to_be_bytes());
        record[8..12].copy_from_slice(&(offset as u32).to_be_bytes());
        record[12..16].copy_from_slice(&(bytes.len() as u32).to_be_bytes());
    }
    let adjustment = 0xB1B0_AFBAu32.wrapping_sub(checksum(&result));
    result[head_adjustment..head_adjustment + 4].copy_from_slice(&adjustment.to_be_bytes());
    std::borrow::Cow::Owned(result)
}

/// Encode a document face as the contents of a double-quoted CSS string.
/// Keep the original name for lookup; only serialize at the output boundary.
/// Hex escapes also keep SVG/HTML style delimiters and XML-invalid controls out
/// of the source. The trailing space terminates the escape before hex digits.
fn escape_css_font_name(name: &str) -> String {
    use std::fmt::Write;

    let mut escaped = String::with_capacity(name.len());
    for character in name.chars() {
        if matches!(
            character,
            '"' | '\\' | '<' | '>' | '&' | '\u{fffe}' | '\u{ffff}'
        ) || character.is_control()
        {
            write!(escaped, "\\{:x} ", character as u32).expect("writing to String");
        } else {
            escaped.push(character);
        }
    }
    escaped
}

/// CSS is text in an XML style element, not markup. Both public SVG export
/// routes use this wrapper, including the WASM print/profile route.
pub(crate) fn svg_font_style_element(css: &str) -> String {
    let text = css
        .replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;");
    format!("\n<style>\n{text}</style>\n")
}

/// [#2524] 문서 임베디드(BinData) 폰트를 @font-face 로 직접 임베딩한다.
///
/// 미설치 임베디드 폰트(bitmap 등)는 `find_font_file`(디스크) 조회에 실패해
/// `local()` 폴백이 되고, blink(chrome) 는 해결 못해 글리프가 두부(□)로 렌더된다
/// (#2524). 서브셋터(typst)는 bitmap glyph 테이블(EBDT/EBLC)을 보존하지 못하므로
/// 임베디드 폰트는 서브셋하지 않고 원본 전체를 data-URI 로 임베딩한다.
fn embedded_font_face_css(
    font_name: &str,
    embedded_fonts: &std::collections::HashMap<String, Vec<u8>>,
    chars: &std::collections::HashSet<char>,
) -> Option<String> {
    let bytes = embedded_fonts.get(font_name)?;
    if bytes.is_empty() {
        return None;
    }
    let bytes = svg_outline_font_data(bytes, chars);
    let (mime, format) = font_data_uri_format(&bytes);
    let b64 = base64::engine::general_purpose::STANDARD.encode(&bytes);
    Some(format!(
        "@font-face {{ font-family: \"{}\"; src: url(\"data:{};base64,{}\") format(\"{}\"); }}\n",
        escape_css_font_name(font_name),
        mime,
        b64,
        format,
    ))
}

/// 폰트 매직 바이트(sfnt version)로 data-URI mime 과 CSS `format()` 을 판별한다.
fn font_data_uri_format(bytes: &[u8]) -> (&'static str, &'static str) {
    match bytes.get(0..4) {
        Some(b"OTTO") => ("font/otf", "opentype"),
        Some(b"wOFF") => ("font/woff", "woff"),
        Some(b"wOF2") => ("font/woff2", "woff2"),
        // 0x00010000 (TrueType) · "true" · "ttcf"(TTC) 등은 truetype 으로 취급
        _ => ("font/ttf", "truetype"),
    }
}

#[cfg(not(target_arch = "wasm32"))]
fn append_local_bold_font_face_css(css: &mut String, font_name: &str) {
    let aliases = font_local_bold_aliases(font_name);
    if aliases.is_empty() {
        return;
    }
    let src = aliases
        .iter()
        .map(|alias| format!("local(\"{}\")", escape_css_font_name(alias)))
        .collect::<Vec<_>>()
        .join(", ");
    css.push_str(&format!(
        "@font-face {{ font-family: \"{}\"; src: {}; font-weight: bold; }}\n",
        escape_css_font_name(font_name),
        src,
    ));
}

/// 실제 Bold face를 data-URI로 추가한다.
///
/// Bold는 기존의 실제 전체 프로그램 공급을 유지한다. Regular의 부분집합 결과로
/// Bold 프로그램을 대신하거나 브라우저의 synthetic bold를 강제하지 않는다.
#[cfg(not(target_arch = "wasm32"))]
fn append_embedded_bold_font_face_css(
    css: &mut String,
    font_name: &str,
    bold_lookup: &FontFileLookupPlan,
) {
    if let Some(font_path) = find_font_file(bold_lookup) {
        if let Ok(font_data) = std::fs::read(&font_path) {
            let b64 = base64::engine::general_purpose::STANDARD.encode(&font_data);
            css.push_str(&format!(
                "@font-face {{ font-family: \"{}\"; src: url(\"data:font/opentype;base64,{}\") format(\"opentype\"); font-weight: bold; }}\n",
                escape_css_font_name(font_name), b64,
            ));
            eprintln!(
                "  [font-embed] {} Bold → 전체 {:.1}KB",
                font_name,
                font_data.len() as f64 / 1024.0
            );
            return;
        }
    }
    append_local_bold_font_face_css(css, font_name);
}

/// 렌더 결과에서 실제 사용된 문서 내장 폰트만 data-URI `@font-face`로 만든다.
///
/// 시스템 폰트 탐색·서브셋 파일 I/O가 없는 경로이므로 WASM의 인쇄 SVG에서도
/// 사용할 수 있다. 비내장 폰트는 기존 SVG `font-family` fallback을 유지한다.
pub fn generate_embedded_font_style(
    renderer: &SvgRenderer,
    embedded_fonts: &std::collections::HashMap<String, Vec<u8>>,
) -> String {
    let mut css = String::new();
    for (font_name, request) in font_style_requests(renderer) {
        if let Some(line) = embedded_font_face_css(&font_name, embedded_fonts, &request.chars) {
            css.push_str(&line);
        }
    }
    css
}

/// CSS 체인의 선언 face를 개별 리소스로 수집한다. 체인 전체를 한 개의
/// @font-face 이름으로 만들거나 generic 사본이 선언 대체를 가리게 하지 않는다.
struct FontStyleRequest {
    chars: std::collections::HashSet<char>,
    #[cfg(not(target_arch = "wasm32"))]
    bold: bool,
    #[cfg(not(target_arch = "wasm32"))]
    allow_generic_substitute: bool,
}

fn font_style_requests(
    renderer: &SvgRenderer,
) -> std::collections::BTreeMap<String, FontStyleRequest> {
    let mut requests = std::collections::BTreeMap::<String, FontStyleRequest>::new();
    for (chain, chars) in renderer.font_codepoints() {
        let members = super::internal_font_family_members(chain);
        for face in &members {
            let request = requests
                .entry((*face).to_string())
                .or_insert_with(|| FontStyleRequest {
                    chars: std::collections::HashSet::new(),
                    #[cfg(not(target_arch = "wasm32"))]
                    bold: false,
                    #[cfg(not(target_arch = "wasm32"))]
                    allow_generic_substitute: true,
                });
            request.chars.extend(chars.iter().copied());
            #[cfg(not(target_arch = "wasm32"))]
            {
                request.bold |= renderer.font_bold_families().contains(chain);
                request.allow_generic_substitute &= members.len() == 1;
            }
        }
    }
    requests
}

/// SvgRenderer의 수집된 폰트 정보를 기반으로 @font-face CSS를 생성한다.
///
/// `embedded_fonts` (face명 → 원본 폰트 bytes) 에 있는 폰트는 임베드 모드와
/// 무관하게 data-URI 로 전체 임베딩한다(#2524, 미설치 임베디드 폰트 대응).
#[cfg(not(target_arch = "wasm32"))]
pub fn generate_font_style(
    renderer: &SvgRenderer,
    font_paths: &[std::path::PathBuf],
    embedded_fonts: &std::collections::HashMap<String, Vec<u8>>,
) -> String {
    let codepoints = font_style_requests(renderer);
    if codepoints.is_empty() {
        return String::new();
    }
    let mut font_names = codepoints.keys().collect::<Vec<_>>();
    font_names.sort_unstable();

    let mut css = String::new();

    match renderer.font_embed_mode {
        FontEmbedMode::Style => {
            for &font_name in &font_names {
                if let Some(line) =
                    embedded_font_face_css(font_name, embedded_fonts, &codepoints[font_name].chars)
                {
                    css.push_str(&line);
                    continue;
                }
                let aliases = font_local_aliases(font_name);
                let src = if aliases.is_empty() {
                    format!("local(\"{}\")", escape_css_font_name(font_name))
                } else {
                    aliases
                        .iter()
                        .map(|a| format!("local(\"{}\")", escape_css_font_name(a)))
                        .collect::<Vec<_>>()
                        .join(", ")
                };
                css.push_str(&format!(
                    "@font-face {{ font-family: \"{}\"; src: {}; }}\n",
                    escape_css_font_name(font_name),
                    src,
                ));
                if codepoints[font_name].bold {
                    append_local_bold_font_face_css(&mut css, font_name);
                }
            }
        }
        FontEmbedMode::Subset => {
            for &font_name in &font_names {
                let chars = &codepoints[font_name].chars;
                if let Some(line) =
                    embedded_font_face_css(font_name, embedded_fonts, &codepoints[font_name].chars)
                {
                    css.push_str(&line);
                    continue;
                }
                let regular_lookup = plan_svg_font_file_lookup_with_fallback(
                    font_name,
                    font_paths,
                    false,
                    codepoints[font_name].allow_generic_substitute,
                );
                if let Some(font_path) =
                    find_font_file_for_chars(&regular_lookup, &codepoints[font_name].chars)
                {
                    if let Ok(font_data) = std::fs::read(&font_path) {
                        if let Some(font_data) =
                            svg_selected_font_data(&font_data, font_name, chars)
                        {
                            let (data, subset) = match webfont_subset::subset(&font_data, chars) {
                                Ok(data) => (std::borrow::Cow::Owned(data), true),
                                Err(error) => {
                                    eprintln!(
                                        "  [font-embed] {} 부분집합 미지원: {} → 전체 face 공급",
                                        font_name, error
                                    );
                                    (font_data, false)
                                }
                            };
                            let (mime, format) = if subset || data.starts_with(b"OTTO") {
                                ("font/opentype", "opentype")
                            } else {
                                ("font/ttf", "truetype")
                            };
                            let b64 = base64::engine::general_purpose::STANDARD.encode(&data);
                            css.push_str(&format!(
                                "@font-face {{ font-family: \"{}\"; src: url(\"data:{};base64,{}\") format(\"{}\"); }}\n",
                                escape_css_font_name(font_name), mime, b64, format,
                            ));
                            if codepoints[font_name].bold {
                                let bold_lookup =
                                    plan_svg_font_file_lookup(font_name, font_paths, true);
                                append_embedded_bold_font_face_css(
                                    &mut css,
                                    font_name,
                                    &bold_lookup,
                                );
                            }
                            continue;
                        }
                    }
                }
                // 폰트 파일 없거나 서브셋 실패 → local() 폴백
                let aliases = font_local_aliases(font_name);
                let src = if aliases.is_empty() {
                    format!("local(\"{}\")", escape_css_font_name(font_name))
                } else {
                    aliases
                        .iter()
                        .map(|a| format!("local(\"{}\")", escape_css_font_name(a)))
                        .collect::<Vec<_>>()
                        .join(", ")
                };
                css.push_str(&format!(
                    "@font-face {{ font-family: \"{}\"; src: {}; }}\n",
                    escape_css_font_name(font_name),
                    src,
                ));
                if codepoints[font_name].bold {
                    append_local_bold_font_face_css(&mut css, font_name);
                }
            }
        }
        FontEmbedMode::Full => {
            for &font_name in &font_names {
                if let Some(line) =
                    embedded_font_face_css(font_name, embedded_fonts, &codepoints[font_name].chars)
                {
                    css.push_str(&line);
                    continue;
                }
                let regular_lookup = plan_svg_font_file_lookup_with_fallback(
                    font_name,
                    font_paths,
                    false,
                    codepoints[font_name].allow_generic_substitute,
                );
                if let Some(font_path) =
                    find_font_file_for_chars(&regular_lookup, &codepoints[font_name].chars)
                {
                    if let Ok(font_data) = std::fs::read(&font_path) {
                        if let Some(font_data) = svg_selected_font_data(
                            &font_data,
                            font_name,
                            &codepoints[font_name].chars,
                        ) {
                            let b64 = base64::engine::general_purpose::STANDARD.encode(&font_data);
                            css.push_str(&format!(
                            "@font-face {{ font-family: \"{}\"; src: url(\"data:font/opentype;base64,{}\") format(\"opentype\"); }}\n",
                            escape_css_font_name(font_name), b64,
                        ));
                            if codepoints[font_name].bold {
                                let bold_lookup =
                                    plan_svg_font_file_lookup(font_name, font_paths, true);
                                append_embedded_bold_font_face_css(
                                    &mut css,
                                    font_name,
                                    &bold_lookup,
                                );
                            }
                            eprintln!(
                                "  [font-embed] {} → 전체 {:.1}KB",
                                font_name,
                                font_data.len() as f64 / 1024.0
                            );
                            continue;
                        }
                    }
                }
                // 폰트 파일 없음 → local() 폴백
                let aliases = font_local_aliases(font_name);
                let src = if aliases.is_empty() {
                    format!("local(\"{}\")", escape_css_font_name(font_name))
                } else {
                    aliases
                        .iter()
                        .map(|a| format!("local(\"{}\")", escape_css_font_name(a)))
                        .collect::<Vec<_>>()
                        .join(", ")
                };
                css.push_str(&format!(
                    "@font-face {{ font-family: \"{}\"; src: {}; }}\n",
                    escape_css_font_name(font_name),
                    src,
                ));
                if codepoints[font_name].bold {
                    append_local_bold_font_face_css(&mut css, font_name);
                }
            }
        }
        FontEmbedMode::None => {}
    }

    fallback_fonts::append_missing_serif_font_css(&mut css, renderer, font_paths, embedded_fonts);
    italic_fonts::append_font_css(&mut css, renderer, font_paths);
    css
}

#[cfg(test)]
mod tests;

fn svg_path_data(commands: &[PathCommand]) -> String {
    let mut d = String::new();
    for cmd in commands {
        match cmd {
            PathCommand::MoveTo(x, y) => d.push_str(&format!("M{} {} ", x, y)),
            PathCommand::LineTo(x, y) => d.push_str(&format!("L{} {} ", x, y)),
            PathCommand::CurveTo(x1, y1, x2, y2, x, y) => {
                d.push_str(&format!("C{} {} {} {} {} {} ", x1, y1, x2, y2, x, y))
            }
            PathCommand::ArcTo(rx, ry, x_rot, large_arc, sweep, x, y) => {
                d.push_str(&format!(
                    "A{} {} {} {} {} {} {} ",
                    rx,
                    ry,
                    x_rot,
                    if *large_arc { 1 } else { 0 },
                    if *sweep { 1 } else { 0 },
                    x,
                    y
                ));
            }
            PathCommand::ClosePath => d.push_str("Z "),
        }
    }
    d
}