File: fpdf.py

package info (click to toggle)
fpdf2 2.8.7-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 114,352 kB
  • sloc: python: 50,410; sh: 133; makefile: 12
file content (6564 lines) | stat: -rw-r--r-- 266,270 bytes parent folder | download
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
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
# ****************************************************************************
# * Software: FPDF for python                                                *
# * License:  LGPL v3.0+                                                     *
# *                                                                          *
# * Original Author (PHP):  Olivier PLATHEY 2004-12-31                       *
# * Ported to Python 2.4 by Max (maxpat78@yahoo.it) on 2006-05               *
# * Maintainer:  Mariano Reingart (reingart@gmail.com) et al since 2008 est. *
# * Maintainer:  David Alexander (daveankin@gmail.com) et al since 2017 est. *
# * Maintainer:  Lucas Cimon et al since 2021 est.                           *
# ****************************************************************************
import hashlib
import io
import logging
import math
import mimetypes
import os
import re
import sys
import types
import warnings
from collections import defaultdict
from contextlib import contextmanager
from datetime import datetime, timezone
from functools import wraps
from os.path import splitext
from pathlib import Path, PurePath
from typing import (
    TYPE_CHECKING,
    Any,
    BinaryIO,
    Callable,
    Iterator,
    Literal,
    NamedTuple,
    Optional,
    ParamSpec,
    Sequence,
    Type,
    TypeAlias,
    TypeVar,
    Union,
    ValuesView,
    cast,
    overload,
)

try:
    from cryptography.hazmat.primitives.serialization import pkcs12
    from endesive import signer
except ImportError:
    pkcs12, signer = None, None  # type: ignore[assignment]

try:
    from PIL.Image import Image  # pyright: ignore[reportAssignmentType]
except ImportError:
    warnings.warn(
        "Pillow could not be imported - fpdf2 will not be able to add any image"
    )

    class Image:  # type: ignore[no-redef]
        # The class must exist for some isinstance checks below
        pass


from .actions import Action, GoToAction, URIAction
from .annotations import (
    DEFAULT_ANNOT_FLAGS,
    AnnotationDict,
    PDFAnnotation,
    PDFEmbeddedFile,
)
from .bidi import BidiParagraph, auto_detect_base_direction
from .deprecation import (
    WarnOnDeprecatedModuleAttributes,
    deprecated_parameter,
    get_stack_level,
    support_deprecated_txt_arg,
)
from .drawing import DrawingContext, GraphicsContext, GraphicsStyle, PaintedPath
from .drawing_primitives import (
    Color,
    ColorInput,
    DeviceCMYK,
    DeviceGray,
    DeviceRGB,
    Point,
    Transform,
    convert_to_device_color,
)
from .encryption import StandardSecurityHandler
from .enums import (
    AccessPermission,
    Align,
    Angle,
    AnnotationFlag,
    AnnotationName,
    AssociatedFileRelationship,
    CharVPos,
    Corner,
    DocumentCompliance,
    EncryptionMethod,
    FileAttachmentAnnotationName,
    MethodReturnValue,
    OutputIntentSubType,
    PageLabelStyle,
    PageLayout,
    PageMode,
    PageOrientation,
    PathPaintRule,
    PDFResourceType,
    RenderStyle,
    TextDirection,
    TextEmphasis,
    TextMarkupType,
    TextMode,
    WrapMode,
    XPos,
    YPos,
)
from .errors import (
    FPDFException,
    FPDFPageFormatException,
    FPDFUnicodeEncodingException,
    PDFAComplianceError,
)
from .fonts import CORE_FONTS, CoreFont, FontFace, TextStyle, TitleStyle, TTFFont
from .graphics_state import GraphicsStateMixin, StateStackType
from .html import HTML2FPDF
from .image_datastructures import (
    ImageCache,
    ImageFilter,
    ImageInfo,
    RasterImageInfo,
    VectorImageInfo,
)
from .image_parsing import (
    SUPPORTED_IMAGE_FILTERS,
    get_img_info,
    load_image,
    preload_image,
)
from .line_break import (
    Fragment,
    MultiLineBreak,
    TextLine,
    TotalPagesSubstitutionFragment,
)
from .linearization import LinearizedOutputProducer
from .outline import OutlineSection
from .output import (
    ZOOM_CONFIGS,
    OutputIntentDictionary,
    OutputProducer,
    PDFICCProfile,
    PDFPage,
    PDFPageLabel,
    ResourceCatalog,
    ResourceTypes,
    stream_content_for_raster_image,
)
from .pattern import Gradient
from .recorder import FPDFRecorder
from .sign import Signature
from .structure_tree import StructElem, StructureTreeBuilder
from .svg import Percent, SVGObject
from .syntax import DestinationXYZ, Name, PDFArray, PDFDate, PDFString
from .table import Table, draw_box_borders
from .text_region import TextColumns, TextRegionMixin
from .transitions import Transition
from .unicode_script import UnicodeScript, get_unicode_script
from .util import (
    FloatTolerance,
    ImageType,
    Number,
    NumberClass,
    Padding,
    builtin_srgb2014_bytes,
    get_parsed_unicode_range,
    get_scale_factor,
)

P = ParamSpec("P")
R = TypeVar("R")

if TYPE_CHECKING:
    from cryptography.hazmat.primitives.asymmetric.types import PrivateKeyTypes
    from cryptography.x509 import Certificate

    from .font_type_3 import Type3Font
    from .prefs import ViewerPreferences

# Public global variables:
FPDF_VERSION = "2.8.7"
__version__ = FPDF_VERSION
PAGE_FORMATS = {
    "a3": (841.89, 1190.55),  # 297mm × 420mm
    "a4": (595.28, 841.89),  # 210mm × 297mm
    "a5": (419.53, 595.28),  # 148mm x 210mm
    "letter": (612, 792),
    "legal": (612, 1008),
}
"Supported page format names & dimensions"

# Private global variables:
LOGGER = logging.getLogger(__name__)
HERE = Path(__file__).resolve().parent
FPDF_FONT_DIR: Path = HERE / "font"
LAYOUT_ALIASES: dict[str, Optional[PageLayout]] = {
    "default": None,
    "single": PageLayout.SINGLE_PAGE,
    "continuous": PageLayout.ONE_COLUMN,
    "two": PageLayout.TWO_COLUMN_LEFT,
}


class ToCPlaceholder(NamedTuple):
    render_function: Callable[["FPDF", list[OutlineSection]], None]
    start_page: int
    y: float
    page_orientation: str | PageOrientation
    pages: int = 1
    reset_page_indices: bool = True


# Disabling this check due to the "format" parameter below:
# pylint: disable=redefined-builtin
def get_page_format(
    format: str | tuple[float, float], k: Optional[float] = None
) -> tuple[float, float]:
    """Return page width and height size in points.

    Throws FPDFPageFormatException

    `format` can be either a 2-tuple or one of 'a3', 'a4', 'a5', 'letter', or
    'legal'.

    If format is a tuple, then the return value is the tuple's values
    given in the units specified on this document in the constructor,
    multiplied by the corresponding scale factor `k`, taken from instance
    variable `self.k`.

    If format is a string, the (width, height) tuple returned is in points.
    For a width and height of 8.5 * 11, 72 dpi is assumed, so the value
    returned is (8.5 * 72, 11 * 72), or (612, 792). Additional formats can be
    added by adding fields to the `PAGE_FORMATS` dictionary with a
    case insensitive key (the name of the new format) and 2-tuple value of
    (width, height) in dots per inch with a 72 dpi resolution.
    """
    if isinstance(format, str):
        format = format.lower()
        if format in PAGE_FORMATS:
            if format == "a5":
                warnings.warn(
                    # This warning should be removed in the next release:
                    "Dimensions for page format A5 were fixed in release 2.8.5"
                )
            return PAGE_FORMATS[format]
        raise FPDFPageFormatException(format, unknown=True)

    if k is None:
        raise FPDFPageFormatException(str(format), one=True)

    try:
        return format[0] * k, format[1] * k
    except Exception as e:
        args = f"{format}, {k}"
        raise FPDFPageFormatException(f"Arguments must be numbers: {args}") from e


def check_page(fn: Callable[P, R]) -> Callable[P, R]:
    """Decorator to protect drawing methods"""

    @wraps(fn)
    def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
        self = args[0]
        if (
            not hasattr(self, "page")
            or not self.page  # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType]
        ) and not (kwargs.get("dry_run") or kwargs.get("split_only")):
            raise FPDFException("No page open, you need to call add_page() first")
        return fn(*args, **kwargs)

    return wrapper


class FPDF(GraphicsStateMixin, TextRegionMixin):
    "PDF Generation class"

    MARKDOWN_BOLD_MARKER = "**"
    MARKDOWN_ITALICS_MARKER = "__"
    MARKDOWN_STRIKETHROUGH_MARKER = "~~"
    MARKDOWN_UNDERLINE_MARKER = "--"
    MARKDOWN_ESCAPE_CHARACTER = "\\"
    MARKDOWN_LINK_REGEX = re.compile(r"^\[([^][]+)\]\(([^()]+)\)(.*)$", re.DOTALL)
    MARKDOWN_LINK_COLOR = None
    MARKDOWN_LINK_UNDERLINE = True

    HTML2FPDF_CLASS = HTML2FPDF

    def __init__(
        self,
        orientation: Union[str, PageOrientation] = PageOrientation.PORTRAIT,
        unit: Union[str, float] = "mm",
        format: Union[str, tuple[float, float]] = "A4",
        font_cache_dir: Literal["DEPRECATED"] = "DEPRECATED",
        *,
        enforce_compliance: Optional[Union[str, DocumentCompliance]] = None,
    ) -> None:
        """
        Args:
            orientation (str): possible values are "portrait" (can be abbreviated "P")
                or "landscape" (can be abbreviated "L"). Default to "portrait".
            unit (str, int, float): possible values are "pt", "mm", "cm", "in", or a number.
                A point equals 1/72 of an inch, that is to say about 0.35 mm (an inch being 2.54 cm).
                This is a very common unit in typography; font sizes are expressed in this unit.
                If given a number, then it will be treated as the number of points per unit.  (eg. 72 = 1 in)
                Default to "mm".
            format (str): possible values are "a3", "a4", "a5", "letter", "legal" or a tuple
                (width, height) expressed in the given unit. Default to "a4".
            font_cache_dir (Path or str): [**DEPRECATED since v2.5.1**] unused
        """
        if font_cache_dir != "DEPRECATED":
            warnings.warn(
                (
                    '"font_cache_dir" parameter is deprecated since v2.5.1, '
                    "unused and will soon be removed"
                ),
                DeprecationWarning,
                stacklevel=get_stack_level(),
            )
        super().__init__()
        self.single_resources_object = False
        """
        Setting this to True restore the old behaviour before 2.7.9.
        Using a single /Resources object makes the resulting PDF document smaller,
        but is less compatible with the PDF spec.
        """
        self.page = 0  # current page number
        """
        Note: Setting the page manually may result in unexpected behavior.
        `pdf.add_page()` takes special care to ensure the page's content stream
        matches FPDF's instance attributes. Manually setting the page does not.
        """
        # array of PDFPage objects starting at index 1:
        self.pages: dict[int, PDFPage] = {}
        # map page numbers to a set of font indices:
        self.links: dict[int, DestinationXYZ] = (
            {}
        )  # Destination objects starting at index 1
        self.named_destinations: dict[str, DestinationXYZ] = (
            {}
        )  # map names to Destination objects
        self.embedded_files: list[PDFEmbeddedFile] = []  # array of PDFEmbeddedFile
        self.image_cache = ImageCache()
        self.in_footer = False  # flag set while rendering footer
        # indicates that we are inside an .unbreakable() code block:
        self._in_unbreakable = False
        self._lasth: float = 0  # height of last cell printed
        self.alias_nb_pages()  # enable alias by default

        self._angle: float = 0  # used by deprecated method: rotate()
        self.xmp_metadata = None
        # Define the compression algorithm used when embedding images:
        self.page_duration = 0  # optional pages display duration, cf. add_page()
        self.page_transition = None  # optional pages transition, cf. add_page()
        self.allow_images_transparency = True
        # Do nothing by default. Allowed values: 'WARN', 'DOWNSCALE':
        self.oversized_images: Optional[Literal["WARN", "DOWNSCALE"]] = None
        self.oversized_images_ratio = 2  # number of pixels per UserSpace point
        self.struct_builder = StructureTreeBuilder()

        self.toc_placeholder: Optional[ToCPlaceholder] = None
        self._outline: list[OutlineSection] = []
        # flag set true while rendering the table of contents
        self.in_toc_rendering = False
        # allow page insertion when writing the table of contents
        self._toc_allow_page_insertion = False
        self._toc_inserted_pages = 0  # number of pages inserted
        # dict of Output Intents, with keys beings their subtypes:
        self._output_intents: dict[Name, OutputIntentDictionary] = {}

        self._sign_key = None
        self.title: Optional[str] = None
        self.section_title_styles: dict[int, TextStyle] = {}  # level -> TextStyle

        self.core_fonts_encoding = "latin-1"
        "Font encoding, Latin-1 by default"
        # Replace these fonts with these core fonts
        self.font_aliases = {
            "arial": "helvetica",
            "couriernew": "courier",
            "timesnewroman": "times",
        }
        # Scale factor
        self.k = get_scale_factor(unit)

        # Graphics state variables defined as properties by GraphicsStateMixin.
        # We set their default values here.
        self.font_family = ""  # current font family
        # current font style (BOLD/ITALICS - does not handle UNDERLINE nor STRIKETHROUGH):
        self.font_style = ""
        self.underline = False
        self.strikethrough = False
        self.font_size_pt: float = 12  # current font size in points
        self.font_stretching = 100  # current font stretching
        self.char_spacing = 0  # current character spacing
        self.current_font: Optional[CoreFont | TTFFont] = (
            None  # None or an instance of CoreFont or TTFFont
        )
        self.current_font_is_set_on_page = False  # current font and size are already added to current page contents with _out
        self.draw_color = self.DEFAULT_DRAW_COLOR
        self.fill_color = self.DEFAULT_FILL_COLOR
        self.text_color = self.DEFAULT_TEXT_COLOR
        self.page_background = None
        self.dash_pattern = dict(dash=0, gap=0, phase=0)
        self.line_width = 0.567 / self.k  # line width (0.2 mm)
        self.text_mode = TextMode.FILL
        # end of graphics state variables

        self.dw_pt, self.dh_pt = get_page_format(format, self.k)
        self._set_orientation(orientation, self.dw_pt, self.dh_pt)
        self.def_orientation = self.cur_orientation
        # Page spacing
        # Page margins (1 cm)
        margin: float = (7200 / 254) / self.k
        self.x: float = 0
        self.y: float = 0
        self.l_margin: float = 0
        self.t_margin: float = 0
        self.set_margins(margin, margin)
        self.x, self.y = self.l_margin, self.t_margin
        self.c_margin: float = margin / 10.0  # Interior cell margin (1 mm)
        # sets self.auto_page_break, self.b_margin & self.page_break_trigger:
        self.set_auto_page_break(True, 2 * margin)
        self.set_display_mode("fullwidth")  # Full width display mode
        self._page_mode: Optional[PageMode] = None
        self.viewer_preferences: Optional["ViewerPreferences"] = (
            None  # optional instance of ViewerPreferences
        )
        self.compress: bool = True  # switch enabling pages content compression
        self.pdf_version: str = "1.3"  # Set default PDF version No.
        self.creation_date: datetime = datetime.now(timezone.utc)
        self._security_handler: Optional[StandardSecurityHandler] = None
        self._fallback_font_ids: list[str] = []
        self._fallback_font_exact_match = False
        self.render_color_fonts: bool = True
        self._compliance: Optional[DocumentCompliance] = (
            DocumentCompliance.coerce(enforce_compliance)
            if enforce_compliance
            else None
        )
        if self._compliance:
            if self._compliance.profile == "PDFA" and self._compliance.part == 1:
                self._set_min_pdf_version("1.4")
                self.allow_images_transparency = False
            if self._compliance.profile == "PDFA" and self._compliance.part in (2, 3):
                self._set_min_pdf_version("1.7")
            if self._compliance.profile == "PDFA" and self._compliance.part == 4:
                self._set_min_pdf_version("2.0")

        self._current_draw_context: Optional[DrawingContext] = None
        # map page numbers to a set of GraphicsState names:
        self._record_text_quad_points = False
        self._resource_catalog: ResourceCatalog = ResourceCatalog()

        # page number -> array of 8 × n numbers:
        self._text_quad_points: dict[int, list[float]] = defaultdict(list)

        # final buffer holding the PDF document in-memory - defined only after calling output():
        self.buffer: Optional[bytearray] = None

    @property
    def fonts(self) -> dict[str, CoreFont | TTFFont]:
        return self._resource_catalog.font_registry

    def set_encryption(
        self,
        owner_password: str,
        user_password: Optional[str] = None,
        encryption_method: EncryptionMethod = EncryptionMethod.RC4,
        permissions: int = AccessPermission.all(),
        encrypt_metadata: bool = False,
    ) -> None:
        """
        Activate encryption of the document content.

        Args:
            owner_password (str): mandatory. The owner password allows to perform any change on the document,
                including removing all encryption and access permissions.
            user_password (str): optional. If a user password is set, the content of the document will be encrypted
                and a password prompt displayed when a user opens the document.
                The document will only be displayed after either the user or owner password is entered.
            encryption_method (fpdf.enums.EncryptionMethod, str): algorithm to be used to encrypt the document.
                Defaults to RC4.
            permissions (fpdf.enums.AccessPermission): specify access permissions granted
                when the document is opened with user access. Defaults to ALL.
            encrypt_metadata (bool): whether to also encrypt document metadata (author, creation date, etc.).
                Defaults to False.
        """
        if self._compliance and self._compliance.profile == "PDFA":
            raise PDFAComplianceError(
                f"Encryption is now allowed for documents compliant with {self._compliance.label}"
            )

        self._security_handler = StandardSecurityHandler(
            self,
            owner_password=owner_password,
            user_password=user_password,
            permission=permissions,
            encryption_method=encryption_method,
            encrypt_metadata=encrypt_metadata,
        )

    def write_html(self, text: str, *args: Any, **kwargs: Any) -> None:
        """
        Parse HTML and convert it to PDF.
        cf. https://py-pdf.github.io/fpdf2/HTML.html

        Args:
            text (str): HTML content to render
            image_map (function): an optional one-argument function that map `<img>` "src" to new image URLs
            li_tag_indent (int): [**DEPRECATED since v2.7.9**]
                numeric indentation of `<li>` elements - Set `tag_styles` instead
            dd_tag_indent (int): [**DEPRECATED since v2.7.9**]
                numeric indentation of `<dd>` elements - Set `tag_styles` instead
            table_line_separators (bool): enable horizontal line separators in `<table>`. Defaults to `False`.
            ul_bullet_char (str): bullet character preceding `<li>` items in `<ul>` lists.
                Can also be configured using the HTML `type` attribute of `<ul>` tags.
            li_prefix_color (tuple, str, fpdf.drawing.DeviceCMYK, fpdf.drawing.DeviceGray, fpdf.drawing.DeviceRGB): color for bullets
                or numbers preceding `<li>` tags. This applies to both `<ul>` & `<ol>` lists.
            heading_sizes (dict): [**DEPRECATED since v2.7.9**]
                font size per heading level names ("h1", "h2"...) - Set `tag_styles` instead
            pre_code_font (str): [**DEPRECATED since v2.7.9**]
                font to use for `<pre>` & `<code>` blocks - Set `tag_styles` instead
            warn_on_tags_not_matching (bool): control warnings production for unmatched HTML tags. Defaults to `True`.
            tag_indents (dict): [**DEPRECATED since v2.8.0**]
                mapping of HTML tag names to numeric values representing their horizontal left indentation. - Set `tag_styles` instead
            tag_styles (dict[str, fpdf.fonts.TextStyle]): mapping of HTML tag names to `fpdf.fonts.TextStyle` or `fpdf.fonts.FontFace` instances
        """
        html2pdf = self.HTML2FPDF_CLASS(self, *args, **kwargs)
        with self.local_context():
            html2pdf.feed(text)

    def _set_min_pdf_version(self, version: str) -> None:
        self.pdf_version = max(self.pdf_version, version)

    @property
    def emphasis(self) -> TextEmphasis:
        "The current text emphasis: bold, italics, underline and/or strikethrough."
        font_style = self.font_style
        if self.strikethrough:
            font_style += "S"
        if self.underline:
            font_style += "U"
        return TextEmphasis.coerce(font_style)

    @property
    def is_ttf_font(self) -> bool:
        return self.current_font is not None and self.current_font.type == "TTF"

    @property
    def page_mode(self) -> Optional[PageMode]:
        return self._page_mode

    @page_mode.setter
    def page_mode(self, page_mode: PageMode | str) -> None:
        self._page_mode = PageMode.coerce(page_mode)
        if self._page_mode == PageMode.USE_ATTACHMENTS:
            self._set_min_pdf_version("1.6")
        elif self._page_mode == PageMode.USE_OC:
            self._set_min_pdf_version("1.5")

    @property
    def output_intents(self) -> ValuesView[OutputIntentDictionary]:
        return self._output_intents.values()

    def add_output_intent(
        self,
        subtype: OutputIntentSubType,
        output_condition_identifier: Optional[str] = None,
        output_condition: Optional[str] = None,
        registry_name: Optional[str] = None,
        dest_output_profile: Optional[PDFICCProfile] = None,
        info: Optional[str] = None,
    ) -> None:
        """
        Adds desired Output Intent to the Output Intents array:

        Args:
            subtype (OutputIntentSubType, required): PDFA, PDFX or ISOPDF
            output_condition_identifier (str, required): see the Name in
                https://www.color.org/registry.xalter
            output_condition (str, optional): see the Definition in
                https://www.color.org/registry.xalter
            registry_name (str, optional): "https://www.color.org"
            dest_output_profile (PDFICCProfile, required/optional):
                PDFICCProfile | None # (required  if
                output_condition_identifier does not specify a standard
                production condition; optional otherwise)
            info (str, required/optional see dest_output_profile): human
                readable description of profile
        """
        if subtype.value in self._output_intents:
            raise ValueError(
                "add_output_intent: subtype '" + subtype.value + "' already exists."
            )
        self._output_intents[subtype.value] = OutputIntentDictionary(
            subtype,
            output_condition_identifier,
            output_condition,
            registry_name,
            dest_output_profile,
            info,
        )
        self._set_min_pdf_version("1.4")

    @property
    def epw(self) -> float:
        """
        Effective page width: the page width minus its horizontal margins.
        """
        return self.w - self.l_margin - self.r_margin

    @property
    def eph(self) -> float:
        """
        Effective page height: the page height minus its vertical margins.
        """
        return self.h - self.t_margin - self.b_margin

    @property
    def pages_count(self) -> int:
        """
        Returns the total pages of the document, at the time it is called.

        Do not use this in `fpdf.fpdf.FPDF.header()` or `fpdf.fpdf.FPDF.footer()`,
        as its value will not be the total page count.
        Uses `{nb}` instead, _cf._ `fpdf.fpdf.FPDF.alias_nb_pages()`.
        """
        return len(self.pages)

    def set_margin(self, margin: float) -> None:
        """
        Sets the document right, left, top & bottom margins to the same value.

        Args:
            margin (float): margin in the unit specified to FPDF constructor
        """
        self.set_margins(margin, margin)
        self.set_auto_page_break(self.auto_page_break, margin)

    def set_margins(self, left: float, top: float, right: float = -1) -> None:
        """
        Sets the document left, top & optionally right margins to the same value.
        By default, they equal 1 cm.
        Also sets the current FPDF.y on the page to this minimum vertical position.

        Args:
            left (float): left margin in the unit specified to FPDF constructor
            top (float): top margin in the unit specified to FPDF constructor
            right (float): optional right margin in the unit specified to FPDF constructor
        """
        self.set_left_margin(left)
        if self.y < top or self.y == self.t_margin:
            self.y = top
        self.t_margin = top
        if right == -1:
            right = left
        self.r_margin = right

    def set_left_margin(self, margin: float) -> None:
        """
        Sets the document left margin.
        Also sets the current FPDF.x on the page to this minimum horizontal position.

        Args:
            margin (float): margin in the unit specified to FPDF constructor
        """
        if self.x < margin or self.x == self.l_margin:
            self.x = margin
        self.l_margin = margin

    def set_top_margin(self, margin: float) -> None:
        """
        Sets the document top margin.

        Args:
            margin (float): margin in the unit specified to FPDF constructor
        """
        self.t_margin = margin

    def set_right_margin(self, margin: float) -> None:
        """
        Sets the document right margin.

        Args:
            margin (float): margin in the unit specified to FPDF constructor
        """
        self.r_margin = margin

    def set_auto_page_break(self, auto: bool, margin: float = 0) -> None:
        """
        Set auto page break mode, and optionally the bottom margin that triggers it.
        By default, the mode is on and the bottom margin is 2 cm.

        Detailed documentation on page breaks: https://py-pdf.github.io/fpdf2/PageBreaks.html

        Args:
            auto (bool): enable or disable this mode
            margin (float): optional bottom margin (distance from the bottom of the page)
                in the unit specified to FPDF constructor
        """
        self.auto_page_break: bool = auto
        self.b_margin: float = margin
        self.page_break_trigger: float = self.h - self.b_margin

    @property
    def default_page_dimensions(self) -> tuple[float, float]:
        "Return a pair (width, height) in points units (1/72 of inch)"
        return (
            (self.dw_pt, self.dh_pt)
            if self.def_orientation == PageOrientation.PORTRAIT
            else (self.dh_pt, self.dw_pt)
        )

    def _set_orientation(
        self,
        orientation: str | PageOrientation,
        page_width_pt: float,
        page_height_pt: float,
    ) -> None:
        self.cur_orientation = PageOrientation.coerce(orientation)
        if self.cur_orientation is PageOrientation.PORTRAIT:
            self.w_pt = page_width_pt
            self.h_pt = page_height_pt
        else:
            self.w_pt = page_height_pt
            self.h_pt = page_width_pt
        self.w = self.w_pt / self.k
        self.h = self.h_pt / self.k
        if hasattr(self, "auto_page_break"):  # not set when called from constructor
            # When self.h is modified, the .page_break_trigger must be re-computed:
            self.set_auto_page_break(self.auto_page_break, self.b_margin)

    def set_display_mode(
        self,
        zoom: str | float,
        layout: str = "continuous",
    ) -> None:
        """
        Defines the way the document is to be displayed by the viewer.

        It allows to set the zoom level: pages can be displayed entirely on screen,
        occupy the full width of the window, use the real size,
        be scaled by a specific zooming factor or use the viewer default (configured in its Preferences menu).

        The page layout can also be specified: single page at a time, continuous display, two columns or viewer default.

        Args:
            zoom: either "fullpage", "fullwidth", "real", "default",
                or a number indicating the zooming factor to use, interpreted as a percentage.
                The zoom level set by default is "default".
            layout (fpdf.enums.PageLayout, str): allowed layout aliases are "single", "continuous", "two" or "default",
                meaning to use the viewer default mode.
                The layout set by default is "continuous".
        """
        if zoom in ZOOM_CONFIGS or not isinstance(zoom, str):
            self.zoom_mode = zoom
        elif zoom != "default":
            raise FPDFException(f"Incorrect zoom display mode: {zoom}")
        if isinstance(layout, PageLayout):
            self.page_layout = layout
        else:
            # First support legacy aliases like "continuous"/"single"/"default"
            alias_layout = LAYOUT_ALIASES.get(str(layout))
            if alias_layout is not None or str(layout) in LAYOUT_ALIASES:
                self.page_layout = alias_layout
            else:
                try:
                    self.page_layout = PageLayout.coerce(str(layout))
                except (ValueError, TypeError) as exc:
                    raise FPDFException(
                        f"Incorrect layout display mode: {layout}"
                    ) from exc

    def set_text_shaping(
        self,
        use_shaping_engine: bool = True,
        features: Optional[dict[str, Any]] = None,
        direction: Optional[str | TextDirection] = None,
        script: Optional[str] = None,
        language: Optional[str] = None,
    ) -> None:
        """
        Enable or disable text shaping engine when rendering text.
        If features, direction, script or language are not specified the shaping engine will try
        to guess the values based on the input text.

        Args:
            use_shaping_engine: enable or disable the use of the shaping engine to process the text
            features: a dictionary containing 4 digit OpenType features and whether each feature
                should be enabled or disabled
                example: features={"kern": False, "liga": False}
            direction: the direction the text should be rendered, either "ltr" (left to right)
                or "rtl" (right to left).
            script: a valid OpenType script tag like "arab" or "latn"
            language: a valid OpenType language tag like "eng" or "fra"
        """
        if not use_shaping_engine:
            self.text_shaping = None
            return

        try:
            # pylint: disable=import-outside-toplevel, unused-import
            import uharfbuzz  # pyright: ignore[reportUnusedImport]
        except ImportError as exc:
            raise FPDFException(
                "The uharfbuzz package could not be imported, but is required for text shaping. Try: pip install uharfbuzz"
            ) from exc

        #
        # Features must be a dictionary containing opentype features and a boolean flag
        # stating whether the feature should be enabled or disabled.
        #
        # e.g. features={"liga": True, "kern": False}
        #
        # https://harfbuzz.github.io/shaping-opentype-features.html
        #

        if features and not isinstance(features, dict):
            raise FPDFException(
                "Features must be a dictionary. See text shaping documentation"
            )
        if not features:
            features = {}

        # Buffer properties (direction, script and language)
        # if the properties are not provided, Harfbuzz "guessing" logic is used.
        # https://harfbuzz.github.io/setting-buffer-properties.html
        # Valid harfbuzz directions are ltr (left to right), rtl (right to left),
        # ttb (top to bottom) or btt (bottom to top)

        text_direction = None
        if direction:
            text_direction = (
                direction
                if isinstance(direction, TextDirection)
                else TextDirection.coerce(direction)
            )
            if text_direction not in [TextDirection.LTR, TextDirection.RTL]:
                raise FPDFException(
                    "FPDF2 only accept ltr (left to right) or rtl (right to left) directions for now."
                )

        self.text_shaping = {
            "use_shaping_engine": True,
            "features": features,
            "direction": text_direction,
            "script": script,
            "language": language,
            "fragment_direction": None,
            "paragraph_direction": None,
        }

    @property
    def page_layout(self) -> Optional[PageLayout]:
        return self._page_layout

    @page_layout.setter
    def page_layout(self, page_layout: Optional[str | PageLayout]) -> None:
        self._page_layout = PageLayout.coerce(page_layout) if page_layout else None
        if self._page_layout in (PageLayout.TWO_PAGE_LEFT, PageLayout.TWO_PAGE_RIGHT):
            self._set_min_pdf_version("1.5")

    def set_compression(self, compress: bool) -> None:
        """
        Activates or deactivates page compression.

        When activated, the internal representation of each page is compressed
        using the zlib/deflate method (FlateDecode), which leads to a compression ratio
        of about 2 for the resulting document.

        Page compression is enabled by default.

        Args:
            compress (bool): indicates if compression should be enabled
        """
        self.compress = compress

    def set_title(self, title: str) -> None:
        """
        Defines the title of the document.

        Most PDF readers will display it when viewing the document.
        There is also a related `fpdf.prefs.ViewerPreferences` entry:

            pdf.viewer_preferences = ViewerPreferences(display_doc_title=True)

        Args:
            title (str): the title
        """
        self.title = title

    def set_lang(self, lang: str) -> None:
        """
        A language identifier specifying the natural language for all text in the document
        except where overridden by language specifications for structure elements or marked content.
        A language identifier can either be the empty text string, to indicate that the language is unknown,
        or a Language-Tag as defined in RFC 3066, "Tags for the Identification of Languages".

        Args:
            lang (str): the document main language
        """
        self.lang = lang
        if lang:
            self._set_min_pdf_version("1.4")

    def set_subject(self, subject: str) -> None:
        """
        Defines the subject of the document.

        Args:
            subject (str): the document main subject
        """
        self.subject = subject

    def set_author(self, author: str | Sequence[str]) -> None:
        """
        Defines the author of the document.

        Args:
            author(str): the name of the author
        """
        self.author = author

    def set_keywords(self, keywords: str | Sequence[str]) -> None:
        """
        Associate keywords with the document

        Args:
            keywords (str): a space-separated list of words
        """
        self.keywords = keywords

    def set_creator(self, creator: str) -> None:
        """
        Defines the creator of the document.
        This is typically the name of the application that generates the PDF.

        Args:
            creator (str): name of the PDF creator
        """
        self.creator = creator

    def set_producer(self, producer: str) -> None:
        """Producer of document"""
        self.producer = producer

    def set_creation_date(self, date: Optional[datetime] = None) -> None:
        """Sets Creation of Date time, or current time if None given."""
        if self._sign_key:
            raise FPDFException(
                ".set_creation_date() must always be called before .sign*() methods"
            )
        if not isinstance(date, datetime):
            raise TypeError(f"date should be a datetime but is a {type(date)}")
        if not date.tzinfo:
            date = date.astimezone()
        self.creation_date = date

    def set_xmp_metadata(self, xmp_metadata: str) -> None:
        if "<?xpacket" in xmp_metadata[:50]:
            raise ValueError(
                "fpdf2 already performs XMP metadata wrapping in a <?xpacket> tag"
            )
        self.xmp_metadata = xmp_metadata
        if xmp_metadata:
            self._set_min_pdf_version("1.4")

    def set_doc_option(self, opt: Literal["core_fonts_encoding"], value: str) -> None:
        """
        Defines a document option.

        Args:
            opt (str): name of the option to set
            value (str) option value

        .. deprecated:: 2.4.0
            Simply set the `FPDF.core_fonts_encoding` property as a replacement.
        """
        warnings.warn(
            (
                "set_doc_option() is deprecated since v2.4.0 "
                "and will be removed in a future release. "
                "Simply set the `.core_fonts_encoding` property as a replacement."
            ),
            DeprecationWarning,
            stacklevel=get_stack_level(),
        )
        if opt != "core_fonts_encoding":
            raise FPDFException(f'Unknown document option "{opt}"')
        self.core_fonts_encoding = value

    def set_image_filter(self, image_filter: str) -> None:
        """
        Args:
            image_filter (str): name of a the image filter to use
                when embedding images in the document, or "AUTO",
                meaning to use the best image filter given the images provided.
                Allowed values: `FlateDecode` (lossless zlib/deflate compression),
                `DCTDecode` (lossy compression with JPEG)
                `LZWDecode` (Lempel-Ziv-Welch aka LZW compression)
                and `JPXDecode` (lossy compression with JPEG2000).

        [**NEW in 2.8.4**] Note that, when using `LZWDecode`, having NumPy installed
        will improve performances, reducing execution time.
        """
        if image_filter not in SUPPORTED_IMAGE_FILTERS:
            raise ValueError(
                f"'{image_filter}' is not a supported image filter"
                f" - Allowed values: {''.join(SUPPORTED_IMAGE_FILTERS)}"
            )
        self.image_cache.image_filter = cast(ImageFilter, image_filter)
        if image_filter == "JPXDecode":
            self._set_min_pdf_version("1.5")

    def alias_nb_pages(self, alias: str = "{nb}") -> None:
        """
        Defines an alias for the total number of pages.
        It will be substituted as the document is closed.

        This is useful to insert the number of pages of the document
        at a time when this number is not known by the program.

        This substitution can be disabled for performances reasons, by calling `alias_nb_pages(None)`.

        Args:
            alias (str): the alias. Defaults to `"{nb}"`.

        Notes
        -----

        When using this feature with the `FPDF.cell` / `FPDF.multi_cell` methods,
        or the `.underline` / `.strikethrough` attributes of `FPDF` class,
        the width of the text rendered will take into account the alias length,
        not the length of the "actual number of pages" string,
        which can causes slight positioning differences.
        """
        self.str_alias_nb_pages = alias

    @check_page
    def set_page_label(
        self,
        label_style: Optional[str | PageLabelStyle] = None,
        label_prefix: Optional[str] = None,
        label_start: Optional[int] = None,
    ) -> None:
        """
        Enable `fpdf.output.PDFPageLabel` to be inserted on every page.
        This will be displayed by some PDF readers to identify pages.
        """
        current_page_label = None
        if self.page in self.pages:
            current_page_label = self.pages[self.page].get_page_label()
        elif self.page > 1:
            current_page_label = self.pages[self.page - 1].get_page_label()
        new_page_label = None
        if label_style or label_prefix or label_start:
            if current_page_label:
                if label_style is None:
                    label_style = current_page_label.get_style()
                if label_prefix is None:
                    label_prefix = current_page_label.get_prefix()
                if label_start is None and not (
                    self.toc_placeholder and self.toc_placeholder.reset_page_indices
                ):
                    label_start = current_page_label.get_start()
            label_style = (
                PageLabelStyle.coerce(label_style, case_sensitive=True)
                if label_style
                else None
            )
            new_page_label = PDFPageLabel(label_style, label_prefix, label_start)
        self.pages[self.page].set_page_label(current_page_label, new_page_label)

    def add_page(
        self,
        orientation: str = "",
        format: str = "",
        same: bool = False,
        duration: float = 0,
        transition: Optional[Transition] = None,
        label_style: Optional[str | PageLabelStyle] = None,
        label_prefix: Optional[str] = None,
        label_start: Optional[int] = None,
    ) -> None:
        """
        Adds a new page to the document.
        If a page is already present, the `FPDF.footer()` method is called first.
        Then the page  is added, the current position is set to the top-left corner,
        with respect to the left and top margins, and the `FPDF.header()` method is called.

        Args:
            orientation (str): "portrait" (can be abbreviated "P")
                or "landscape" (can be abbreviated "L"). Default to "portrait".
            format (str): "a3", "a4", "a5", "letter", "legal" or a tuple
                (width, height). Default to "a4".
            same (bool): indicates to use the same page format as the previous page.
                Default to False.
            duration (float): optional page’s display duration, i.e. the maximum length of time,
                in seconds, that the page is displayed in presentation mode,
                before the viewer application automatically advances to the next page.
                Can be configured globally through the `.page_duration` FPDF property.
                As of june 2021, onored by Adobe Acrobat reader, but ignored by Sumatra PDF reader.
            transition (Transition child class): optional visual transition to use when moving
                from another page to the given page during a presentation.
                Can be configured globally through the `.page_transition` FPDF property.
                As of june 2021, onored by Adobe Acrobat reader, but ignored by Sumatra PDF reader.
            label_style (str or PageLabelStyle): Defines the numbering style for the numeric portion of each
                page label. Possible values are:
                - "D": Decimal Arabic numerals.
                - "R": Uppercase Roman numerals.
                - "r": Lowercase Roman numerals.
                - "A": Uppercase letters (A to Z for the first 26 pages, followed by AA to ZZ, etc.).
                - "a": Lowercase letters (a to z for the first 26 pages, followed by aa to zz, etc.).
            label_prefix (str): Prefix string applied to the page label, preceding the numeric portion.
            label_start (int): Starting number for the first page of a page label range.
        """
        if self.buffer:
            raise FPDFException(
                "A page cannot be added on a closed document, after calling output()"
            )

        self.current_font_is_set_on_page = False

        family = self.font_family
        emphasis = self.emphasis
        size = self.font_size_pt
        lw = self.line_width
        dc = self.draw_color
        fc = self.fill_color
        tc = self.text_color
        stretching = self.font_stretching
        char_spacing = self.char_spacing
        dash_pattern = self.dash_pattern

        in_toc_extra_page = (
            self.in_toc_rendering
            and self._toc_allow_page_insertion
            and self.page > self.toc_placeholder.start_page  # type: ignore[union-attr]
        )
        if self.page > 0 and (not self.in_toc_rendering or in_toc_extra_page):
            # Page footer
            self._render_footer()

        current_page_label = (
            None if self.page == 0 else self.pages[self.page].get_page_label()
        )
        new_page_label = None
        if label_style or label_prefix or label_start:
            label_style = (
                PageLabelStyle.coerce(label_style, case_sensitive=True)
                if label_style
                else None
            )
            new_page_label = PDFPageLabel(label_style, label_prefix, label_start)

        # Start new page
        self._beginpage(
            orientation,
            format,
            same,
            duration or self.page_duration,
            transition or self.page_transition,
            new_page=not self._has_next_page(),
        )

        self.pages[self.page].set_page_label(current_page_label, new_page_label)

        if self.page_background:
            if isinstance(self.page_background, tuple):
                self.set_fill_color(*self.page_background)
                self.rect(0, 0, self.w, self.h, style="F")
                assert isinstance(fc, (DeviceRGB, DeviceGray))
                self.set_fill_color(*fc.colors255)
            else:
                self.image(
                    self.page_background,  # pyright: ignore[reportArgumentType]
                    0,
                    0,
                    self.w,
                    self.h,
                )

        self._out("2 J")  # Set line cap style to square
        self.line_width = lw  # Set line width
        self._out(f"{lw * self.k:.2f} w")

        # Set font
        if family:
            self.set_font(family, emphasis, size)

        # Set colors
        self.draw_color = dc
        if dc != self.DEFAULT_DRAW_COLOR and dc is not None:
            self._out(dc.serialize().upper())
        self.fill_color = fc
        if fc != self.DEFAULT_FILL_COLOR and fc is not None:
            self._out(fc.serialize().lower())
        self.text_color = tc

        # BEGIN Page header
        if (not self.in_toc_rendering) or self._toc_allow_page_insertion:
            self.header()

        if self.line_width != lw:  # Restore line width
            self.line_width = lw
            self._out(f"{lw * self.k:.2f} w")

        if family:
            self.set_font(family, emphasis, size)  # Restore font

        if self.draw_color != dc and dc is not None:  # Restore colors
            self.draw_color = dc
            self._out(dc.serialize().upper())
        if self.fill_color != fc and fc is not None:
            self.fill_color = fc
            self._out(fc.serialize().lower())
        self.text_color = tc

        if stretching != 100:  # Restore stretching
            self.set_stretching(stretching)
        if char_spacing != 0:
            self.set_char_spacing(char_spacing)
        if dash_pattern != dict(dash=0, gap=0, phase=0):
            self._write_dash_pattern(
                dash_pattern["dash"], dash_pattern["gap"], dash_pattern["phase"]
            )
        # END Page header

    def _render_footer(self) -> None:
        self.in_footer = True
        if self.toc_placeholder:
            # The ToC is rendered AFTER the footer,
            # so we must ensure there is no "style leak":
            self._push_local_stack()
            self._start_local_context()
        self.footer()
        if self.toc_placeholder:
            self._end_local_context()
            self._pop_local_stack()
        self.in_footer = False

    def _beginpage(
        self,
        orientation: str | PageOrientation,
        format: str | tuple[float, float],
        same: bool,
        duration: Optional[float],
        transition: Optional[Transition],
        new_page: bool = True,
    ) -> None:
        self.page += 1
        if self.in_toc_rendering and self._toc_allow_page_insertion:
            self._toc_inserted_pages += 1
            self.page = len(self.pages) + 1
            new_page = True
        if new_page:
            page = PDFPage(
                contents=bytearray(),
                duration=duration,
                transition=transition,
                index=self.page,
            )
            self.pages[self.page] = page
            if transition:
                self._set_min_pdf_version("1.5")
        else:
            page = self.pages[self.page]
        self.x = self.l_margin
        self.y = self.t_margin
        self.font_family = ""
        self.font_stretching = 100
        self.char_spacing = 0
        if same:
            if orientation or format:
                raise ValueError(
                    f"Inconsistent parameters: same={same} but orientation={orientation} format={format}"
                )
        else:
            # Set page format if provided, else use default value:
            page_width_pt, page_height_pt = (
                get_page_format(format, self.k) if format else (self.dw_pt, self.dh_pt)
            )
            self._set_orientation(
                orientation or self.def_orientation, page_width_pt, page_height_pt
            )
        page.set_dimensions(self.w_pt, self.h_pt)

    def header(self) -> None:
        """
        Header to be implemented in your own inherited class

        This is automatically called by `FPDF.add_page()`
        and should not be called directly by the user application.
        The default implementation performs nothing: you have to override this method
        in a subclass to implement your own rendering logic.

        Note that header rendering can have an impact on the initial
        (x,y) position when starting to render the page content.
        """

    def footer(self) -> None:
        """
        Footer to be implemented in your own inherited class.

        This is automatically called by `FPDF.add_page()` and `FPDF.output()`
        and should not be called directly by the user application.
        The default implementation performs nothing: you have to override this method
        in a subclass to implement your own rendering logic.
        """

    def page_no(self) -> int:
        """Get the current page number"""
        return self.page

    def get_page_label(self) -> str:
        """
        Return the current page `fpdf.output.PDFPageLabel`.
        This will be displayed by some PDF readers to identify pages.
        `FPDF.set_page_label()` needs to be called first for those to be inserted.
        """
        return self.pages[self.page].get_label()

    def set_draw_color(
        self, r: Number | Color | str | Sequence[Number], g: Number = -1, b: Number = -1
    ) -> None:
        """
        Defines the color used for all stroking operations (lines, rectangles and cell borders).
        Accepts either a single greyscale value, 3 values as RGB components, a single `#abc` or `#abcdef` hexadecimal color string,
        or an instance of `fpdf.drawing.DeviceCMYK`, `fpdf.drawing.DeviceRGB` or `fpdf.drawing.DeviceGray`.
        The method can be called before the first page is created and the value is retained from page to page.

        Args:
            r (int, tuple, fpdf.drawing.DeviceGray, fpdf.drawing.DeviceRGB): if `g` and `b` are given, this indicates the red component.
                Else, this indicates the grey level. The value must be between 0 and 255.
            g (int): green component (between 0 and 255)
            b (int): blue component (between 0 and 255)
        """
        draw_color = convert_to_device_color(r, g, b)
        if draw_color != self.draw_color:
            self.draw_color = draw_color
            if self.page > 0:
                self._out(
                    self.draw_color.serialize().upper()  # pyright: ignore[reportOptionalMemberAccess]
                )

    def set_fill_color(
        self, r: Number | Color | str | Sequence[Number], g: Number = -1, b: Number = -1
    ) -> None:
        """
        Defines the color used for all filling operations (filled rectangles and cell backgrounds).
        Accepts either a single greyscale value, 3 values as RGB components, a single `#abc` or `#abcdef` hexadecimal color string,
        or an instance of `fpdf.drawing.DeviceCMYK`, `fpdf.drawing.DeviceRGB` or `fpdf.drawing.DeviceGray`.
        The method can be called before the first page is created and the value is retained from page to page.

        Args:
            r (int, tuple, fpdf.drawing.DeviceGray, fpdf.drawing.DeviceRGB): if `g` and `b` are given, this indicates the red component.
                Else, this indicates the grey level. The value must be between 0 and 255.
            g (int): green component (between 0 and 255)
            b (int): blue component (between 0 and 255)
        """
        fill_color = convert_to_device_color(r, g, b)
        if fill_color != self.fill_color:
            self.fill_color = fill_color
            if self.page > 0:
                self._out(
                    self.fill_color.serialize().lower()  # pyright: ignore[reportOptionalMemberAccess]
                )

    def set_text_color(
        self,
        r: (
            Number
            | Color
            | str
            | Sequence[Number]
            | DeviceCMYK
            | DeviceGray
            | DeviceRGB
        ),
        g: Number = -1,
        b: Number = -1,
    ) -> None:
        """
        Defines the color used for text.
        Accepts either a single greyscale value, 3 values as RGB components, a single `#abc` or `#abcdef` hexadecimal color string,
        or an instance of `fpdf.drawing.DeviceCMYK`, `fpdf.drawing.DeviceRGB` or `fpdf.drawing.DeviceGray`.
        The method can be called before the first page is created and the value is retained from page to page.

        Args:
            r (int, tuple, fpdf.drawing.DeviceGray, fpdf.drawing.DeviceRGB): if `g` and `b` are given, this indicates the red component.
                Else, this indicates the grey level. The value must be between 0 and 255.
            g (int): green component (between 0 and 255)
            b (int): blue component (between 0 and 255)
        """
        self.text_color = convert_to_device_color(r, g, b)

    def get_string_width(
        self, s: str, normalized: bool = False, markdown: bool = False
    ) -> float:
        """
        Returns the length of a string in user unit. A font must be selected.
        The value is calculated with stretching and spacing.

        Note that the width of a cell has some extra padding added to this width,
        on the left & right sides, equal to the .c_margin property.

        Args:
            s (str): the string whose length is to be computed.
            normalized (bool): whether normalization needs to be performed on the input string.
            markdown (bool): indicates if basic markdown support is enabled
        """
        if not self.font_family:
            raise FPDFException("No font set, you need to call set_font() beforehand")
        # normalized is parameter for internal use
        s = s if normalized else self.normalize_text(s)
        return sum(
            frag.get_width() for frag in self._preload_bidirectional_text(s, markdown)
        )

    def set_line_width(self, width: float) -> None:
        """
        Defines the line width of all stroking operations (lines, rectangles and cell borders).
        By default, the value equals 0.2 mm.
        The method can be called before the first page is created and the value is retained from page to page.

        Args:
            width (float): the width in user unit
        """
        if width != self.line_width:
            self.line_width = width
            if self.page > 0:
                self._out(f"{width * self.k:.2f} w")

    def set_page_background(
        self, background: Optional[str | BinaryIO | Image | DeviceRGB | tuple[float]]
    ) -> None:
        """
        Sets a background color or image to be drawn every time `FPDF.add_page()` is called, or removes a previously set background.
        The method can be called before the first page is created and the value is retained from page to page.

        Args:
            background: either a string representing a file path or URL to an image,
                an io.BytesIO containing an image as bytes, an instance of `PIL.Image.Image`, drawing.DeviceRGB
                or a RGB tuple representing a color to fill the background with or `None` to remove the background
        """

        if isinstance(
            background, (str, io.BytesIO, Image, DeviceRGB, tuple, type(None))
        ):
            if isinstance(background, DeviceRGB):
                self.page_background = background.colors255
            else:
                self.page_background = background
        else:
            raise TypeError(
                f"""background must be of type str, io.BytesIO, PIL.Image.Image, drawing.DeviceRGB, tuple or None
        got: {type(background)}"""
            )

    @contextmanager
    @check_page
    def drawing_context(
        self, debug_stream: Optional[bool] = None  # pylint: disable=unused-argument
    ) -> Iterator[DrawingContext]:
        """
        Create a context for drawing paths on the current page.

        If this context manager is called again inside of an active context, it will
        raise an exception, as base drawing contexts cannot be nested.
        """

        if self._current_draw_context is not None:
            raise FPDFException(
                "cannot create a drawing context while one is already open"
            )

        context = DrawingContext()
        self._current_draw_context = context
        try:
            yield context
        finally:
            self._current_draw_context = None

        starting_style = self._current_graphic_style()
        render_args = (
            self._resource_catalog,
            Point(self.x, self.y),
            self.k,
            self.h,
            starting_style,
        )

        rendered = context.render(*render_args)

        # Let the catalog scan & register resources used by this drawing:
        self._resource_catalog.index_stream_resources(rendered, self.page)
        # Once we handle text-rendering SVG tags (cf. PR #1029),
        # we should also detect fonts used and add them to the resource catalog

        self._out(rendered)
        # The drawing API makes use of features (notably transparency and blending modes) that were introduced in PDF 1.4:
        self._set_min_pdf_version("1.4")

    @contextmanager
    @check_page
    def use_pattern(self, shading: Gradient) -> Iterator[None]:
        """
        Create a context for using a shading pattern on the current page.
        """
        self._resource_catalog.add(PDFResourceType.SHADING, shading, self.page)
        pattern = shading.get_pattern()
        pattern_name = self._resource_catalog.add(
            PDFResourceType.PATTERN, pattern, self.page
        )
        self._out(f"/Pattern cs /{pattern_name} scn")
        try:
            yield
        finally:
            assert self.draw_color is not None
            self._out(self.draw_color.serialize().lower())

    def _current_graphic_style(self) -> GraphicsStyle:
        gs = GraphicsStyle()
        gs.allow_transparency = self.allow_images_transparency

        # This initial stroke_width is ignored when embedding SVGs,
        # as the value in SVGObject.convert_graphics() takes precedence,
        # so this probably creates an unnecessary PDF dict entry:
        gs.stroke_width = self.line_width

        if self.draw_color != self.DEFAULT_DRAW_COLOR:
            gs.stroke_color = self.draw_color
        if self.fill_color != self.DEFAULT_FILL_COLOR:
            gs.fill_color = self.fill_color

        dash_info = self.dash_pattern
        dash_pattern: Optional[tuple[float, float]] = (
            (dash_info["dash"], dash_info["gap"])
            if dash_info["dash"] != 0 and dash_info["gap"] != 0
            else None
        )

        gs.stroke_dash_pattern = dash_pattern
        gs.stroke_dash_phase = dash_info["phase"]

        return gs

    @contextmanager
    def new_path(
        self,
        x: float = 0,
        y: float = 0,
        paint_rule: PathPaintRule = PathPaintRule.AUTO,
        debug_stream: Optional[bool] = None,  # pylint: disable=unused-argument
    ) -> Iterator[PaintedPath]:
        """
        Create a path for appending lines and curves to.

        Args:
            x (float): Abscissa of the path starting point
            y (float): Ordinate of the path starting point
            paint_rule (PathPaintRule): Optional choice of how the path should
                be painted. The default (AUTO) automatically selects stroke/fill based
                on the path style settings.
        """
        with self.drawing_context() as ctxt:
            path = PaintedPath(x=x, y=y)
            path.style.paint_rule = paint_rule
            yield path
            ctxt.add_item(path)

    def draw_path(
        self,
        path: GraphicsContext,
        debug_stream: Optional[bool] = None,  # pylint: disable=unused-argument
        copy: bool = True,
    ) -> None:
        """
        Add a pre-constructed path to the document.

        Args:
            path (drawing.PaintedPath): the path to be drawn.
            copy (bool): if true (the default), the path will be copied before being
                added. This prevents modifications to a referenced object from
                "retroactively" altering its style/shape and should be disabled with
                caution.
        """
        with self.drawing_context() as ctxt:
            ctxt.add_item(path, copy)

    def set_dash_pattern(
        self, dash: float = 0, gap: float = 0, phase: float = 0
    ) -> None:
        """
        Set the current dash pattern for lines and curves.

        Args:
            dash (float): The length of the dashes in current units.

            gap (float): The length of the gaps between dashes in current units.
                If omitted, the dash length will be used.

            phase (float): Where in the sequence to start drawing.

        Omitting 'dash' (= 0) resets the pattern to a solid line.
        """
        if not (isinstance(dash, (int, float)) and dash >= 0):
            raise ValueError("Dash length must be zero or a positive number.")
        if not (isinstance(gap, (int, float)) and gap >= 0):
            raise ValueError("gap length must be zero or a positive number.")
        if not (isinstance(phase, (int, float)) and phase >= 0):
            raise ValueError("Phase must be zero or a positive number.")

        pattern: dict[str, float] = dict(
            dash=float(dash), gap=float(gap), phase=float(phase)
        )

        if pattern != self.dash_pattern:
            self.dash_pattern = pattern
            self._write_dash_pattern(dash, gap, phase)

    def _write_dash_pattern(self, dash: float, gap: float, phase: float) -> None:
        if dash:
            if gap:
                dstr = f"[{dash * self.k:.3f} {gap * self.k:.3f}] {phase *self.k:.3f} d"
            else:
                dstr = f"[{dash * self.k:.3f}] {phase *self.k:.3f} d"
        else:
            dstr = "[] 0 d"
        self._out(dstr)

    @contextmanager
    def glyph_drawing_context(self) -> Iterator[DrawingContext]:
        """
        Create a context for drawing paths for type 3 font glyphs, without writing on the current page.
        """

        if self._current_draw_context is not None:
            raise FPDFException(
                "cannot create a drawing context while one is already open"
            )

        context = DrawingContext()
        self._current_draw_context = context
        try:
            yield context
        finally:
            self._current_draw_context = None

        self._set_min_pdf_version("1.4")

    def draw_vector_glyph(
        self, path: Union[PaintedPath, GraphicsContext], font: "Type3Font"
    ) -> str:
        """
        Add a pre-constructed path to the document.
        """
        output_stream: str = ""
        with self.glyph_drawing_context() as ctxt:
            ctxt.add_item(path)

            starting_style = GraphicsStyle()
            render_args = (
                self._resource_catalog,
                Point(0, 0),
                1,
                0,
                starting_style,
            )

            output_stream = ctxt.render(*render_args)
            # Registering raster images embedded in the vector graphics:
            for resource_type, resource_id in self._resource_catalog.scan_stream(
                output_stream
            ):
                if resource_type == PDFResourceType.X_OBJECT:
                    font.images_used.add(int(resource_id))
                if resource_type == PDFResourceType.EXT_G_STATE:
                    font.graphics_style_used.add(resource_id)
                if resource_type == PDFResourceType.PATTERN:
                    font.patterns_used.add(resource_id)

        return output_stream

    @check_page
    def line(self, x1: float, y1: float, x2: float, y2: float) -> None:
        """
        Draw a line between two points.

        Args:
            x1 (float): Abscissa of first point
            y1 (float): Ordinate of first point
            x2 (float): Abscissa of second point
            y2 (float): Ordinate of second point
        """
        self._out(
            f"{x1 * self.k:.2f} {(self.h - y1) * self.k:.2f} m {x2 * self.k:.2f} "
            f"{(self.h - y2) * self.k:.2f} l S"
        )

    @check_page
    def polyline(
        self,
        point_list: Sequence[tuple[float, float]],
        fill: bool = False,
        polygon: bool = False,
        style: Optional[RenderStyle | str] = None,
    ) -> None:
        """
        Draws lines between two or more points.

        Args:
            point_list (list of tuples): List of Abscissa and Ordinate of
                                        segments that should be drawn
            fill (bool): [**DEPRECATED since v2.5.4**] Use `style="F"` or `style="DF"` instead
            polygon (bool): If true, close path before stroking, to fill the inside of the polyline
            style (fpdf.enums.RenderStyle, str): Optional style of rendering. Possible values are:

            * `D` or None: draw border. This is the default value.
            * `F`: fill
            * `DF` or `FD`: draw and fill
        """
        if fill:
            warnings.warn(
                (
                    '"fill" parameter is deprecated since v2.5.4, '
                    'use style="F" or style="DF" instead'
                ),
                DeprecationWarning,
                stacklevel=get_stack_level(),
            )
        if fill and style is None:
            style = RenderStyle.DF
        else:
            style = RenderStyle.coerce(style) if style is not None else RenderStyle.D
            if fill and style == RenderStyle.D:
                raise ValueError(
                    f"Conflicting values provided: fill={fill} & style={style}"
                )
        operator = "m"
        for point in point_list:
            self._out(
                f"{point[0] * self.k:.2f} {(self.h - point[1]) * self.k:.2f} {operator}"
            )
            operator = "l"
        if polygon:
            self._out(" h")
        self._out(f" {style.operator}")

    @check_page
    def polygon(
        self,
        point_list: Sequence[tuple[float, float]],
        fill: bool = False,
        style: Optional[RenderStyle | str] = None,
    ) -> None:
        """
        Outputs a polygon defined by three or more points.

        Args:
            point_list (list of tuples): List of coordinates defining the polygon to draw
            fill (bool): [**DEPRECATED since v2.5.4**] Use `style="F"` or `style="DF"` instead
            style (fpdf.enums.RenderStyle, str): Optional style of rendering. Possible values are:

            * `D` or None: draw border. This is the default value.
            * `F`: fill
            * `DF` or `FD`: draw and fill
        """
        self.polyline(point_list, fill=fill, polygon=True, style=style)

    @check_page
    def dashed_line(
        self,
        x1: float,
        y1: float,
        x2: float,
        y2: float,
        dash_length: float = 1,
        space_length: float = 1,
    ) -> None:
        """
        Draw a dashed line between two points.

        Args:
            x1 (float): Abscissa of first point
            y1 (float): Ordinate of first point
            x2 (float): Abscissa of second point
            y2 (float): Ordinate of second point
            dash_length (float): Length of the dash
            space_length (float): Length of the space between 2 dashes

        .. deprecated:: 2.4.6
            Use `FPDF.set_dash_pattern()` and the normal drawing operations instead.
        """
        warnings.warn(
            (
                "dashed_line() is deprecated since v2.4.6, "
                "and will be removed in a future release. "
                "Use set_dash_pattern() and the normal drawing operations instead."
            ),
            DeprecationWarning,
            stacklevel=get_stack_level(),
        )
        self.set_dash_pattern(dash_length, space_length)
        self.line(x1, y1, x2, y2)
        self.set_dash_pattern()

    @check_page
    def rect(
        self,
        x: float,
        y: float,
        w: float,
        h: float,
        style: Optional[RenderStyle | str] = None,
        round_corners: bool = False,
        corner_radius: float = 0,
    ) -> None:
        """
        Outputs a rectangle.
        It can be drawn (border only), filled (with no border) or both.

        Args:
            x (float): Abscissa of upper-left bounding box.
            y (float): Ordinate of upper-left bounding box.
            w (float): Width.
            h (float): Height.
            style (fpdf.enums.RenderStyle, str): Optional style of rendering. Possible values are:

            * `D` or empty string: draw border. This is the default value.
            * `F`: fill
            * `DF` or `FD`: draw and fill

            round_corners (tuple of str, tuple of fpdf.enums.Corner, bool): Optional draw a rectangle with round corners.
            Possible values are:

            *`TOP_LEFT`: a rectangle with round top left corner
            *`TOP_RIGHT`: a rectangle with round top right corner
            *`BOTTOM_LEFT`: a rectangle with round bottom left corner
            *`BOTTOM_RIGHT`: a rectangle with round bottom right corner
            *`True`: a rectangle with all round corners
            *`False`: a rectangle with no round corners

            corner_radius: Optional radius of the corners
        """

        style = RenderStyle.coerce(style) if style is not None else RenderStyle.D
        if round_corners is not False:
            self._draw_rounded_rect(x, y, w, h, style, round_corners, corner_radius)
        else:
            self._out(
                f"{x * self.k:.2f} {(self.h - y) * self.k:.2f} {w * self.k:.2f} "
                f"{-h * self.k:.2f} re {style.operator}"
            )

    def _draw_rounded_rect(
        self,
        x: float,
        y: float,
        w: float,
        h: float,
        style: RenderStyle,
        round_corners: bool | tuple[Corner | str, ...],
        r: float,
    ) -> None:
        min = h
        if w < h:
            min = w

        if r == 0:
            r = min / 5

        if r >= min / 2:
            r /= min

        # Calculate corner points
        point_1 = point_8 = (x, y)
        point_2 = (x + w, y)
        point_4 = (x + w, y + h)
        point_6 = (x, y + h)

        if round_corners is True:
            round_corners = (
                Corner.TOP_RIGHT.value,
                Corner.TOP_LEFT.value,
                Corner.BOTTOM_RIGHT.value,
                Corner.BOTTOM_LEFT.value,
            )
        assert not isinstance(round_corners, bool)
        round_corners_list: tuple[Corner, ...] = tuple(
            Corner.coerce(rc) for rc in round_corners
        )

        # Update points based on which corners are rounded
        if Corner.TOP_RIGHT in round_corners_list:
            point_1 = (x + r, y)
            point_8 = (x, y + r)

        if Corner.TOP_LEFT in round_corners_list:
            point_2 = (x + w - r, y)
            _point_3 = (x + w, y + r)

        if Corner.BOTTOM_LEFT in round_corners_list:
            point_4 = (x + w, y + h - r)
            _point_5 = (x + w - r, y + h)

        if Corner.BOTTOM_RIGHT in round_corners_list:
            point_6 = (x + r, y + h)
            _point_7 = (x, y + h - r)

        # Build a single continuous path
        # Start at point_1
        self._out(f"{point_1[0] * self.k:.2f} {(self.h - point_1[1]) * self.k:.2f} m")

        # Top edge: point_1 to point_2
        self._out(f"{point_2[0] * self.k:.2f} {(self.h - point_2[1]) * self.k:.2f} l")

        # Top-left corner arc
        if Corner.TOP_LEFT in round_corners_list:
            self._draw_arc_segment(x + w - 2 * r, y, 2 * r, 270, 0)

        # Right edge: point_3 to point_4
        self._out(f"{point_4[0] * self.k:.2f} {(self.h - point_4[1]) * self.k:.2f} l")

        # Bottom-left corner arc
        if Corner.BOTTOM_LEFT in round_corners_list:
            self._draw_arc_segment(x + w - 2 * r, y + h - 2 * r, 2 * r, 0, 90)

        # Bottom edge: point_5 to point_6
        self._out(f"{point_6[0] * self.k:.2f} {(self.h - point_6[1]) * self.k:.2f} l")

        # Bottom-right corner arc
        if Corner.BOTTOM_RIGHT in round_corners_list:
            self._draw_arc_segment(x, y + h - 2 * r, 2 * r, 90, 180)

        # Left edge: point_7 to point_8
        self._out(f"{point_8[0] * self.k:.2f} {(self.h - point_8[1]) * self.k:.2f} l")

        # Top-right corner arc
        if Corner.TOP_RIGHT in round_corners_list:
            self._draw_arc_segment(x, y, 2 * r, 180, 270)

        # Close path and apply style
        self._out(f"h {style.operator}")

    def _draw_arc_segment(
        self,
        x: float,
        y: float,
        a: float,
        start_angle: float,
        end_angle: float,
        b: Optional[float] = None,
    ) -> None:
        """
        Draw an arc segment as part of an existing path (no move, no style application).
        Used internally for building complex shapes like rounded rectangles.
        """
        if b is None:
            b = a

        a /= 2
        b /= 2

        cx = x + a
        cy = y + b

        def deg_to_rad(deg: float) -> float:
            return deg * math.pi / 180

        def angle_to_param(angle: float) -> float:
            angle = deg_to_rad(angle % 360)
            eta = math.atan2(math.sin(angle) / b, math.cos(angle) / a)
            if eta < 0:
                eta += 2 * math.pi
            return eta

        def evaluate(eta: float) -> list[float]:
            a_cos_eta = a * math.cos(eta)
            b_sin_eta = b * math.sin(eta)
            return [cx + a_cos_eta, cy + b_sin_eta]

        def derivative_evaluate(eta: float) -> list[float]:
            a_sin_eta = a * math.sin(eta)
            b_cos_eta = b * math.cos(eta)
            return [-a_sin_eta, b_cos_eta]

        start_eta = angle_to_param(start_angle)
        end_eta = angle_to_param(end_angle)

        if end_eta <= start_eta:
            end_eta += 2 * math.pi

        max_curves = 4
        n = min(
            max_curves, math.ceil(abs(end_eta - start_eta) / (2 * math.pi / max_curves))
        )
        d_eta = (end_eta - start_eta) / n

        alpha = math.sin(d_eta) * (math.sqrt(4 + 3 * math.tan(d_eta / 2) ** 2) - 1) / 3

        eta2 = start_eta
        p2 = evaluate(eta2)
        p2_prime = derivative_evaluate(eta2)

        for _ in range(n):
            p1 = p2
            p1_prime = p2_prime

            eta2 += d_eta
            p2 = evaluate(eta2)
            p2_prime = derivative_evaluate(eta2)

            control_point_1 = [p1[0] + alpha * p1_prime[0], p1[1] + alpha * p1_prime[1]]
            control_point_2 = [p2[0] - alpha * p2_prime[0], p2[1] - alpha * p2_prime[1]]

            self._out(
                f"{control_point_1[0] * self.k:.2f} {(self.h - control_point_1[1]) * self.k:.2f} "
                f"{control_point_2[0] * self.k:.2f} {(self.h - control_point_2[1]) * self.k:.2f} "
                f"{p2[0] * self.k:.2f} {(self.h - p2[1]) * self.k:.2f} c"
            )

    @check_page
    def ellipse(
        self,
        x: float,
        y: float,
        w: float,
        h: float,
        style: Optional[RenderStyle | str] = None,
    ) -> None:
        """
        Outputs an ellipse.
        It can be drawn (border only), filled (with no border) or both.

        Args:
            x (float): Abscissa of upper-left bounding box.
            y (float): Ordinate of upper-left bounding box.
            w (float): Width
            h (float): Height
            style (fpdf.enums.RenderStyle, str): Optional style of rendering. Possible values are:

            * `D` or empty string: draw border. This is the default value.
            * `F`: fill
            * `DF` or `FD`: draw and fill
        """
        style = RenderStyle.coerce(style) if style is not None else RenderStyle.D
        self._draw_ellipse(x, y, w, h, style.operator)

    def _draw_ellipse(
        self, x: float, y: float, w: float, h: float, operator: str
    ) -> None:
        cx = x + w / 2
        cy = y + h / 2
        rx = w / 2
        ry = h / 2

        lx = 4 / 3 * (math.sqrt(2) - 1) * rx
        ly = 4 / 3 * (math.sqrt(2) - 1) * ry

        self._out(
            (
                f"{(cx + rx) * self.k:.2f} {(self.h - cy) * self.k:.2f} m "
                f"{(cx + rx) * self.k:.2f} {(self.h - cy + ly) * self.k:.2f} "
                f"{(cx + lx) * self.k:.2f} {(self.h - cy + ry) * self.k:.2f} "
                f"{cx * self.k:.2f} {(self.h - cy + ry) * self.k:.2f} c"
            )
        )
        self._out(
            (
                f"{(cx - lx) * self.k:.2f} {(self.h - cy + ry) * self.k:.2f} "
                f"{(cx - rx) * self.k:.2f} {(self.h - cy + ly) * self.k:.2f} "
                f"{(cx - rx) * self.k:.2f} {(self.h - cy) * self.k:.2f} c"
            )
        )
        self._out(
            (
                f"{(cx - rx) * self.k:.2f} {(self.h - cy - ly) * self.k:.2f} "
                f"{(cx - lx) * self.k:.2f} {(self.h - cy - ry) * self.k:.2f} "
                f"{cx * self.k:.2f} {(self.h - cy - ry) * self.k:.2f} c"
            )
        )
        self._out(
            (
                f"{(cx + lx) * self.k:.2f} {(self.h - cy - ry) * self.k:.2f} "
                f"{(cx + rx) * self.k:.2f} {(self.h - cy - ly) * self.k:.2f} "
                f"{(cx + rx) * self.k:.2f} {(self.h - cy) * self.k:.2f} c {operator}"
            )
        )

    @check_page
    def circle(
        self,
        x: float,
        y: float,
        radius: float,
        style: Optional[RenderStyle | str] = None,
    ) -> None:
        """
        Outputs a circle.
        It can be drawn (border only), filled (with no border) or both.

        WARNING: This method changed parameters in [release 2.8.1](https://github.com/py-pdf/fpdf2/releases/tag/2.8.1)

        Args:
            x (float): Abscissa of upper-left bounding box.
            y (float): Ordinate of upper-left bounding box.
            radius (float): Radius of the circle.
            style (str): Style of rendering. Possible values are:

            * `D` or None: draw border. This is the default value.
            * `F`: fill
            * `DF` or `FD`: draw and fill
        """
        self.ellipse(x - radius, y - radius, 2 * radius, 2 * radius, style)

    @check_page
    def regular_polygon(
        self,
        x: float,
        y: float,
        numSides: int,
        polyWidth: float,
        rotateDegrees: float = 0,
        style: Optional[RenderStyle | str] = None,
    ) -> None:
        """
        Outputs a regular polygon with n sides
        It can be rotated
        Style can also be applied (fill, border...)

        Args:
            x (float): Abscissa of upper-left bounding box.
            y (float): Ordinate of upper-left bounding box.
            numSides (int): Number of sides for polygon.
            polyWidth (float): Width of the polygon.
            rotateDegrees (float): Optional degree amount to rotate polygon.
            style (fpdf.enums.RenderStyle, str): Optional style of rendering. Possible values are:

            * `D` or None: draw border. This is the default value.
            * `F`: fill
            * `DF` or `FD`: draw and fill
        """
        radius = polyWidth / 2
        centerX = x + radius
        centerY = y - radius
        # center point is (centerX, centerY)
        points: list[tuple[float, float]] = []
        for i in range(1, numSides + 1):
            point = centerX + radius * math.cos(
                math.radians((360 / numSides) * i) + math.radians(rotateDegrees)
            ), centerY + radius * math.sin(
                math.radians((360 / numSides) * i) + math.radians(rotateDegrees)
            )
            points.append(point)
        # creates list of tuples containing coordinate points of vertices

        self.polygon(points, style=style)
        # passes points through polygon function

    @check_page
    def star(
        self,
        x: float,
        y: float,
        r_in: float,
        r_out: float,
        corners: int,
        rotate_degrees: float = 0,
        style: Optional[RenderStyle | str] = None,
    ) -> None:
        """
        Outputs a regular star with n corners.
        It can be rotated.
        It can be drawn (border only), filled (with no border) or both.

        Args:
            x (float): Abscissa of star's centre.
            y (float): Ordinate of star's centre.
            r_in (float): radius of internal circle.
            r_out (float): radius of external circle.
            corners (int): number of star's corners.
            rotate_degrees (float): Optional degree amount to rotate star clockwise.

            style (fpdf.enums.RenderStyle, str): Optional style of rendering. Possible values are:
            * `D`: draw border. This is the default value.
            * `F`: fill.
            * `DF` or `FD`: draw and fill.
        """
        th = math.radians(rotate_degrees)
        point_list: list[tuple[float, float]] = []
        for i in range(0, (corners * 2) + 1):
            corner_x = x + (r_out if i % 2 == 0 else r_in) * math.sin(th)
            corner_y = y + (r_out if i % 2 == 0 else r_in) * math.cos(th)
            point_list.append((corner_x, corner_y))

            th += math.radians(180 / corners)

        self.polyline(point_list, polygon=True, style=style)

    @check_page
    def arc(
        self,
        x: float,
        y: float,
        a: float,
        start_angle: float,
        end_angle: float,
        b: Optional[float] = None,
        inclination: float = 0,
        clockwise: bool = False,
        start_from_center: bool = False,
        end_at_center: bool = False,
        style: Optional[RenderStyle | str] = None,
    ) -> None:
        """
        Outputs an arc.
        It can be drawn (border only), filled (with no border) or both.

        Args:
            x (float): Abscissa of upper-left corner of the bounding box of the full ellipse.
            y (float): Ordinate of upper-left corner of the bounding box of the full ellipse.
            a (float): Major axis diameter (width of bounding box).
            b (float): Minor axis diameter (height of bounding box), if None, equals to a (default: None).
            start_angle (float): Start angle of the arc (in degrees).
            end_angle (float): End angle of the arc (in degrees).
            inclination (float): Inclination of the arc in respect of the x-axis (default: 0).
            clockwise (bool): Way of drawing the arc (True: clockwise, False: counterclockwise) (default: False).
            start_from_center (bool): Start drawing from the center of the ellipse (default: False).
            end_at_center (bool): End drawing at the center of the ellipse (default: False).
            style (fpdf.enums.RenderStyle, str): Optional style of rendering. Allowed values are:

            * `D` or None: draw border. This is the default value.
            * `F`: fill
            * `DF` or `FD`: draw and fill
        """
        style = RenderStyle.coerce(style) if style is not None else RenderStyle.D

        if b is None:
            b = a

        a /= 2
        b /= 2

        cx = x + a
        cy = y + b

        # Functions used only to construct other points of the bezier curve
        def deg_to_rad(deg: float) -> float:
            return deg * math.pi / 180

        def angle_to_param(angle: float) -> float:
            angle = deg_to_rad(angle % 360)
            eta = math.atan2(math.sin(angle) / b, math.cos(angle) / a)

            if eta < 0:
                eta += 2 * math.pi
            return eta

        theta = deg_to_rad(inclination)
        cos_theta = math.cos(theta)
        sin_theta = math.sin(theta)

        def evaluate(eta: float) -> list[float]:
            a_cos_eta = a * math.cos(eta)
            b_sin_eta = b * math.sin(eta)

            return [
                cx + a_cos_eta * cos_theta - b_sin_eta * sin_theta,
                cy + a_cos_eta * sin_theta + b_sin_eta * cos_theta,
            ]

        def derivative_evaluate(eta: float) -> list[float]:
            a_sin_eta = a * math.sin(eta)
            b_cos_eta = b * math.cos(eta)

            return [
                -a_sin_eta * cos_theta - b_cos_eta * sin_theta,
                -a_sin_eta * sin_theta + b_cos_eta * cos_theta,
            ]

        # Calculating start_eta and end_eta so that
        #   start_eta < end_eta   <= start_eta + 2*PI if counterclockwise
        #   end_eta   < start_eta <= end_eta + 2*PI   if clockwise
        start_eta = angle_to_param(start_angle)
        end_eta = angle_to_param(end_angle)

        if not clockwise and end_eta <= start_eta:
            end_eta += 2 * math.pi
        elif clockwise and end_eta >= start_eta:
            start_eta += 2 * math.pi

        start_point = evaluate(start_eta)

        # Move to the start point
        if start_from_center:
            self._out(f"{cx * self.k:.2f} {(self.h - cy) * self.k:.2f} m")
            self._out(
                f"{start_point[0] * self.k:.2f} {(self.h - start_point[1]) * self.k:.2f} l"
            )
        else:
            self._out(
                f"{start_point[0] * self.k:.2f} {(self.h - start_point[1]) * self.k:.2f} m"
            )

        # Number of curves to use, maximal segment angle is 2*PI/max_curves
        max_curves = 4
        n = min(
            max_curves, math.ceil(abs(end_eta - start_eta) / (2 * math.pi / max_curves))
        )
        d_eta = (end_eta - start_eta) / n

        alpha = math.sin(d_eta) * (math.sqrt(4 + 3 * math.tan(d_eta / 2) ** 2) - 1) / 3

        eta2 = start_eta
        p2 = evaluate(eta2)
        p2_prime = derivative_evaluate(eta2)

        for i in range(n):
            p1 = p2
            p1_prime = p2_prime

            eta2 += d_eta
            p2 = evaluate(eta2)
            p2_prime = derivative_evaluate(eta2)

            control_point_1 = [p1[0] + alpha * p1_prime[0], p1[1] + alpha * p1_prime[1]]
            control_point_2 = [p2[0] - alpha * p2_prime[0], p2[1] - alpha * p2_prime[1]]

            end = ""
            if i == n - 1 and not end_at_center:
                end = f" {style.operator}"

            self._out(
                (
                    f"{control_point_1[0] * self.k:.2f} {(self.h - control_point_1[1]) * self.k:.2f} "
                    f"{control_point_2[0] * self.k:.2f} {(self.h - control_point_2[1]) * self.k:.2f} "
                    f"{p2[0] * self.k:.2f} {(self.h - p2[1]) * self.k:.2f} c" + end
                )
            )

        if end_at_center:
            if start_from_center:
                self._out(f"h {style.operator}")
            else:
                self._out(
                    f"{cx * self.k:.2f} {(self.h - cy) * self.k:.2f} l {style.operator}"
                )

    def solid_arc(
        self,
        x: float,
        y: float,
        a: float,
        start_angle: float,
        end_angle: float,
        b: Optional[float] = None,
        inclination: float = 0,
        clockwise: bool = False,
        style: Optional[RenderStyle | str] = None,
    ) -> None:
        """
        Outputs a solid arc. A solid arc combines an arc and a triangle to form a pie slice
        It can be drawn (border only), filled (with no border) or both.

        Args:
            x (float): Abscissa of upper-left bounding box.
            y (float): Ordinate of upper-left bounding box.
            a (float): Semi-major axis.
            b (float): Semi-minor axis, if None, equals to a (default: None).
            start_angle (float): Start angle of the arc (in degrees).
            end_angle (float): End angle of the arc (in degrees).
            inclination (float): Inclination of the arc in respect of the x-axis (default: 0).
            clockwise (bool): Way of drawing the arc (True: clockwise, False: counterclockwise) (default: False).
            style (str): Style of rendering. Possible values are:

            * `D` or None: draw border. This is the default value.
            * `F`: fill
            * `DF` or `FD`: draw and fill
        """
        self.arc(
            x,
            y,
            a,
            start_angle,
            end_angle,
            b,
            inclination,
            clockwise,
            True,
            True,
            style,
        )

    def bezier(
        self,
        point_list: Sequence[tuple[float, float]],
        closed: bool = False,
        style: Optional[RenderStyle | str] = None,
    ) -> None:
        """
        Outputs a quadratic or cubic Bézier curve, defined by three or four coordinates.

        Args:
            point_list (list of tuples): List of Abscissa and Ordinate of
                                        segments that should be drawn. Should be
                                        three or four tuples. The first and last
                                        points are the start and end point. The
                                        middle point(s) are the control point(s).
            closed (bool): True to draw the curve as a closed path, False (default)
                                        for it to be drawn as an open path.
            style (fpdf.enums.RenderStyle, str): Optional style of rendering. Allowed values are:
            * `D` or None: draw border. This is the default value.
            * `F`: fill
            * `DF` or `FD`: draw and fill
        """
        points = len(point_list)
        if points not in (3, 4):
            raise ValueError(
                "point_list should contain 3 tuples for a quadratic curve"
                " or 4 tuples for a cubic curve."
            )
        style = RenderStyle.coerce(style) if style is not None else RenderStyle.D

        # QuadraticBezierCurve and BezierCurve make use of `initial_point` when instantiated.
        # If we want to define all 3 (quad.) or 4 (cubic) points, we can set `initial_point`
        # to be the first point given in `point_list` by creating a separate dummy path at that pos.
        with self.drawing_context() as ctxt:
            p1 = point_list[0]
            x1, y1 = p1[0], p1[1]

            dummy_path = PaintedPath(x1, y1)
            ctxt.add_item(dummy_path)

            p2 = point_list[1]
            x2, y2 = p2[0], p2[1]

            p3 = point_list[2]
            x3, y3 = p3[0], p3[1]

            if points == 4:
                p4 = point_list[3]
                x4, y4 = p4[0], p4[1]

            path = PaintedPath(x1, y1)

            # Translate enum style (RenderStyle) into rule (PathPaintRule)
            rule = PathPaintRule.STROKE_FILL_NONZERO
            if style.is_draw and not style.is_fill:
                rule = PathPaintRule.STROKE
            elif style.is_fill and not style.is_draw:
                rule = PathPaintRule.FILL_NONZERO

            path.style.paint_rule = rule
            path.style.auto_close = closed

            if points == 4:
                path.curve_to(
                    x2,
                    y2,
                    x3,
                    y3,
                    x4,  # pyright: ignore[reportPossiblyUnboundVariable]
                    y4,  # pyright: ignore[reportPossiblyUnboundVariable]
                )
            elif points == 3:
                path.curve_to(x2, y2, x2, y2, x3, y3)

            ctxt.add_item(path)

    @deprecated_parameter([("uni", "2.5.1")])
    def add_font(
        self,
        family: Optional[str] = None,
        style: str = "",
        fname: Optional[str | PurePath] = None,
        *,
        unicode_range: Optional[str | Sequence[str | int | tuple[int, int]]] = None,
        variations: Optional[dict[str, dict[str, float]] | dict[str, float]] = None,
        palette: Optional[int] = None,
        collection_font_number: int = 0,
    ) -> None:
        """
        Imports a TrueType or OpenType font and makes it available
        for later calls to the `FPDF.set_font()` method.

        You will find more information on the "Unicode" documentation page.

        Args:
            family (str): optional name of the font family. Used as a reference for `FPDF.set_font()`.
                If not provided, use the base name of the `fname` font path, without extension.
            style (str): font style. "" for regular, include 'B' for bold, and/or 'I' for italic.
            fname (str): font file name. You can specify a relative or full path.
                If the file is not found, it will be searched in `FPDF_FONT_DIR`.
            unicode_range (Optional[Union[str, int, tuple, list]]): subset of Unicode codepoints to embed.
                Accepts CSS-style strings (e.g. "U+1F600-1F64F, U+2600"), integers, tuples, or lists.
                Defaults to None, which embeds the full cmap.
            variations (dict[style, dict]): maps style to limits of axes for the variable font.
            palette (int): optional palette index for color fonts (COLR/CPAL). Defaults to 0 (first palette).
                Only applicable to fonts with CPAL table (color fonts).
            collection_font_number (int): face index for TTC/OTC collections.
        """
        if not fname:
            raise ValueError('"fname" parameter is required')

        ext = splitext(str(fname))[1].lower()
        if ext not in (".otb", ".otf", ".otc", ".ttf", ".ttc", ".woff", ".woff2"):
            raise ValueError(
                f"Unsupported font file extension: {ext}."
                " add_font() used to accept .pkl file as input, but for security reasons"
                " this feature is deprecated since v2.5.1 and has been removed in v2.5.3."
            )

        for parent in (Path("."), FPDF_FONT_DIR):
            if (parent / fname).exists():
                font_file_path = parent / fname
                break
        else:
            raise FileNotFoundError(f"TTF Font file not found: {fname}")

        if family is None:
            family = font_file_path.stem

        parsed_unicode_range = None
        if unicode_range is not None:
            parsed_unicode_range = get_parsed_unicode_range(unicode_range)

        style = "".join(sorted(style.upper()))
        if any(letter not in "BI" for letter in style):
            raise ValueError(
                f"Unknown style provided (only B & I letters are allowed): {style}"
            )

        # Handle variable font.
        if variations is not None:
            if not isinstance(variations, dict):
                raise TypeError("Variations, if specified, must be a dictionary")

            # Check variations dictionary
            if all(
                key.upper() in ("", "B", "I", "BI") and isinstance(value, dict)
                for key, value in variations.items()
            ):
                for var_style, axes_dict in variations.items():
                    self.add_font(
                        family=family,
                        style=var_style,
                        fname=fname,
                        unicode_range=unicode_range,
                        variations=axes_dict,  # type: ignore[arg-type]
                        palette=palette,
                        collection_font_number=collection_font_number,
                    )
                return
        fontkey = f"{family.lower()}{style}"

        if fontkey in self.fonts or fontkey in CORE_FONTS:
            warnings.warn(
                f"Core font or font already added '{fontkey}': doing nothing",
                stacklevel=get_stack_level(),
            )
            return

        font_obj = TTFFont(
            self,
            font_file_path,
            fontkey,
            style,
            parsed_unicode_range,
            variations,  # type: ignore[arg-type]
            palette,
            collection_font_number,
        )
        self.fonts[fontkey] = font_obj
        if font_obj.is_cff and font_obj.is_cid_keyed:
            self._set_min_pdf_version("1.6")

    def set_font(
        self,
        family: Optional[str] = None,
        style: Union[str, TextEmphasis] = "",
        size: float = 0,
    ) -> None:
        """
        Sets the font used to print character strings.
        It is mandatory to call this method at least once before printing text.

        Default encoding is not specified, but all text writing methods accept only
        unicode for external fonts and one byte encoding for standard.

        Standard fonts use `Latin-1` encoding by default, but Windows
        encoding `cp1252` (Western Europe) can be used with
        `self.core_fonts_encoding = encoding`.

        The font specified is retained from page to page.
        The method can be called before the first page is created.

        Args:
            family (str): name of a font added with `FPDF.add_font`,
                or name of one of the 14 standard "PostScript" fonts:
                Courier (fixed-width), Helvetica (sans serif), Times (serif),
                Symbol (symbolic) or ZapfDingbats (symbolic)
                If an empty string is provided, the current family is retained.
            style (str, fpdf.enums.TextEmphasis): empty string (by default) or a combination
                of one or several letters among B (bold), I (italic), S (strikethrough) and U (underline).
                Bold and italic styles do not apply to Symbol and ZapfDingbats fonts.
            size (float): in points. The default value is the current size.
        """
        if not family:
            family = self.font_family

        family = family.lower()
        if isinstance(style, TextEmphasis):
            style = style.style
        style = "".join(sorted(style.upper()))
        if any(letter not in "BISU" for letter in style):
            raise ValueError(
                f"Unknown style provided (only B/I/S/U letters are allowed): {style}"
            )
        if "U" in style:
            self.underline = True
            style = style.replace("U", "")
        else:
            self.underline = False
        if "S" in style:
            self.strikethrough = True
            style = style.replace("S", "")
        else:
            self.strikethrough = False

        if family in self.font_aliases and family + style not in self.fonts:
            warnings.warn(
                f"Substituting font {family} by core font {self.font_aliases[family]}"
                " - This is deprecated since v2.7.8, and will soon be removed",
                DeprecationWarning,
                stacklevel=get_stack_level(),
            )
            family = self.font_aliases[family]
        elif family in ("symbol", "zapfdingbats") and style:
            warnings.warn(
                f"Built-in font {family} only has a single 'style' "
                "and can't be bold or italic",
                stacklevel=get_stack_level(),
            )
            style = ""

        if not size:
            size = self.font_size_pt

        # Test if font is already selected
        if (
            self.font_family == family
            and self.font_style == style
            and FloatTolerance.equal(self.font_size_pt, size)
        ):
            return

        # Test if used for the first time
        fontkey = family + style
        if fontkey not in self.fonts:
            if fontkey not in CORE_FONTS:
                raise FPDFException(
                    f"Undefined font: {fontkey} - "
                    f"Use built-in fonts or FPDF.add_font() beforehand"
                )
            # If it's one of the core fonts, add it to self.fonts
            if self._compliance and self._compliance.profile == "PDFA":
                raise PDFAComplianceError(
                    f"Usage of base fonts is now allowed for documents compliant with {self._compliance.label}. Use add_font() to embed a font file"
                )

            self.fonts[fontkey] = CoreFont(len(self.fonts) + 1, fontkey, style)

        # Select it
        self.font_family = family
        self.font_style = style
        self.font_size_pt = size
        self.current_font = self.fonts[fontkey]
        self.current_font_is_set_on_page = False

    def set_font_size(self, size: float) -> None:
        """
        Configure the font size in points

        Args:
            size (float): font size in points
        """
        if FloatTolerance.equal(self.font_size_pt, size):
            return
        self.font_size_pt = size
        self.current_font_is_set_on_page = False

    def _set_font_for_page(
        self,
        font: CoreFont | TTFFont,
        font_size_pt: float,
        wrap_in_text_object: bool = True,
    ) -> str:
        """
        Set font and size for current page.
        This step is needed before adding text into page and not needed in set_font and set_font_size.
        """
        sl = f"/F{font.i} {font_size_pt:.2f} Tf"
        if wrap_in_text_object:
            sl = f"BT {sl} ET"
        self._resource_catalog.add(PDFResourceType.FONT, font.i, self.page)
        self.current_font_is_set_on_page = True
        return sl

    def set_char_spacing(self, spacing: float) -> None:
        """
        Sets horizontal character spacing.
        A positive value increases the space between characters, a negative value
        reduces it (which may result in glyph overlap).
        By default, no spacing is set (which is equivalent to a value of 0).

        Args:
            spacing (float): horizontal spacing in document units
        """
        if self.char_spacing == spacing:
            return
        self.char_spacing = spacing
        if self.page > 0:
            self._out(f"BT {spacing:.2f} Tc ET")

    def set_stretching(self, stretching: float) -> None:
        """
        Sets horizontal font stretching.
        By default, no stretching is set (which is equivalent to a value of 100).

        Args:
            stretching (float): horizontal stretching (scaling) in percents.
        """
        if self.font_stretching == stretching:
            return
        self.font_stretching = stretching
        if self.page > 0:
            self._out(f"BT {stretching:.2f} Tz ET")

    def set_fallback_fonts(
        self, fallback_fonts: Sequence[str], exact_match: bool = True
    ) -> None:
        """
        Allows you to specify a list of fonts to be used if any character is not available on the font currently set.
        Detailed documentation: https://py-pdf.github.io/fpdf2/Unicode.html#fallback-fonts

        Args:
            fallback_fonts: sequence of fallback font IDs
            exact_match (bool): when a glyph cannot be rendered uing the current font,
                fpdf2 will look for a fallback font matching the current character emphasis (bold/italics).
                If it does not find such matching font, and `exact_match` is True, no fallback font will be used.
                If it does not find such matching font, and `exact_match` is False, a fallback font will still be used.
                To get even more control over this logic, you can also override `FPDF.get_fallback_font()`
        """
        fallback_font_ids: list[str] = []
        for fallback_font in fallback_fonts:
            found = False
            for fontkey in self.fonts:
                # will add all font styles on the same family
                if fontkey.replace("B", "").replace("I", "") == fallback_font.lower():
                    if fontkey not in fallback_font_ids:
                        fallback_font_ids.append(fontkey)
                    found = True
            if not found:
                raise FPDFException(
                    f"Undefined fallback font: {fallback_font} - Use FPDF.add_font() beforehand"
                )
        self._fallback_font_ids = fallback_font_ids
        self._fallback_font_exact_match = exact_match

    def add_link(
        self,
        y: float = 0,
        x: float = 0,
        page: int = -1,
        zoom: str | float = "null",
        name: Optional[str] = None,
    ) -> int:
        """
        Creates a new internal link and returns its identifier.
        An internal link is a clickable area which directs to another place within the document.

        The identifier can then be passed to the `FPDF.cell()`, `FPDF.write()`, `FPDF.image()`
        or `FPDF.link()` methods.

        If a name is provided, creates a named destination that can be referenced later.
        Named destinations are more stable than plain links when pages are added or removed.

        Args:
            y (float): optional ordinate of target position.
                The default value is 0 (top of page).
            x (float): optional abscissa of target position.
                The default value is 0 (top of page).
            page (int): optional number of target page.
                -1 indicates the current page, which is the default value.
            zoom (float): optional new zoom level after following the link.
                Currently ignored by Sumatra PDF Reader, but observed by Adobe Acrobat reader.
            name (str, optional): Name for the destination. If provided, creates a named
                destination in the PDF that can be referenced from other parts of the document
                or from external documents.
        """
        # Create destination
        link = DestinationXYZ(
            self.page if page == -1 else page,
            top=self.h_pt - y * self.k,
            left=x * self.k,
            zoom=zoom,
        )

        # Handle named destinations
        if name is not None:
            if not name or name.isspace():
                raise ValueError("Destination name cannot be empty or whitespace")
            self.named_destinations[name] = link

        # Store link and return index
        link_index = len(self.links) + 1
        self.links[link_index] = link
        return link_index

    def get_named_destination(self, name: str) -> str:
        """
        Retrieves a named destination by its name and creates a link to it.

        Args:
            name (str): The name of the destination to retrieve.

        Returns:
            str: A string with format "#name" that can be used with cell(), write(), image(), or link()

        Raises:
            KeyError: If no destination exists with the given name
        """
        if name not in self.named_destinations:
            # Create a placeholder named destination pointing to page 0
            # This will be caught during output if never set properly
            self.named_destinations[name] = DestinationXYZ(0, top=self.h_pt * self.k)

        # Return the name prefixed with # to indicate it's a named destination
        # This way, the link() method will use the named destination string
        return f"#{name}"

    def set_link(
        self,
        link: Optional[int] = None,
        y: float = 0,
        x: float = 0,
        page: int = -1,
        zoom: float | str = "null",
        name: Optional[str] = None,
    ) -> DestinationXYZ | str:
        """
        Defines the page and position a link points to.

        Args:
            link (int, optional): a link identifier returned by `FPDF.add_link()`.
                If None and name is provided, will create or update a named destination.
            y (float): optional ordinate of target position.
                The default value is 0 (top of page).
            x (float): optional abscissa of target position.
                The default value is 0 (top of page).
            page (int): optional number of target page.
                -1 indicates the current page, which is the default value.
            zoom (float): optional new zoom level after following the link.
                Currently ignored by Sumatra PDF Reader, but observed by Adobe Acrobat reader.
            name (str, optional): Name for the destination. If provided, creates or updates a named
                destination in the PDF that can be referenced from other parts of the document
                or from external documents.
        """
        # Handle named destination case
        if name and link is None:
            # Create the destination
            dest = DestinationXYZ(
                self.page if page == -1 else page,
                top=self.h_pt - y * self.k,
                left=x * self.k,
                zoom=zoom,
            )
            # Store it in the named destinations dictionary
            self.named_destinations[name] = dest
            # Return the name for reference
            return name

        # Regular link handling (backward compatibility)
        # We must take care to update the existing DestinationXYZ,
        # and NOT re-assign self.links[link] to a new instance,
        # as a reference to self.links[link] is kept in self.pages[].annots:
        assert link is not None
        destination = self.links[link]
        destination.page_number = self.page if page == -1 else page
        destination.top = self.h_pt - y * self.k
        destination.left = x * self.k
        destination.zoom = zoom

        # If a name is provided with an existing link, associate the name with this link
        if name:
            self.named_destinations[name] = destination
            return name

        # Return link index for backward compatibility
        return destination

    def link(
        self,
        x: float,
        y: float,
        w: float,
        h: float,
        link: str | int,
        alt_text: Optional[str] = None,
        **kwargs: Any,
    ) -> AnnotationDict:
        """
        Puts a link annotation on a rectangular area of the page.
        Text or image links are generally put via `FPDF.cell`,
        `FPDF.write` or `FPDF.image`,
        but this method can be useful for instance to define a clickable area inside an image.

        Args:
            x (float): horizontal position (from the left) to the left side of the link rectangle
            y (float): vertical position (from the top) to the bottom side of the link rectangle
            w (float): width of the link rectangle
            h (float): height of the link rectangle
            link: can be one of the following:
                - a URL string to create an external link
                - an integer returned by `FPDF.add_link`, defining an internal link to a page
                - a named destination string prefixed with '#' (e.g., '#chapter1')
            alt_text (str): optional textual description of the link, for accessibility purposes
            border_width (int): thickness of an optional black border surrounding the link.
                Not all PDF readers honor this: Acrobat renders it but not Sumatra.
        """
        action: Optional[URIAction] = None
        dest: Optional[PDFString | DestinationXYZ] = None
        if link:
            if isinstance(link, str):
                # Check if this is a named destination (prefixed with '#')
                if link.startswith("#"):
                    dest_name = link[1:]  # Remove the '#' prefix
                    # If the named destination doesn't exist yet, create a placeholder
                    # destination pointing to page 0 (which doesn't exist)
                    # This will be caught during output if never set properly
                    if dest_name not in self.named_destinations:
                        self.named_destinations[dest_name] = DestinationXYZ(
                            0, top=self.h_pt * self.k
                        )
                    # Use destination name instead of destination object for named destinations
                    dest = PDFString(dest_name, encrypt=True)
                else:
                    # Regular URL
                    action = URIAction(link)
            else:  # Dest type ending of annotation entry
                assert (
                    link in self.links
                ), f"Link with an invalid index: {link} (doc #links={len(self.links)})"
                dest = self.links[link]
                if not dest.page_number:
                    raise ValueError(
                        f"Cannot insert link {link} with no page number assigned"
                    )
        link_annot = AnnotationDict(
            "Link",
            x=x * self.k,
            y=self.h_pt - y * self.k,
            width=w * self.k,
            height=h * self.k,
            action=action,
            dest=dest,
            **kwargs,
        )
        self.pages[self.page].add_annotation(link_annot)
        if alt_text is not None:
            # Note: the spec indicates that a /StructParent could be added **inside* this /Annot,
            # but tests with Adobe Acrobat Reader reveal that the page /StructParents inserted below
            # is enough to link the marked content in the hierarchy tree with this annotation link.
            self._add_marked_content(struct_type="/Link", alt_text=alt_text)
        return link_annot

    def embed_file(
        self,
        file_path: Optional[Union[str, Path]] = None,
        bytes: Optional[bytes] = None,
        basename: Optional[str] = None,
        modification_date: Optional[datetime] = None,
        mime_type: Optional[str] = None,
        associated_file_relationship: Optional[str] = None,
        **kwargs: Any,
    ) -> PDFEmbeddedFile:
        """
        Embed a file into the PDF as an attachment (and, for PDF/A-3 or PDF/A-4f, as an
        Associated File).

        Args:
            file_path (str or Path): filesystem path to the existing file to embed
            bytes (bytes): optional, as an alternative to file_path, bytes content of the file to embed
            basename (str): optional, required if bytes is provided, file base name
            creation_date (datetime): date and time when the file was created
            modification_date (datetime): date and time when the file was last modified
            desc (str): optional description of the file
            mime_type: MIME type of the embedded content (e.g., "application/pdf", "text/csv", "image/png")
            associated_file_relationship: For PDF/A-3/A-4f, the AF relationship to declare in the FileSpec
                (e.g., "Data", "Source", "Alternative", "Supplement", or "Unspecified").

            **kwargs:
            desc (str): Optional human-readable description for the FileSpec.
            creation_date (datetime): Original creation time of the file.
            compress (bool): enabled zlib compression of the file - False by default
            checksum (bool): insert a MD5 checksum of the file content - False by default

        Returns: a PDFEmbeddedFile instance, with a .basename string attribute representing the internal file name
        """
        if file_path:
            if bytes:
                raise ValueError("'bytes' cannot be provided with 'file_path'")
            if basename:
                raise ValueError("'basename' cannot be provided with 'file_path'")
            file_path = Path(file_path)
            with file_path.open("rb") as input_file:
                bytes = input_file.read()
            basename = file_path.name
            stats = file_path.stat()
            if modification_date is None:
                modification_date = datetime.fromtimestamp(stats.st_mtime).astimezone()
        else:
            if not bytes:
                raise ValueError("'bytes' is required if 'file_path' is not provided")
            if not basename:
                raise ValueError(
                    "'basename' is required if 'file_path' is not provided"
                )
        if mime_type is None:
            mime_type = mimetypes.guess_type(basename)[0] or "application/octet-stream"
        mime_type = mime_type.lower()
        af_relationship = (
            AssociatedFileRelationship.coerce(associated_file_relationship)
            if associated_file_relationship is not None
            else None
        )
        already_embedded_basenames = set(
            file.basename() for file in self.embedded_files
        )
        if basename in already_embedded_basenames:
            raise ValueError(f"{basename} has already been embedded in this file")

        if self._compliance and self._compliance.profile == "PDFA":
            if self._compliance.part == 1:
                raise PDFAComplianceError(
                    f"Embedding files is not allowed for documents compliant with {self._compliance.label}"
                )
            if self._compliance.part == 2 or (
                self._compliance.part == 4 and self._compliance.conformance is None
            ):
                if (mime_type == "application/pdf") or basename.lower().endswith(
                    ".pdf"
                ):
                    LOGGER.warning(
                        "%s: ensure the embedded PDF '%s' is itself PDF/A to remain compliant.",
                        self._compliance.label,
                        basename,
                    )
                else:
                    raise PDFAComplianceError(
                        f"{self._compliance.label} permits embedding only PDF files, which must themselves be PDF/A."
                    )
            if self._compliance.part in (3, 4):
                if af_relationship is None:
                    af_relationship = AssociatedFileRelationship.UNSPECIFIED

        embedded_file = PDFEmbeddedFile(
            basename=basename,
            contents=bytes,
            modification_date=modification_date,
            mime_type=mime_type,
            af_relationship=af_relationship,
            **kwargs,
        )
        self.embedded_files.append(embedded_file)
        self._set_min_pdf_version("1.4")
        return embedded_file

    @check_page
    def file_attachment_annotation(
        self,
        file_path: str | Path,
        x: float,
        y: float,
        w: float = 1,
        h: float = 1,
        name: Optional[FileAttachmentAnnotationName | str] = None,
        flags: tuple[AnnotationFlag | str, ...] = DEFAULT_ANNOT_FLAGS,
        **kwargs: Any,
    ) -> AnnotationDict:
        """
        Puts a file attachment annotation on a rectangular area of the page.

        Args:
            file_path (str or Path): filesystem path to the existing file to embed
            x (float): horizontal position (from the left) to the left side of the link rectangle
            y (float): vertical position (from the top) to the bottom side of the link rectangle
            w (float): optional width of the link rectangle
            h (float): optional height of the link rectangle
            name (fpdf.enums.FileAttachmentAnnotationName, str): optional icon that shall be used in displaying the annotation
            flags (Tuple[fpdf.enums.AnnotationFlag], Tuple[str]): optional list of flags defining annotation properties
            bytes (bytes): optional, as an alternative to file_path, bytes content of the file to embed
            basename (str): optional, required if bytes is provided, file base name
            creation_date (datetime): date and time when the file was created
            modification_date (datetime): date and time when the file was last modified
            desc (str): optional description of the file
            compress (bool): enabled zlib compression of the file - False by default
            checksum (bool): insert a MD5 checksum of the file content - False by default
        """
        embedded_file = self.embed_file(file_path, **kwargs)
        # Attachment annotations should not be listed in the document-level AF entry
        # (they are reachable through the annotation itself), so keep them out of AF:
        embedded_file.set_globally_enclosed(False)
        annotation = AnnotationDict(
            "FileAttachment",
            x * self.k,
            self.h_pt - y * self.k,
            w * self.k,
            h * self.k,
            file_spec=embedded_file.file_spec(),
            name=FileAttachmentAnnotationName.coerce(name) if name else None,
            flags=flags,
        )
        self.pages[self.page].add_annotation(annotation)
        return annotation

    @check_page
    def text_annotation(
        self,
        x: float,
        y: float,
        text: str,
        w: float = 1,
        h: float = 1,
        name: Optional[AnnotationName | str] = None,
        **kwargs: Any,
    ) -> AnnotationDict:
        """
        Puts a text annotation on a rectangular area of the page.

        Args:
            x (float): horizontal position (from the left) to the left side of the link rectangle
            y (float): vertical position (from the top) to the bottom side of the link rectangle
            text (str): text to display
            w (float): optional width of the link rectangle
            h (float): optional height of the link rectangle
            name (fpdf.enums.AnnotationName, str): optional icon that shall be used in displaying the annotation
            flags (Tuple[fpdf.enums.AnnotationFlag], Tuple[str]): optional list of flags defining annotation properties
            title (str): the text label that shall be displayed in the title bar of the annotation’s
                pop-up window when open and active. This entry shall identify the user who added the annotation.
        """
        annotation = AnnotationDict(
            "Text",
            x * self.k,
            self.h_pt - y * self.k,
            w * self.k,
            h * self.k,
            contents=text,
            name=AnnotationName.coerce(name) if name else None,
            **kwargs,
        )
        self.pages[self.page].add_annotation(annotation)
        return annotation

    @check_page
    def free_text_annotation(
        self,
        text: str,
        x: Optional[float] = None,
        y: Optional[float] = None,
        w: Optional[float] = None,
        h: Optional[float] = None,
        **kwargs: Any,
    ) -> AnnotationDict:
        """
        Puts a free text annotation on a rectangular area of the page.

        Args:
            text (str): text to display
            x (float): optional horizontal position (from the left) to the left side of the link rectangle.
                Default value: None, meaning the current abscissa is used
            y (float): vertical position (from the top) to the bottom side of the link rectangle.
                Default value: None, meaning the current ordinate is used
            w (float): optional width of the link rectangle. Default value: None, meaning the length of text in user unit
            h (float): optional height of the link rectangle. Default value: None, meaning an height equal
                to the current font size
            flags (Tuple[fpdf.enums.AnnotationFlag], Tuple[str]): optional list of flags defining annotation properties
            color (tuple): a tuple of numbers in the range 0.0 to 1.0, representing a colour used for the annotation background
            border_width (float): width of the annotation border
        """
        if not self.font_family:
            raise FPDFException("No font set, you need to call set_font() beforehand")
        if not self.current_font_is_set_on_page:
            assert self.current_font is not None
            self._out(self._set_font_for_page(self.current_font, self.font_size_pt))
        if x is None:
            x = self.x
        if y is None:
            y = self.y
        if h is None:
            h = self.font_size
        if w is None:
            w = self.get_string_width(text, normalized=True, markdown=False)

        assert self.draw_color is not None and self.current_font is not None
        annotation = AnnotationDict(
            "FreeText",
            x * self.k,
            self.h_pt - y * self.k,
            w * self.k,
            h * self.k,
            contents=text,
            default_appearance=f"({self.draw_color.serialize()} /F{self.current_font.i} {self.font_size_pt:.2f} Tf)",
            **kwargs,
        )
        self.pages[self.page].add_annotation(annotation)
        return annotation

    @check_page
    def add_action(
        self, action: Action, x: float, y: float, w: float, h: float, **kwargs: Any
    ) -> AnnotationDict:
        """
        Puts an Action annotation on a rectangular area of the page.

        Args:
            action (fpdf.actions.Action): the action to add
            x (float): horizontal position (from the left) to the left side of the link rectangle
            y (float): vertical position (from the top) to the bottom side of the link rectangle
            w (float): width of the link rectangle
            h (float): height of the link rectangle
        """
        annotation_action_type = "Action"
        if isinstance(action, GoToAction):
            annotation_action_type = "Link"
        annotation = AnnotationDict(
            annotation_action_type,
            x * self.k,
            self.h_pt - y * self.k,
            w * self.k,
            h * self.k,
            action=action,
            **kwargs,
        )
        self.pages[self.page].add_annotation(annotation)
        return annotation

    @contextmanager
    def highlight(
        self,
        text: str,
        type: TextMarkupType | str = "Highlight",
        color: tuple[float, float, float] = (1, 1, 0),
        modification_time: Optional[datetime] = None,
        **kwargs: Any,
    ) -> Iterator[None]:
        """
        Context manager that adds a single highlight annotation based on the text lines inserted
        inside its indented block.

        Args:
            text (str): text of the annotation
            title (str): the text label that shall be displayed in the title bar of the annotation’s
                pop-up window when open and active. This entry shall identify the user who added the annotation.
            type (fpdf.enums.TextMarkupType, str): "Highlight", "Underline", "Squiggly" or "StrikeOut".
            color (tuple): a tuple of numbers in the range 0.0 to 1.0, representing a colour used for
                the title bar of the annotation’s pop-up window. Defaults to yellow.
            modification_time (datetime): date and time when the annotation was most recently modified
        """
        if self._record_text_quad_points:
            raise FPDFException("highlight() cannot be nested")
        self._record_text_quad_points = True
        yield
        for page, quad_points in self._text_quad_points.items():
            self.add_text_markup_annotation(
                type,
                text,
                quad_points=quad_points,
                modification_time=modification_time,
                page=page,
                color=color,
                **kwargs,
            )
        self._text_quad_points = defaultdict(list)
        self._record_text_quad_points = False

    @contextmanager
    def add_highlight(self, *args: Any, **kwargs: Any) -> Iterator[None]:
        warnings.warn(
            "add_highlight() has been renamed to highlight() in v2.5.5.",
            DeprecationWarning,
            stacklevel=get_stack_level(),
        )
        with self.highlight(*args, **kwargs):
            yield

    @check_page
    def add_text_markup_annotation(
        self,
        type: TextMarkupType | str,
        text: str,
        quad_points: Sequence[float],
        color: tuple[float, float, float] = (1, 1, 0),
        modification_time: Optional[datetime] = None,
        page: Optional[int] = None,
        **kwargs: Any,
    ) -> AnnotationDict:
        """
        Adds a text markup annotation on some quadrilateral areas of the page.

        Args:
            type (fpdf.enums.TextMarkupType, str): "Highlight", "Underline", "Squiggly" or "StrikeOut"
            text (str): text of the annotation
            quad_points (tuple): array of 8 × n numbers specifying the coordinates of n quadrilaterals
                in default user space that comprise the region in which the link should be activated.
                The coordinates for each quadrilateral are given in the order: x1 y1 x2 y2 x3 y3 x4 y4
                specifying the four vertices of the quadrilateral in counterclockwise order
            title (str): the text label that shall be displayed in the title bar of the annotation’s
                pop-up window when open and active. This entry shall identify the user who added the annotation.
            color (tuple): a tuple of numbers in the range 0.0 to 1.0, representing a colour used for
                the title bar of the annotation’s pop-up window. Defaults to yellow.
            modification_time (datetime): date and time when the annotation was most recently modified
            page (int): index of the page where this annotation is added
        """
        self._set_min_pdf_version("1.6")
        type = TextMarkupType.coerce(type).value
        if modification_time is None:
            modification_time = self.creation_date
        if page is None:
            page = self.page
        x_min = min(quad_points[0::2])
        y_min = min(quad_points[1::2])
        x_max = max(quad_points[0::2])
        y_max = max(quad_points[1::2])
        annotation = AnnotationDict(
            type,
            contents=text,
            x=y_min,
            y=y_max,
            width=x_max - x_min,
            height=y_max - y_min,
            modification_time=modification_time,
            quad_points=quad_points,
            color=color,
            **kwargs,
        )
        self.pages[page].add_annotation(annotation)
        return annotation

    @check_page
    def ink_annotation(
        self,
        coords: Sequence[tuple[float, float]],
        text: str = "",
        color: tuple[float, float, float] = (1, 1, 0),
        border_width: float = 1,
        **kwargs: Any,
    ) -> AnnotationDict:
        """
        Adds add an ink annotation on the page.

        Args:
            coords (tuple): an iterable of coordinates (pairs of numbers) defining a path
            text (str): textual description
            title (str): the text label that shall be displayed in the title bar of the annotation’s
                pop-up window when open and active. This entry shall identify the user who added the annotation.
            color (tuple): a tuple of numbers in the range 0.0 to 1.0, representing a colour used for
                the title bar of the annotation’s pop-up window. Defaults to yellow.
            border_width (float): thickness of the path stroke.
        """
        ink_list = sum(((x * self.k, (self.h - y) * self.k) for (x, y) in coords), ())
        x_min = min(ink_list[0::2])
        y_min = min(ink_list[1::2])
        x_max = max(ink_list[0::2])
        y_max = max(ink_list[1::2])
        annotation = AnnotationDict(
            "Ink",
            x=y_min,
            y=y_max,
            width=x_max - x_min,
            height=y_max - y_min,
            ink_list=ink_list,
            contents=text,
            border_width=border_width,
            color=color,
            **kwargs,
        )
        self.pages[self.page].add_annotation(annotation)
        return annotation

    @check_page
    @support_deprecated_txt_arg
    def text(self, x: float, y: float, text: str = "") -> None:
        """
        Prints a character string. The origin is on the left of the first character,
        on the baseline. This method allows placing a string precisely on the page,
        but it is usually easier to use the `FPDF.cell()`, `FPDF.multi_cell() or `FPDF.write()` methods.

        Args:
            x (float): abscissa of the origin
            y (float): ordinate of the origin
            text (str): string to print
            txt (str): [**DEPRECATED since v2.7.6**] string to print

        Notes
        -----

        `text()` lacks many of the features available in `FPDF.write()`,
        `FPDF.cell()` and `FPDF.multi_cell()` like markdown and text shaping.
        """
        if not self.font_family:
            raise FPDFException("No font set, you need to call set_font() beforehand")
        text = self.normalize_text(text)
        assert self.current_font is not None
        if not self.current_font_is_set_on_page:
            self._out(self._set_font_for_page(self.current_font, self.font_size_pt))
        sl = [f"BT {x * self.k:.2f} {(self.h - y) * self.k:.2f} Td"]
        if self.text_mode != TextMode.FILL:
            sl.append(f" {self.text_mode} Tr {self.line_width:.2f} w")
        sl.append(f"{self.current_font.encode_text(text)} ET")
        if (
            text != "" and (self.underline or self.strikethrough)
        ) or self._record_text_quad_points:
            w = self.get_string_width(text, normalized=True, markdown=False)
            if text != "":
                if self.underline:
                    sl.append(self._do_underline(x, y, w))
                if self.strikethrough:
                    sl.append(self._do_strikethrough(x, y, w))
            if self._record_text_quad_points:
                h = self.font_size
                y -= 0.8 * h  # same coefficient as in _render_styled_text_line()
                self._add_quad_points(x, y, w, h)
        attr_l: list[str] = []
        if self.fill_color != self.text_color:
            assert self.text_color is not None
            attr_l.append(f"{self.text_color.serialize().lower()}")
        if attr_l:
            sl = ["q"] + attr_l + sl + ["Q"]
        self._out(" ".join(sl))

    @check_page
    def rotate(
        self, angle: float, x: Optional[float] = None, y: Optional[float] = None
    ) -> None:
        """
        .. deprecated:: 2.1.0
            Use `FPDF.rotation()` instead.
        """
        warnings.warn(
            (
                "rotate() can produces malformed PDFs and is deprecated since v2.1.0. "
                "It will be removed in a future release. "
                "Use the rotation() context manager instead."
            ),
            DeprecationWarning,
            stacklevel=get_stack_level(),
        )
        if x is None:
            x = self.x
        if y is None:
            y = self.y

        if self._angle != 0:
            self._out("Q")
        self._angle = angle
        if angle != 0:
            angle *= math.pi / 180
            c = math.cos(angle)
            s = math.sin(angle)
            cx = x * self.k
            cy = (self.h - y) * self.k
            output = (
                f"q {c:.5F} {s:.5F} {-s:.5F} {c:.5F} {cx:.2F} {cy:.2F} cm "
                f"1 0 0 1 {-cx:.2F} {-cy:.2F} cm"
            )
            self._out(output)

    @check_page
    @contextmanager
    def rotation(
        self, angle: float, x: Optional[float] = None, y: Optional[float] = None
    ) -> Iterator[None]:
        """
        Method to perform a rotation around a given center.
        It must be used as a context-manager using `with`:

            with rotation(angle=90, x=x, y=y):
                pdf.something()

        The rotation affects all elements which are printed inside the indented
        context (with the exception of clickable areas).

        Args:
            angle (float): angle in degrees
            x (float): abscissa of the center of the rotation
            y (float): ordinate of the center of the rotation

        Notes
        -----

        Only the rendering is altered. The `FPDF.get_x()` and `FPDF.get_y()` methods are
        not affected, nor the automatic page break mechanism.
        The rotation also establishes a local graphics state, so that any
        graphics state settings changed within will not affect the operations
        invoked after it has finished.
        """
        if x is None:
            x = self.x
        if y is None:
            y = self.y
        with self.transform(Transform.rotation_d(-angle).about(x, y)):
            yield

    @check_page
    @contextmanager
    def skew(
        self,
        ax: float = 0,
        ay: float = 0,
        x: Optional[float] = None,
        y: Optional[float] = None,
    ) -> Iterator[None]:
        """
        Method to perform a skew transformation originating from a given center.
        It must be used as a context-manager using `with`:

            with skew(ax=15, ay=15, x=x, y=y):
                pdf.something()

        The skew transformation affects all elements which are printed inside the indented
        context (with the exception of clickable areas).

        Args:
            ax (float): angle of skew in the horizontal direction in degrees
            ay (float): angle of skew in the vertical direction in degrees
            x (float): abscissa of the center of the skew transformation
            y (float): ordinate of the center of the skew transformation
        """
        lim_val = 2**32
        if x is None:
            x = self.x
        if y is None:
            y = self.y
        ax = max(min(math.tan(ax * (math.pi / 180)), lim_val), -lim_val)
        ay = max(min(math.tan(ay * (math.pi / 180)), lim_val), -lim_val)
        with self.transform(Transform.shearing(-ax, -ay).about(x, y)):
            yield

    @check_page
    @contextmanager
    def mirror(
        self, origin: tuple[float, float], angle: Angle | str | float
    ) -> Iterator[None]:
        """
        Method to perform a reflection transformation over a given mirror line.
        It must be used as a context-manager using `with`:

            with mirror(origin=(15,15), angle="SOUTH"):
                pdf.something()

        The mirror transformation affects all elements which are rendered inside the indented
        context (with the exception of clickable areas).

        Args:
            origin (float, Sequence(float, float)): a point on the mirror line
            angle: (fpdf.enums.Angle): the direction of the mirror line
        """
        x, y = origin

        try:
            if isinstance(angle, (str, Angle)):
                theta = float(Angle.coerce(angle).value)
            else:
                theta = float(angle)
        except ValueError:
            theta = float(angle)

        a = math.cos(math.radians(theta * 2))
        b = -math.sin(math.radians(theta * 2))

        with self.transform(Transform(a, b, b, -a, 0, 0).about(x, y)):
            yield

    @check_page
    @contextmanager
    def transform(self, transform: Transform) -> Iterator[None]:
        """
        Apply a transformation matrix to the current graphics state.
        This context manager isolates the transformation so it doesn't affect
        rendering outside the 'with' block.

        It automatically handles the conversion from FPDF's User Units (usually mm, top-left origin)
        to PDF Device Units (points, bottom-left origin).

        Args:
            transform (fpdf.drawing_primitives.Transform): The transformation matrix to apply.
        """
        with self.local_context():
            user_to_pdf = Transform.scaling(self.k, -self.k).translate(0, self.h_pt)
            adjusted_transform = user_to_pdf.inverse() @ transform @ user_to_pdf

            command, _ = adjusted_transform.render(None)  # type: ignore
            self._out(command)
            yield

    @check_page
    @contextmanager
    def local_context(self, **kwargs: Any) -> Iterator[None]:
        """
        Creates a local graphics state, which won't affect the surrounding code.
        This method must be used as a context manager using `with`:

            with pdf.local_context():
                set_some_state()
                draw_some_stuff()

        The affected settings are those controlled by GraphicsStateMixin and drawing.GraphicsStyle:

        * allow_transparency
        * auto_close
        * blend_mode
        * char_vpos
        * char_spacing
        * dash_pattern
        * denom_lift
        * denom_scale
        * draw_color
        * fill_color
        * fill_opacity
        * font_family
        * font_size
        * font_size_pt
        * font_style
        * font_stretching
        * intersection_rule
        * line_width
        * nom_lift
        * nom_scale
        * paint_rule
        * strikethrough
        * stroke_cap_style
        * stroke_join_style
        * stroke_miter_limit
        * stroke_opacity
        * sub_lift
        * sub_scale
        * sup_lift
        * sup_scale
        * text_color
        * text_mode
        * text_shaping
        * underline

        Font size can be specified in document units with `font_size` or in points with `font_size_pt`.

        Args:
            **kwargs: key-values settings to set at the beginning of this context.
        """
        if self._in_unbreakable:
            raise FPDFException(
                "cannot create a local context inside an unbreakable() code block"
            )
        self._push_local_stack()
        self._start_local_context(**kwargs)
        yield
        self._end_local_context()
        self._pop_local_stack()

    def _start_local_context(
        self,
        font_family: Optional[str] = None,
        font_style: Optional[str] = None,
        font_size_pt: Optional[float] = None,
        line_width: Optional[float] = None,
        draw_color: Optional[ColorInput] = None,
        fill_color: Optional[ColorInput] = None,
        text_color: Optional[ColorInput] = None,
        dash_pattern: Optional[
            Union[tuple[float, float, float], dict[str, float]]
        ] = None,
        **kwargs: Any,
    ) -> None:
        """
        This method starts a "q/Q" context in the page content stream,
        and inserts operators in it to initialize all the PDF settings specified.
        """
        if "font_size" in kwargs:
            # At some point we may want to deprecate font_size here in favour of font_size_pt,
            # and raise a warning if font_size is provided:
            # * font_size_pt is more consistent with the size parameter of .set_font(), provided in points.
            # * font_size can be misused, as users may not be aware of the difference between the 2 properties,
            #   and may erroneously provide a value in points as font_size.
            if font_size_pt is not None:
                raise ValueError("font_size & font_size_pt cannot be both provided")
            font_size_pt = kwargs["font_size"] * self.k
            del kwargs["font_size"]
        gs = None
        for key, value in kwargs.items():
            if key in (
                "stroke_color",
                "stroke_dash_phase",
                "stroke_dash_pattern",
                "stroke_width",
            ):
                raise ValueError(
                    f"Unsupported setting: {key} - This can be controlled through dash_pattern / draw_color / line_width"
                )
            if key in GraphicsStyle.MERGE_PROPERTIES:
                if gs is None:
                    gs = GraphicsStyle()
                setattr(gs, key, value)
                if key == "blend_mode":
                    self._set_min_pdf_version("1.4")
            elif key in (
                "char_vpos",
                "char_spacing",
                "current_font",
                "denom_lift",
                "denom_scale",
                "font_stretching",
                "nom_lift",
                "nom_scale",
                "strikethrough",
                "sub_lift",
                "sub_scale",
                "sup_lift",
                "sup_scale",
                "text_mode",
                "text_shaping",
                "underline",
                "current_font_is_set_on_page",
            ):
                setattr(self, key, value)
            else:
                raise ValueError(f"Unsupported setting: {key}")
        if gs:
            gs_name = self._resource_catalog.register_graphics_style(gs)
            assert gs_name is not None
            self._resource_catalog.add(PDFResourceType.EXT_G_STATE, gs_name, self.page)
            self._out(f"q /{gs_name} gs")
        else:
            self._out("q")
        # All the following calls to .set*() methods invoke .out() and write to the stream buffer:
        if (
            font_family is not None
            or font_style is not None
            or font_size_pt is not None
        ):
            self.set_font(
                font_family or self.font_family,
                # Beware: font_style='' must be handled distinctly from font_style=None
                self.font_style if font_style is None else font_style,
                font_size_pt or self.font_size_pt,
            )
        if line_width is not None:
            self.set_line_width(line_width)
        if draw_color is not None:
            self.set_draw_color(draw_color)
        if fill_color is not None:
            self.set_fill_color(fill_color)
        if text_color is not None:
            self.set_text_color(text_color)
        if dash_pattern is not None:
            if isinstance(dash_pattern, dict):
                self.set_dash_pattern(
                    dash_pattern.get("dash", 0),
                    dash_pattern.get("gap", 0),
                    dash_pattern.get("phase", 0),
                )
            else:
                self.set_dash_pattern(dash_pattern[0], dash_pattern[1], dash_pattern[2])

    def _end_local_context(self) -> None:
        """
        This method ends a "q/Q" context in the page content stream.
        """
        self._out("Q")

    @property
    def accept_page_break(self) -> bool:
        """
        Whenever a page break condition is met, this `@property` method is called,
        and the break is issued or not depending on the returned value.

        The default implementation returns `self.auto_page_break`,
        a value according to the mode selected by `FPDF.set_auto_page_break()`.

        This method is called automatically and should not be called directly by the application.

        Detailed documentation on page breaks: https://py-pdf.github.io/fpdf2/PageBreaks.html
        """
        return self.auto_page_break

    @check_page
    @support_deprecated_txt_arg
    def cell(
        self,
        w: Optional[float] = None,
        h: Optional[float] = None,
        text: str = "",
        border: Literal[0, 1] | str = 0,
        ln: Literal["DEPRECATED"] = "DEPRECATED",
        align: str | Align = Align.L,
        fill: bool = False,
        link: Optional[str | int] = "",
        center: bool = False,
        markdown: bool = False,
        new_x: str | XPos = XPos.RIGHT,
        new_y: str | YPos = YPos.TOP,
    ) -> bool:
        """
        Prints a cell (rectangular area) with optional borders, background color and
        character string. The upper-left corner of the cell corresponds to the current
        position. The text can be aligned or centered. After the call, the current
        position moves to the selected `new_x`/`new_y` position. It is possible to put a link
        on the text. A cell has an horizontal padding, on the left & right sides, defined by
        the.c_margin property.

        If automatic page breaking is enabled and the cell goes beyond the limit, a
        page break is performed before outputting.

        Args:
            w (float): Cell width. Default value: None, meaning to fit text width.
                If 0, the cell extends up to the right margin.
            h (float): Cell height. Default value: None, meaning an height equal
                to the current font size.
            text (str): String to print. Default value: empty string.
            border: Indicates if borders must be drawn around the cell.
                The value can be either a number (`0`: no border ; `1`: frame)
                or a string containing some or all of the following characters
                (in any order):
                `L`: left ; `T`: top ; `R`: right ; `B`: bottom. Default value: 0.
            new_x (fpdf.enums.XPos, str): New current position in x after the call. Default: RIGHT
            new_y (fpdf.enums.YPos, str): New current position in y after the call. Default: TOP
            ln (int): **DEPRECATED since 2.5.1**: Use `new_x` and `new_y` instead.
            align (fpdf.enums.Align, str): Set text alignment inside the cell.
                Possible values are: `L` or empty string: left align (default value) ;
                `C`: center; `X`: center around current x position; `R`: right align
            fill (bool): Indicates if the cell background must be painted (`True`)
                or transparent (`False`). Default value: False.
            link (str): optional link to add on the cell, internal
                (identifier returned by `FPDF.add_link`) or external URL.
            center (bool): center the cell horizontally on the page.
            markdown (bool): enable minimal markdown-like markup to render part
                of text as bold / italics / strikethrough / underlined.
                Supports `\\` as escape character. Default to False.
            txt (str): [**DEPRECATED since v2.7.6**] String to print. Default value: empty string.

        Returns: a boolean indicating if page break was triggered
        """
        if not self.font_family:
            raise FPDFException("No font set, you need to call set_font() beforehand")
        if isinstance(w, str) or isinstance(h, str):
            raise ValueError(
                "Parameter 'w' and 'h' must be numbers, not strings."
                " You can omit them by passing string content with text="
            )
        if isinstance(border, int) and border not in (0, 1):
            warnings.warn(
                'Integer values for "border" parameter other than 1 are currently ignored',
                stacklevel=get_stack_level(),
            )
            border = 1
        new_x = XPos.coerce(new_x)
        new_y = YPos.coerce(new_y)
        align = Align.coerce(align)
        if align == Align.J:
            raise ValueError(
                "cell() only produces one text line, justified alignment is not possible"
            )
        if ln != "DEPRECATED":
            # For backwards compatibility, if "ln" is used we overwrite "new_[xy]".
            if ln == 0:
                new_x = XPos.RIGHT
                new_y = YPos.TOP
            elif ln == 1:
                new_x = XPos.LMARGIN
                new_y = YPos.NEXT
            elif ln == 2:
                new_x = XPos.LEFT
                new_y = YPos.NEXT
            else:
                raise ValueError(
                    f'Invalid value for parameter "ln" ({ln}),'
                    " must be an int between 0 and 2."
                )
            warnings.warn(
                (
                    'The parameter "ln" is deprecated since v2.5.2.'
                    f" Instead of ln={ln} use new_x=XPos.{new_x.name}, new_y=YPos.{new_y.name}."
                ),
                DeprecationWarning,
                stacklevel=get_stack_level(),
            )
        # Font styles preloading must be performed before any call to FPDF.get_string_width:
        text = self.normalize_text(text)
        styled_txt_frags = (
            self._preload_bidirectional_text(text, markdown)
            if self.text_shaping
            else self._preload_font_styles(text, markdown)
        )
        line_height = self.font_size if h is None else h
        return self._render_styled_text_line(
            TextLine(
                styled_txt_frags,
                text_width=0,
                number_of_spaces=0,
                align=align,
                height=line_height,
                max_width=w,
                trailing_nl=False,
            ),
            line_height,
            border,
            new_x=new_x,
            new_y=new_y,
            fill=fill,
            link=link,
            center=center,
            prevent_font_change=markdown,
        )

    def _render_styled_text_line(
        self,
        text_line: TextLine,
        h: Optional[float] = None,
        border: Union[str, int] = 0,
        new_x: XPos = XPos.RIGHT,
        new_y: YPos = YPos.TOP,
        fill: bool = False,
        link: Optional[str | int] = "",
        center: bool = False,
        padding: Optional[Padding] = None,
        prevent_font_change: bool = False,
    ) -> bool:
        """
        Prints a cell (rectangular area) with optional borders, background color and
        character string. The upper-left corner of the cell corresponds to the current
        position. The text can be aligned, centered or justified. After the call, the
        current position moves to the requested new position. It is possible to put a
        link on the text.

        If automatic page breaking is enabled and the cell goes beyond the limit, a
        page break is performed before outputting.

        Args:
            text_line (TextLine instance): Contains the (possibly empty) tuple of
                fragments to render.
            h (float): Cell height. Default value: None, meaning an height equal
                to the current font size.
            border: Indicates if borders must be drawn around the cell.
                The value can be either a number (`0`: no border ; `1`: frame)
                or a string containing some or all of the following characters
                (in any order):
                `L`: left ; `T`: top ; `R`: right ; `B`: bottom. Default value: 0.
            new_x (fpdf.enums.XPos): New current position in x after the call.
            new_y (fpdf.enums.YPos): New current position in y after the call.
            fill (bool): Indicates if the cell background must be painted (`True`)
                or transparent (`False`). Default value: False.
            link (str): optional link to add on the cell, internal
                (identifier returned by `FPDF.add_link`) or external URL.
            center (bool): center the cell horizontally on the page.
            padding (Padding or None): optional padding to apply to the cell content.
                If padding for left and right is non-zero then c_margin is ignored.
            prevent_font_change (bool): ensure no font settings (family / size / style)
                change during this call.

        Returns: a boolean indicating if page break was triggered
        """
        if isinstance(border, int) and border not in (0, 1):
            warnings.warn(
                'Integer values for "border" parameter other than 1 are currently ignored',
                stacklevel=get_stack_level(),
            )
            border = 1
        elif isinstance(border, str) and set(border).issuperset("LTRB"):
            border = 1

        if padding is None:
            padding = Padding(0, 0, 0, 0)
        l_c_margin = r_c_margin = float(0)
        if padding.left == 0:
            l_c_margin = self.c_margin
        if padding.right == 0:
            r_c_margin = self.c_margin

        styled_txt_width = text_line.text_width
        if not styled_txt_width:
            for i, frag in enumerate(text_line.fragments):
                unscaled_width = frag.get_width(initial_cs=i != 0)
                styled_txt_width += unscaled_width

        w = text_line.max_width
        if w is None:
            if not text_line.fragments:
                raise ValueError(
                    "'text_line' must have fragments if 'text_line.text_width' is None"
                )
            w = styled_txt_width + l_c_margin + r_c_margin
        elif w == 0:
            w = self.w - self.r_margin - self.x
        if center:
            self.x = self.l_margin + (self.epw - w) / 2
        elif text_line.align == Align.X:
            self.x -= w / 2

        max_font_size: float = 0  # how much height we need to accommodate.
        # currently all font sizes within a line are vertically aligned on the baseline.
        fragments = text_line.get_ordered_fragments()
        for frag in fragments:
            if FloatTolerance.greater_than(frag.font_size, max_font_size):
                max_font_size = frag.font_size
        if h is None:
            h = max_font_size
        page_break_triggered = self._perform_page_break_if_need_be(h)
        sl: list[str] = []

        k = self.k

        # pre-calc border edges with padding

        left = (self.x - padding.left) * k
        right = (self.x + w + padding.right) * k
        top = (self.h - self.y + padding.top) * k
        bottom = (self.h - (self.y + h) - padding.bottom) * k

        if fill:
            op = "B" if border == 1 else "f"
            sl.append(f"{left:.2f} {top:.2f} {right-left:.2f} {bottom-top:.2f} re {op}")
        elif border == 1:
            sl.append(f"{left:.2f} {top:.2f} {right-left:.2f} {bottom-top:.2f} re S")
        # pylint: enable=invalid-unary-operand-type

        if isinstance(border, str):
            if "L" in border:
                sl.append(f"{left:.2f} {top:.2f} m {left:.2f} {bottom:.2f} l S")
            if "T" in border:
                sl.append(f"{left:.2f} {top:.2f} m {right:.2f} {top:.2f} l S")
            if "R" in border:
                sl.append(f"{right:.2f} {top:.2f} m {right:.2f} {bottom:.2f} l S")
            if "B" in border:
                sl.append(f"{left:.2f} {bottom:.2f} m {right:.2f} {bottom:.2f} l S")

        if self._record_text_quad_points:
            self._add_quad_points(self.x, self.y, w, h)

        s_start = self.x
        s_width: float = 0
        # We try to avoid modifying global settings for temporary changes.
        current_ws = frag_ws = 0.0
        current_lift = 0.0
        current_char_vpos = CharVPos.LINE
        current_font = self.current_font
        current_font_size_pt = self.font_size_pt
        current_font_style = self.font_style
        current_text_mode = self.text_mode
        current_font_stretching = self.font_stretching
        current_char_spacing = self.char_spacing
        fill_color_changed = False
        last_used_color = self.fill_color
        if fragments:
            if text_line.align == Align.R:
                dx = w - l_c_margin - styled_txt_width
            elif text_line.align in [Align.C, Align.X]:
                dx = (w - styled_txt_width) / 2
            else:
                dx = l_c_margin
            s_start += dx
            word_spacing: float = 0
            if text_line.align == Align.J and text_line.number_of_spaces:
                word_spacing = (
                    w - l_c_margin - r_c_margin - styled_txt_width
                ) / text_line.number_of_spaces
            sl.append(
                f"BT {(self.x + dx) * k:.2f} "
                f"{(self.h - self.y - 0.5 * h - 0.3 * max_font_size) * k:.2f} Td"
            )
            underlines: list[tuple[float, float, CoreFont | TTFFont, float]] = []
            strikethroughs: list[tuple[float, float, CoreFont | TTFFont, float]] = []
            for i, frag in enumerate(fragments):
                if isinstance(frag, TotalPagesSubstitutionFragment):
                    self.pages[self.page].add_text_substitution(frag)
                if frag.text_color != last_used_color:
                    # allow to change color within the line of text.
                    last_used_color = frag.text_color
                    assert last_used_color is not None
                    sl.append(last_used_color.serialize().lower())
                    fill_color_changed = True
                if word_spacing and frag.font_stretching != 100:
                    # Space character is already stretched, extra spacing is absolute.
                    frag_ws = word_spacing * 100 / frag.font_stretching
                else:
                    frag_ws = word_spacing
                if current_font_stretching != frag.font_stretching:
                    current_font_stretching = frag.font_stretching
                    sl.append(f"{frag.font_stretching:.2f} Tz")
                if current_char_spacing != frag.char_spacing:
                    current_char_spacing = frag.char_spacing
                    sl.append(f"{frag.char_spacing:.2f} Tc")
                if not self.current_font_is_set_on_page:
                    if prevent_font_change:
                        # This is "local" to the current BT / ET context:
                        current_font = frag.font
                        current_font_size_pt = frag.font_size_pt
                        current_font_style = frag.font_style
                        sl.append(f"/F{current_font.i} {current_font_size_pt:.2f} Tf")
                        self._resource_catalog.add(
                            PDFResourceType.FONT, current_font.i, self.page
                        )
                        current_char_vpos = frag.char_vpos
                    else:
                        # This is "global" to the page,
                        # as it is rendered in the content stream
                        # BEFORE the text_lines /fragments,
                        # wrapped into BT / ET operators:
                        current_font = self.current_font = frag.font
                        current_font_size_pt = self.font_size_pt = frag.font_size_pt
                        current_font_style = self.font_style = frag.font_style
                        self._out(
                            self._set_font_for_page(
                                current_font,
                                current_font_size_pt,
                            )
                        )
                        current_char_vpos = frag.char_vpos
                elif (
                    current_font != frag.font
                    or current_font_size_pt != frag.font_size_pt
                    or current_font_style != frag.font_style
                    or current_char_vpos != frag.char_vpos
                ):
                    # This is "local" to the current BT / ET context:
                    current_font = frag.font
                    current_font_size_pt = frag.font_size_pt
                    current_font_style = frag.font_style
                    sl.append(
                        self._set_font_for_page(
                            current_font,
                            current_font_size_pt,
                            wrap_in_text_object=False,
                        )
                    )
                    current_char_vpos = frag.char_vpos
                lift = frag.lift
                if lift != current_lift:
                    # Use text rise operator:
                    sl.append(f"{lift:.2f} Ts")
                    current_lift = lift
                if (
                    frag.text_mode != TextMode.FILL
                    or frag.text_mode != current_text_mode
                ):
                    current_text_mode = frag.text_mode
                    sl.append(f"{frag.text_mode} Tr {frag.line_width:.2f} w")

                r_text = frag.render_pdf_text(
                    frag_ws,
                    current_ws,
                    word_spacing,
                    self.x + dx + s_width,
                    self.y + (0.5 * h + 0.3 * max_font_size),
                    self.h,
                )
                if r_text:
                    sl.append(r_text)

                frag_width = frag.get_width(
                    initial_cs=i != 0
                ) + word_spacing * frag.characters.count(" ")
                if frag.underline:
                    underlines.append(
                        (self.x + dx + s_width, frag_width, frag.font, frag.font_size)
                    )
                if frag.strikethrough:
                    strikethroughs.append(
                        (self.x + dx + s_width, frag_width, frag.font, frag.font_size)
                    )
                if frag.link:
                    self.link(
                        x=self.x + dx + s_width,
                        y=self.y + (0.5 * h) - (0.5 * frag.font_size),
                        w=frag_width,
                        h=frag.font_size,
                        link=frag.link,
                    )
                if not frag.is_ttf_font:
                    current_ws = frag_ws
                s_width += frag_width

            sl.append("ET")

            # Underlines & strikethrough must be rendred OUTSIDE BT/ET contexts,
            # cf. https://github.com/py-pdf/fpdf2/issues/1456
            if underlines:
                for start_x, width, font, font_size in underlines:
                    sl.append(
                        self._do_underline(
                            start_x, self.y + (0.5 * h) + (0.3 * font_size), width, font
                        )
                    )
            if strikethroughs:
                for start_x, width, font, font_size in strikethroughs:
                    sl.append(
                        self._do_strikethrough(
                            start_x, self.y + (0.5 * h) + (0.3 * font_size), width, font
                        )
                    )
            if link:
                self.link(
                    self.x + dx,
                    self.y
                    + (0.5 * h)
                    - (
                        0.5
                        * frag.font_size  # pyright: ignore[reportPossiblyUnboundVariable]
                    ),
                    styled_txt_width,
                    frag.font_size,  # pyright: ignore[reportPossiblyUnboundVariable]
                    link,
                )

        if sl:
            # If any PDF settings have been left modified, wrap the line
            # in a local context.
            # pylint: disable=too-many-boolean-expressions
            if (
                current_ws != 0.0
                or current_lift != 0.0
                or current_char_vpos != CharVPos.LINE
                or current_font != self.current_font
                or current_font_size_pt != self.font_size_pt
                or current_font_style != self.font_style
                or current_text_mode != self.text_mode
                or fill_color_changed
                or current_font_stretching != self.font_stretching
                or current_char_spacing != self.char_spacing
            ):
                s = f"q {' '.join(sl)} Q"
            else:
                s = " ".join(sl)
            # pylint: enable=too-many-boolean-expressions
            self._out(s)
        # If the text is empty, h = max_font_size ends up as 0.
        # We still need a valid default height for self.ln() (issue #601).
        self._lasth = h or self.font_size

        # XPos.LEFT -> self.x stays the same
        if new_x == XPos.RIGHT:
            self.x += w
        elif new_x == XPos.START:
            self.x = s_start
        elif new_x == XPos.END:
            self.x = s_start + s_width
        elif new_x == XPos.WCONT:
            if s_width:
                self.x = s_start + s_width - r_c_margin
            else:
                self.x = s_start
        elif new_x == XPos.CENTER:
            self.x = s_start + s_width / 2.0
        elif new_x == XPos.LMARGIN:
            self.x = self.l_margin
        elif new_x == XPos.RMARGIN:
            self.x = self.w - self.r_margin

        # YPos.TOP:  -> self.y stays the same
        # YPos.LAST: -> self.y stays the same (single line)
        if new_y == YPos.NEXT:
            self.y += h
        if new_y == YPos.TMARGIN:
            self.y = self.t_margin
        if new_y == YPos.BMARGIN:
            self.y = self.h - self.b_margin

        return page_break_triggered

    def _add_quad_points(self, x: float, y: float, w: float, h: float) -> None:
        self._text_quad_points[self.page].extend(
            [
                x * self.k,
                (self.h - y) * self.k,
                (x + w) * self.k,
                (self.h - y) * self.k,
                x * self.k,
                (self.h - y - h) * self.k,
                (x + w) * self.k,
                (self.h - y - h) * self.k,
            ]
        )

    def _preload_bidirectional_text(
        self, text: str, markdown: bool
    ) -> Sequence[Fragment]:
        """ "
        Break the text into bidirectional segments and preload font styles for each fragment
        """
        if not self.text_shaping:
            return self._preload_font_styles(text, markdown)
        paragraph_direction = (
            self.text_shaping["direction"]
            if self.text_shaping["direction"]
            else auto_detect_base_direction(text)
        )

        paragraph = BidiParagraph(text=text, base_direction=paragraph_direction)
        directional_segments = paragraph.get_bidi_fragments()
        self.text_shaping["paragraph_direction"] = paragraph.base_direction

        fragments: list[Fragment] = []
        for bidi_text, bidi_direction in directional_segments:
            self.text_shaping["fragment_direction"] = bidi_direction
            fragments += self._preload_font_styles(bidi_text, markdown)
        return tuple(fragments)

    def _preload_font_styles(
        self, text: Optional[str], markdown: bool
    ) -> Sequence[Fragment]:
        """
        When Markdown styling is enabled, we require secondary fonts
        to ender text in bold & italics.
        This function ensure that those fonts are available.
        It needs to perform Markdown parsing,
        so we return the resulting `styled_txt_frags` tuple
        to avoid repeating this processing later on.
        """
        if not text:
            return tuple()
        prev_font_style = self.font_style
        if self.underline:
            prev_font_style += "U"
        if self.strikethrough:
            prev_font_style += "S"
        styled_txt_frags = tuple(self._parse_chars(text, markdown))
        if markdown:
            page = self.page
            # We set the current to page to zero so that
            # set_font() does not produce any text object on the stream buffer:
            self.page = 0
            if any(frag.font_style == "B" for frag in styled_txt_frags):
                # Ensuring bold font is supported:
                self.set_font(style="B")
            if any(frag.font_style == "I" for frag in styled_txt_frags):
                # Ensuring italics font is supported:
                self.set_font(style="I")
            if any(frag.font_style == "BI" for frag in styled_txt_frags):
                # Ensuring bold italics font is supported:
                self.set_font(style="BI")
            if any(frag.font_style == "" for frag in styled_txt_frags):
                # Ensuring base font is supported:
                self.set_font(style="")
            for frag in styled_txt_frags:
                frag.font = self.fonts[frag.font_family + frag.font_style]
            # Restoring initial style:
            self.set_font(style=prev_font_style)
            self.page = page
        return styled_txt_frags

    def get_fallback_font(self, char: str, style: str = "") -> Optional[str]:
        """
        Returns which fallback font has the requested glyph.
        This method can be overridden to provide more control than the `select_mode` parameter
        of `FPDF.set_fallback_fonts()` provides.
        """
        emphasis = TextEmphasis.coerce(style)
        fonts_with_char = [
            font_id
            for font_id in self._fallback_font_ids
            if ord(char) in self.fonts[font_id].cmap  # type: ignore[union-attr]
        ]
        if not fonts_with_char:
            return None
        font_with_matching_emphasis = next(
            (font for font in fonts_with_char if self.fonts[font].emphasis == emphasis),
            None,
        )
        if font_with_matching_emphasis:
            return font_with_matching_emphasis
        if self._fallback_font_exact_match:
            return None
        return fonts_with_char[0]

    def _parse_chars(self, text: str, markdown: bool) -> Iterator[Fragment]:
        "Split text into fragments"
        if not markdown and not self.text_shaping and not self._fallback_font_ids:
            if self.str_alias_nb_pages:
                for seq, fragment_text in enumerate(
                    text.split(self.str_alias_nb_pages)
                ):
                    if seq > 0:
                        yield TotalPagesSubstitutionFragment(
                            self.str_alias_nb_pages,
                            self._get_current_graphics_state(),
                            self.k,
                        )
                    if fragment_text:
                        yield Fragment(
                            fragment_text, self._get_current_graphics_state(), self.k
                        )
                return

            yield Fragment(text, self._get_current_graphics_state(), self.k)
            return
        txt_frag: list[str] = []
        in_bold: bool = "B" in self.font_style
        in_italics: bool = "I" in self.font_style
        in_strikethrough: bool = bool(self.strikethrough)
        in_underline: bool = bool(self.underline)
        current_fallback_font = None
        current_text_script = None

        def frag() -> Fragment:
            nonlocal txt_frag, current_fallback_font, current_text_script
            gstate = self._get_current_graphics_state()
            gstate.font_style = ("B" if in_bold else "") + ("I" if in_italics else "")
            gstate.strikethrough = in_strikethrough
            gstate.underline = in_underline
            if current_fallback_font:
                style = "".join(c for c in current_fallback_font if c in ("BI"))
                family = current_fallback_font.replace("B", "").replace("I", "")
                gstate.font_family = family
                gstate.font_style = style
                gstate.current_font = self.fonts[current_fallback_font]
                current_fallback_font = None
                current_text_script = None
            fragment = Fragment(
                txt_frag,
                gstate,
                self.k,
            )
            txt_frag = []
            return fragment

        if self.is_ttf_font:
            font_glyphs = self.current_font.cmap  # type: ignore[union-attr]
        else:
            font_glyphs = []

        escape_next_marker = 0
        escape_run = 0

        while text:
            if markdown and text[0] == self.MARKDOWN_ESCAPE_CHARACTER:
                escape_run += 1
                text = text[1:]
                continue

            if markdown and escape_run:
                is_escape_target = text[:2] in (
                    self.MARKDOWN_BOLD_MARKER,
                    self.MARKDOWN_ITALICS_MARKER,
                    self.MARKDOWN_STRIKETHROUGH_MARKER,
                    self.MARKDOWN_UNDERLINE_MARKER,
                )
                if is_escape_target and escape_run % 2 == 1:
                    for _ in range(escape_run - 1):
                        txt_frag.append(self.MARKDOWN_ESCAPE_CHARACTER)
                    if current_fallback_font:
                        if txt_frag:
                            yield frag()
                        current_fallback_font = None
                    escape_next_marker = 2
                    escape_run = 0
                    continue
                for _ in range(escape_run):
                    txt_frag.append(self.MARKDOWN_ESCAPE_CHARACTER)
                escape_run = 0

            is_marker = text[:2] in (
                self.MARKDOWN_BOLD_MARKER,
                self.MARKDOWN_ITALICS_MARKER,
                self.MARKDOWN_STRIKETHROUGH_MARKER,
                self.MARKDOWN_UNDERLINE_MARKER,
            )
            if markdown and escape_next_marker:
                is_marker = False
            half_marker = text[0]
            text_script = get_unicode_script(text[0])
            if text_script not in (
                UnicodeScript.COMMON,
                UnicodeScript.UNKNOWN,
                current_text_script,
            ):
                if txt_frag and current_text_script:
                    yield frag()
                current_text_script = text_script

            if self.str_alias_nb_pages:
                if text[: len(self.str_alias_nb_pages)] == self.str_alias_nb_pages:
                    if txt_frag:
                        yield frag()
                    gstate = self._get_current_graphics_state()
                    gstate.font_style = ("B" if in_bold else "") + (
                        "I" if in_italics else ""
                    )
                    gstate.strikethrough = in_strikethrough
                    gstate.underline = in_underline
                    yield TotalPagesSubstitutionFragment(
                        self.str_alias_nb_pages,
                        gstate,
                        self.k,
                    )
                    text = text[len(self.str_alias_nb_pages) :]
                    continue

            # Check that previous & next characters are not identical to the marker:
            if markdown:
                if (
                    is_marker
                    and (not txt_frag or txt_frag[-1] != half_marker)
                    and (len(text) < 3 or text[2] != half_marker)
                ):
                    if txt_frag:
                        yield frag()
                    if text[:2] == self.MARKDOWN_BOLD_MARKER:
                        in_bold = not in_bold
                    if text[:2] == self.MARKDOWN_ITALICS_MARKER:
                        in_italics = not in_italics
                    if text[:2] == self.MARKDOWN_STRIKETHROUGH_MARKER:
                        in_strikethrough = not in_strikethrough
                    if text[:2] == self.MARKDOWN_UNDERLINE_MARKER:
                        in_underline = not in_underline
                    text = text[2:]
                    continue

                is_link = self.MARKDOWN_LINK_REGEX.match(text)
                if is_link:
                    link_text, link_dest, text = is_link.groups()
                    if txt_frag:
                        yield frag()
                    gstate = self._get_current_graphics_state()
                    gstate.underline = self.MARKDOWN_LINK_UNDERLINE
                    if self.MARKDOWN_LINK_COLOR:
                        gstate.text_color = convert_to_device_color(
                            self.MARKDOWN_LINK_COLOR
                        )
                    try:
                        page = int(link_dest)
                        link_dest = self.add_link(page=page)
                    except ValueError:
                        pass
                    yield Fragment(
                        list(link_text),
                        gstate,
                        self.k,
                        link=link_dest,
                    )
                    continue
            if self.is_ttf_font and text[0] != "\n" and not ord(text[0]) in font_glyphs:
                style = ("B" if in_bold else "") + ("I" if in_italics else "")
                fallback_font = self.get_fallback_font(text[0], style)
                if fallback_font:
                    if fallback_font == current_fallback_font:
                        txt_frag.append(text[0])
                        text = text[1:]
                        continue
                    if txt_frag:
                        yield frag()
                    current_fallback_font = fallback_font
                    txt_frag.append(text[0])
                    text = text[1:]
                    continue
            if current_fallback_font:
                if txt_frag:
                    yield frag()
                current_fallback_font = None
            txt_frag.append(text[0])
            text = text[1:]
            if markdown and escape_next_marker:
                escape_next_marker -= 1
                if escape_next_marker == 0:
                    yield frag()
        if markdown and escape_run:
            for _ in range(escape_run):
                txt_frag.append(self.MARKDOWN_ESCAPE_CHARACTER)
            escape_run = 0
        if txt_frag:
            yield frag()

    def will_page_break(self, height: float) -> bool:
        """
        Let you know if adding an element will trigger a page break,
        based on its height and the current ordinate (`y` position).

        Detailed documentation on page breaks: https://py-pdf.github.io/fpdf2/PageBreaks.html

        Args:
            height (float): height of the section that would be added, e.g. a cell

        Returns: a boolean indicating if a page break would occur
        """
        return (
            self.y + height > self.page_break_trigger
            and not self.in_footer
            and self.accept_page_break
        )

    def _perform_page_break_if_need_be(self, h: float) -> bool:
        if self.will_page_break(h):
            LOGGER.debug(
                "Page break on page %d at y=%d for element of height %d > %d",
                self.page,
                self.y,
                h,
                self.page_break_trigger,
            )
            self._perform_page_break()
            return True
        return False

    def _perform_page_break(self) -> None:
        """
        Performs a page break, taking care to preserve self.x
        and a potential existing `fpdf.fpdf.FPDF.local_context()`.
        A call to `fpdf.fpdf.FPDF.will_page_break()` should be performed beforehand.
        """
        x = self.x
        # If we are in a .local_context(), we need to temporarily leave it,
        # by popping out every GraphicsState:
        gs_stack: list[StateStackType] = []
        while self._is_current_graphics_state_nested():
            gs_stack.append(self._get_current_graphics_state())
            self._pop_local_stack()
            # This code assumes that every Graphics State in the stack
            # has been pushed in it while adding a "q" in the PDF stream
            # (which is what FPDF.local_context() does):
            self._end_local_context()
        # Using a temporary GS to render header & footer:
        self.current_font_is_set_on_page = False
        self._push_local_stack()
        self.add_page(same=True)
        self._pop_local_stack()
        for prev_gs in reversed(gs_stack):
            self._push_local_stack()
            prev_gs.current_font_is_set_on_page = False
            self._start_local_context(**prev_gs.as_kwargs())
        self.x = x  # restore x but not y after drawing header

    def _has_next_page(self) -> bool:
        return self.pages_count > self.page

    @contextmanager
    def _disable_writing(self) -> Iterator[None]:
        if not isinstance(self._out, types.MethodType):
            # This mean that self._out has already been redefined.
            # This is the case of a nested call to this method: we do nothing
            yield
            return
        self._out = lambda *args, **kwargs: None  # type: ignore[method-assign]
        prev_page, prev_pages_count, prev_x, prev_y = (
            self.page,
            self.pages_count,
            self.x,
            self.y,
        )
        annots = self.pages[self.page].annots or PDFArray()
        self._push_local_stack()
        try:
            yield
        finally:
            self._pop_local_stack()
            # restore location:
            for p in range(prev_pages_count + 1, self.pages_count + 1):
                del self.pages[p]
            self.page = prev_page
            self.pages[self.page].annots = annots
            self.set_xy(prev_x, prev_y)
            # restore writing function:
            del self._out

    # multi_cell has dynamic results depending on the `output` parameter
    MultiCellPageBreakResult: TypeAlias = bool
    MultiCellLinesResult: TypeAlias = list[str]
    MultiCellHeightResult: TypeAlias = float

    MultiCellResult: TypeAlias = (
        MultiCellPageBreakResult
        | MultiCellLinesResult
        | MultiCellHeightResult
        | tuple[MultiCellPageBreakResult, MultiCellLinesResult]
        | tuple[MultiCellPageBreakResult, MultiCellHeightResult]
        | tuple[MultiCellLinesResult, MultiCellHeightResult]
        | tuple[MultiCellPageBreakResult, MultiCellLinesResult, MultiCellHeightResult]
    )

    @check_page
    @support_deprecated_txt_arg
    def multi_cell(
        self,
        w: float,
        h: Optional[float] = None,
        text: str = "",
        border: Literal[0, 1] | str = 0,
        align: str | Align = Align.J,
        fill: bool = False,
        split_only: bool = False,  # DEPRECATED
        link: Optional[int | str] = None,
        ln: Literal["DEPRECATED"] = "DEPRECATED",
        max_line_height: Optional[float] = None,
        markdown: bool = False,
        print_sh: bool = False,
        new_x: str | XPos = XPos.RIGHT,
        new_y: str | YPos = YPos.NEXT,
        wrapmode: WrapMode = WrapMode.WORD,
        dry_run: bool = False,
        output: str | MethodReturnValue = MethodReturnValue.PAGE_BREAK,
        center: bool = False,
        padding: int | Sequence[int] | Padding = 0,
    ) -> MultiCellResult:
        """
        This method allows printing text with line breaks. They can be automatic
        (breaking at the most recent space or soft-hyphen character) as soon as the text
        reaches the right border of the cell, or explicit (via the `\\n` character).
        As many cells as necessary are stacked, one below the other.
        Text can be aligned, centered or justified. The cell block can be framed and
        the background painted. A cell has an horizontal padding, on the left & right sides,
        defined by the.c_margin property.

        Args:
            w (float): cell width. If 0, they extend up to the right margin of the page.
            h (float): height of a single line of text.  Default value: None, meaning to use the current font size.
            text (str): string to print.
            border: Indicates if borders must be drawn around the cell.
                The value can be either a number (`0`: no border ; `1`: frame)
                or a string containing some or all of the following characters
                (in any order):
                `L`: left ; `T`: top ; `R`: right ; `B`: bottom. Default value: 0.
            align (fpdf.enums.Align, str): Set text alignment inside the cell.
                Possible values are:
                `J`: justify (default value); `L` or empty string: left align;
                `C`: center; `X`: center around current x position; `R`: right align
            fill (bool): Indicates if the cell background must be painted (`True`)
                or transparent (`False`). Default value: False.
            split_only (bool): **DEPRECATED since 2.7.4**:
                Use `dry_run=True` and `output=("LINES",)` instead.
            link (str): optional link to add on the cell, internal
                (identifier returned by `add_link`) or external URL.
            new_x (fpdf.enums.XPos, str): New current position in x after the call. Default: RIGHT
            new_y (fpdf.enums.YPos, str): New current position in y after the call. Default: NEXT
            ln (int): **DEPRECATED since 2.5.1**: Use `new_x` and `new_y` instead.
            max_line_height (float): optional maximum height of each sub-cell generated
            markdown (bool): enable minimal markdown-like markup to render part
                of text as bold / italics / strikethrough / underlined.
                Supports `\\` as escape character. Default to False.
            print_sh (bool): Treat a soft-hyphen (\\u00ad) as a normal printable
                character, instead of a line breaking opportunity. Default value: False
            wrapmode (fpdf.enums.WrapMode): "WORD" for word based line wrapping (default),
                "CHAR" for character based line wrapping.
            dry_run (bool): if `True`, does not output anything in the document.
                Can be useful when combined with `output`.
            output (fpdf.enums.MethodReturnValue): defines what this method returns.
                If several enum values are joined, the result will be a tuple.
            txt (str): [**DEPRECATED since v2.7.6**] string to print.
            center (bool): center the cell horizontally on the page.
            padding (float or Sequence): padding to apply around the text. Default value: 0.
                When one value is specified, it applies the same padding to all four sides.
                When two values are specified, the first padding applies to the top and bottom, the second to
                the left and right. When three values are specified, the first padding applies to the top,
                the second to the right and left, the third to the bottom. When four values are specified,
                the paddings apply to the top, right, bottom, and left in that order (clockwise)
                If padding for left or right ends up being non-zero then respective c_margin is ignored.

        Center overrides values for horizontal padding

        Using `new_x=XPos.RIGHT, new_y=XPos.TOP, maximum height=pdf.font_size` is
        useful to build tables with multiline text in cells.

        Returns: a single value or a tuple, depending on the `output` parameter value
        """

        padding = Padding.new(padding)
        wrapmode = WrapMode.coerce(wrapmode)

        if split_only:
            warnings.warn(
                (
                    'The parameter "split_only" is deprecated since v2.7.4.'
                    ' Use instead dry_run=True and output="LINES".'
                ),
                DeprecationWarning,
                stacklevel=get_stack_level(),
            )
        if dry_run or split_only:
            with self._disable_writing():
                return self.multi_cell(
                    w=w,
                    h=h,
                    text=text,
                    border=border,
                    align=align,
                    fill=fill,
                    link=link,
                    ln=ln,
                    max_line_height=max_line_height,
                    markdown=markdown,
                    print_sh=print_sh,
                    new_x=new_x,
                    new_y=new_y,
                    wrapmode=wrapmode,
                    dry_run=False,
                    split_only=False,
                    output=MethodReturnValue.LINES if split_only else output,
                    center=center,
                    padding=padding,
                )
        if not self.font_family:
            raise FPDFException("No font set, you need to call set_font() beforehand")
        if isinstance(w, str) or isinstance(h, str):
            raise ValueError(
                "Parameter 'w' and 'h' must be numbers, not strings."
                " You can omit them by passing string content with text="
            )
        new_x = XPos.coerce(new_x)
        new_y = YPos.coerce(new_y)
        if ln != "DEPRECATED":
            # For backwards compatibility, if "ln" is used we overwrite "new_[xy]".
            if ln == 0:
                new_x = XPos.RIGHT
                new_y = YPos.NEXT
            elif ln == 1:
                new_x = XPos.LMARGIN
                new_y = YPos.NEXT
            elif ln == 2:
                new_x = XPos.LEFT
                new_y = YPos.NEXT
            elif ln == 3:
                new_x = XPos.RIGHT
                new_y = YPos.TOP
            else:
                raise ValueError(
                    f'Invalid value for parameter "ln" ({ln}),'
                    " must be an int between 0 and 3."
                )
            warnings.warn(
                (
                    'The parameter "ln" is deprecated since v2.5.2.'
                    f" Instead of ln={ln} use new_x=XPos.{new_x.name}, new_y=YPos.{new_y.name}."
                ),
                DeprecationWarning,
                stacklevel=get_stack_level(),
            )
        align = Align.coerce(align)

        page_break_triggered = False

        if h is None:
            h = self.font_size

        # If width is 0, set width to available width between margins
        if w == 0:
            w = self.w - self.r_margin - self.x

        # Store the starting position before applying padding
        prev_x, prev_y = self.x, self.y

        # Apply padding to contents
        # decrease maximum allowed width by padding
        # shift the starting point by padding
        maximum_allowed_width = w = w - padding.right - padding.left
        clearance_margins: list[float] = []
        # If we don't have padding on either side, we need a clearance margin.
        if not padding.left:
            clearance_margins.append(self.c_margin)
        if not padding.right:
            clearance_margins.append(self.c_margin)
        if align != Align.X:
            self.x += padding.left
        self.y += padding.top

        # Center overrides padding
        if center:
            self.x = (
                self.w / 2 if align == Align.X else self.l_margin + (self.epw - w) / 2
            )
            prev_x = self.x

        # Calculate text length
        text = self.normalize_text(text)
        normalized_string = text.replace("\r", "")
        styled_text_fragments = (
            self._preload_bidirectional_text(normalized_string, markdown)
            if self.text_shaping
            else self._preload_font_styles(normalized_string, markdown)
        )

        prev_current_font = self.current_font
        prev_font_style = self.font_style
        prev_underline = self.underline
        total_height: float = 0

        text_lines: list[TextLine] = []
        multi_line_break = MultiLineBreak(
            styled_text_fragments,
            maximum_allowed_width,
            clearance_margins,
            align=align,
            print_sh=print_sh,
            wrapmode=wrapmode,
        )
        text_line = multi_line_break.get_line()
        while (text_line) is not None:
            text_lines.append(text_line)
            text_line = multi_line_break.get_line()

        if not text_lines:  # ensure we display at least one cell - cf. issue #349
            text_lines = [
                TextLine(
                    [],
                    text_width=0,
                    number_of_spaces=0,
                    align=align,
                    height=h,
                    max_width=w,
                    trailing_nl=False,
                )
            ]

        if max_line_height is None or len(text_lines) == 1:
            line_height = h
        else:
            line_height = min(h, max_line_height)

        box_required = fill or border
        page_break_triggered = False

        for text_line_index, text_line in enumerate(text_lines):
            start_of_new_page = self._perform_page_break_if_need_be(h + padding.bottom)
            if start_of_new_page:
                page_break_triggered = True
                self.y += padding.top

            if box_required and (text_line_index == 0 or start_of_new_page):
                # estimate how many cells can fit on this page
                top_gap = self.y  # Top padding has already been added
                bottom_gap = padding.bottom + self.b_margin
                lines_before_break = int((self.h - top_gap - bottom_gap) // line_height)
                # check how many cells should be rendered
                num_lines = min(lines_before_break, len(text_lines) - text_line_index)
                box_height = max(
                    h - text_line_index * line_height, num_lines * line_height
                )
                # render the box
                x = self.x - (w / 2 if align == Align.X else 0)
                draw_box_borders(
                    self,
                    x - padding.left,
                    self.y - padding.top,
                    x + w + padding.right,
                    self.y + box_height + padding.bottom,
                    border,
                    self.fill_color if fill else None,
                )
            is_last_line = text_line_index == len(text_lines) - 1
            self._render_styled_text_line(
                text_line,
                h=line_height,
                new_x=new_x if is_last_line else XPos.LEFT,
                new_y=new_y if is_last_line else YPos.NEXT,
                border=0,  # already rendered
                fill=False,  # already rendered
                link=link,
                padding=Padding(0, padding.right, 0, padding.left),
                prevent_font_change=markdown,
            )
            total_height += line_height
            if not is_last_line and align == Align.X:
                # prevent cumulative shift to the left
                self.x = prev_x

        if total_height < h:
            # Move to the bottom of the multi_cell
            if new_y == YPos.NEXT:
                self.y += h - total_height
            total_height = h

        if page_break_triggered and new_y == YPos.TOP:
            # When a page jump is performed and the requested y is TOP,
            # pretend we started at the top of the text block on the new page.
            # cf. test_multi_cell_table_with_automatic_page_break
            prev_y = self.y

        last_line = text_lines[-1]
        if last_line and last_line.trailing_nl and new_y in (YPos.LAST, YPos.NEXT):
            # The line renderer can't handle trailing newlines in the text.
            self.ln()

        if new_y == YPos.TOP:  # We may have jumped a few lines -> reset
            self.y = prev_y
        elif new_y == YPos.NEXT:  # move down by bottom padding
            self.y += padding.bottom

        if markdown:
            self.font_style = prev_font_style
            self.current_font = prev_current_font
            self.underline = prev_underline

        if new_x == XPos.RIGHT:  # move right by right padding to align outer RHS edge
            self.x += padding.right
        elif new_x == XPos.LEFT:  # move left by left padding to align outer LHS edge
            self.x -= padding.left

        output = MethodReturnValue.coerce(output)
        return_value = ()
        if output & MethodReturnValue.PAGE_BREAK:
            return_value += (page_break_triggered,)  # type: ignore[assignment]
        if output & MethodReturnValue.LINES:
            output_lines: list[str] = []
            for text_line in text_lines:
                characters: list[str] = []
                for frag in text_line.fragments:
                    characters.extend(frag.characters)
                output_lines.append("".join(characters))
            return_value += (output_lines,)  # type: ignore[assignment]
        if output & MethodReturnValue.HEIGHT:
            return_value += (total_height + padding.top + padding.bottom,)  # type: ignore[assignment]
        if len(return_value) == 1:
            return return_value[0]
        return return_value  # type: ignore[return-value]

    @check_page
    @support_deprecated_txt_arg
    def write(
        self,
        h: Optional[float] = None,
        text: str = "",
        link: Optional[str | int] = "",
        print_sh: bool = False,
        wrapmode: WrapMode = WrapMode.WORD,
    ) -> bool:
        """
        Prints text from the current position.
        When the right margin is reached, a line break occurs at the most recent
        space or soft-hyphen character, and text continues from the left margin.
        A manual break happens any time the \\n character is met,
        Upon method exit, the current position is left just at the end of the text.

        Args:
            h (float): line height. Default value: None, meaning to use the current font size.
            text (str): text content
            link (str): optional link to add on the text, internal
                (identifier returned by `FPDF.add_link`) or external URL.
            print_sh (bool): Treat a soft-hyphen (\\u00ad) as a normal printable
                character, instead of a line breaking opportunity. Default value: False
            wrapmode (fpdf.enums.WrapMode): "WORD" for word based line wrapping (default),
                "CHAR" for character based line wrapping.
            txt (str): [**DEPRECATED since v2.7.6**] text content
        """
        wrapmode = WrapMode.coerce(wrapmode)
        if not self.font_family:
            raise FPDFException("No font set, you need to call set_font() beforehand")
        if isinstance(h, str):
            raise ValueError(
                "Parameter 'h' must be a number, not a string."
                " You can omit it by passing string content with text="
            )
        if h is None:
            h = self.font_size

        page_break_triggered = False
        normalized_string = self.normalize_text(text).replace("\r", "")
        styled_text_fragments = (
            self._preload_bidirectional_text(normalized_string, False)
            if self.text_shaping
            else self._preload_font_styles(normalized_string, False)
        )

        text_lines: list[TextLine] = []
        multi_line_break = MultiLineBreak(
            styled_text_fragments,
            lambda _height: max_width,  # pyright: ignore[reportUnknownLambdaType]
            (self.c_margin, self.c_margin),
            print_sh=print_sh,
            wrapmode=wrapmode,
        )
        # first line from current x position to right margin
        first_width = self.w - self.x - self.r_margin
        max_width = first_width
        text_line = multi_line_break.get_line()
        # remaining lines fill between margins
        full_width = self.w - self.l_margin - self.r_margin
        max_width = full_width
        while (text_line) is not None:
            text_lines.append(text_line)
            text_line = multi_line_break.get_line()
        if not text_lines:
            return False

        for text_line_index, text_line in enumerate(text_lines):
            if text_line_index > 0:
                self.ln()
            new_page = self._render_styled_text_line(
                text_line,
                h=h,
                border=0,
                new_x=XPos.WCONT,
                new_y=YPos.TOP,
                fill=False,
                link=link,
            )
            page_break_triggered = page_break_triggered or new_page
        if text_line is not None and text_line.trailing_nl:
            # The line renderer can't handle trailing newlines in the text.
            self.ln()
        return page_break_triggered

    @check_page
    def text_columns(
        self,
        text: Optional[str] = None,
        img: Optional[str] = None,
        img_fill_width: bool = False,
        ncols: int = 1,
        gutter: Optional[float] = 10,
        balance: bool = False,
        text_align: Optional[Align | str] = "LEFT",
        line_height: Optional[float] = 1,
        l_margin: Optional[float] = None,
        r_margin: Optional[float] = None,
        print_sh: Optional[bool] = False,
        wrapmode: Optional[WrapMode] = WrapMode.WORD,
        skip_leading_spaces: Optional[bool] = False,
    ) -> TextColumns:
        """Establish a layout with multiple columns to fill with text.
        Args:
            text (str, optional): A first piece of text to insert.
            ncols (int, optional): the number of columns to create. (Default: 1).
            gutter (float, optional): The distance between the columns. (Default: 10).
            balance: (bool, optional): Specify whether multiple columns should end at approximately
                the same height, if they don't fill the page. (Default: False)
            text_align (Align or str, optional): The alignment of the text within the region.
                (Default: "LEFT")
            line_height (float, optional): A multiplier relative to the font size changing the
                vertical space occupied by a line of text. (Default: 1.0).
            l_margin (float, optional): Override the current left page margin.
            r_margin (float, optional): Override the current right page margin.
            print_sh (bool, optional): Treat a soft-hyphen (\\u00ad) as a printable character,
                instead of a line breaking opportunity. (Default: False)
            wrapmode (fpdf.enums.WrapMode, optional): "WORD" for word based line wrapping,
                "CHAR" for character based line wrapping. (Default: "WORD")
            skip_leading_spaces (bool, optional): On each line, any space characters at the
                beginning will be skipped if True. (Default: False)
        """
        return TextColumns(
            self,
            text=text,
            img=img,
            img_fill_width=img_fill_width,
            ncols=ncols,
            gutter=gutter or 10,
            balance=balance,
            text_align=text_align,
            line_height=line_height,
            l_margin=l_margin,
            r_margin=r_margin,
            print_sh=print_sh,
            wrapmode=wrapmode,
            skip_leading_spaces=skip_leading_spaces,
        )

    def image(
        self,
        name: ImageType,
        x: Optional[float | Align] = None,
        y: Optional[float] = None,
        w: float = 0,
        h: float = 0,
        type: str | Literal["DEPRECATED"] | None = "",
        link: Optional[str | int] = "",
        title: Optional[str] = None,
        alt_text: Optional[str] = None,
        dims: Optional[tuple[float, float]] = None,
        keep_aspect_ratio: bool = False,
    ) -> RasterImageInfo | VectorImageInfo:
        """
        Put an image on the page.

        The size of the image on the page can be specified in different ways:
        * explicit width and height (expressed in user units)
        * one explicit dimension, the other being calculated automatically
          in order to keep the original proportions
        * no explicit dimension, in which case the image is put at 72 dpi.
        * explicit width and height (expressed in user units) and `keep_aspect_ratio=True`

        **Remarks**:
        * if an image is used several times, only one copy is embedded in the file.
        * when using an animated GIF, only the first frame is used.

        Args:
            name: either a string representing a file path to an image, an URL to an image,
                bytes, an io.BytesIO, or a instance of `PIL.Image.Image`
            x (float, fpdf.enums.Align): optional horizontal position where to put the image on the page.
                If not specified or equal to None, the current abscissa is used.
                `fpdf.enums.Align.C` can also be passed to center the image horizontally;
                and `fpdf.enums.Align.R` to place it along the right page margin
            y (float): optional vertical position where to put the image on the page.
                If not specified or equal to None, the current ordinate is used.
                After the call, the current ordinate is moved to the bottom of the image
            w (float): optional width of the image. If not specified or equal to zero,
                it is automatically calculated from the image size.
                Pass `pdf.epw` to scale horizontally to the full page width.
            h (float): optional height of the image. If not specified or equal to zero,
                it is automatically calculated from the image size.
                Pass `pdf.eph` to scale horizontally to the full page height.
            type (str): [**DEPRECATED since 2.2.0**] unused, will be removed in a later version.
            link (str): optional link to add on the image, internal
                (identifier returned by `FPDF.add_link`) or external URL.
            title (str): optional. Currently, never seem rendered by PDF readers.
            alt_text (str): optional alternative text describing the image,
                for accessibility purposes. Displayed by some PDF readers on hover.
            dims (Tuple[float]): optional dimensions as a tuple (width, height) to resize the image
                before storing it in the PDF. Note that those are the **intrinsic** image dimensions,
                but the image will still be rendered on the page with the width (`w`) and height (`h`)
                provided as parameters. Note also that the `.oversized_images` attribute of FPDF
                provides an automated way to auto-adjust those intrinsic image dimensions.
            keep_aspect_ratio (bool): ensure the image fits in the rectangle defined by `x`, `y`, `w` & `h`
                while preserving its original aspect ratio. Defaults to False.
                Only meaningful if both `w` & `h` are provided.

        If `y` is provided, this method will not trigger any page break;
        otherwise, auto page break detection will be performed.

        Returns: an instance of a subclass of `ImageInfo`.
        """
        if not self.page:
            raise FPDFException("No page open, you need to call add_page() first")
        if type:
            warnings.warn(
                (
                    '"type" parameter is deprecated since v2.2.0, '
                    "unused and will soon be removed"
                ),
                DeprecationWarning,
                stacklevel=get_stack_level(),
            )

        name, img, info = preload_image(self.image_cache, name, dims)
        if isinstance(info, VectorImageInfo):
            return self._vector_image(
                name,
                cast(SVGObject, img),
                info,
                x,
                y,
                w,
                h,
                link,
                title,
                alt_text,
                keep_aspect_ratio,
            )
        if TYPE_CHECKING:
            assert not isinstance(img, SVGObject)
        return self._raster_image(
            name,
            img,
            info,
            x,
            y,
            w,
            h,
            link,
            title,
            alt_text,
            dims,
            keep_aspect_ratio,
        )

    def _raster_image(
        self,
        name: str,
        img: ImageType,
        info: RasterImageInfo,
        x: Optional[float | Align] = None,
        y: Optional[float] = None,
        w: float = 0,
        h: float = 0,
        link: Optional[str | int] = "",
        title: Optional[str] = None,
        alt_text: Optional[str] = None,
        dims: Optional[tuple[float, float]] = None,
        keep_aspect_ratio: bool = False,
    ) -> RasterImageInfo:
        if "smask" in info:
            self._set_min_pdf_version("1.4")

        # Automatic width and height calculation if needed
        w, h = info.size_in_document_units(w, h, scale=self.k)

        # Flowing mode
        if y is None:
            self._perform_page_break_if_need_be(h)
            y = self.y
            self.y += h
        if x is None:
            x = self.x

        if not isinstance(x, NumberClass):
            x = self.x_by_align(x, w, h, info, keep_aspect_ratio)
        if TYPE_CHECKING:
            x = float(x)
        if keep_aspect_ratio:
            x, y, w, h = info.scale_inside_box(x, y, w, h)
        if self.oversized_images and info["usages"] == 1 and not dims:
            info = self._downscale_image(name, img, info, w, h, scale=self.k)

        stream_content = stream_content_for_raster_image(
            info, x, y, w, h, keep_aspect_ratio, scale=self.k, pdf_height_to_flip=self.h
        )

        if title or alt_text:
            with self._marked_sequence(title=title, alt_text=alt_text):
                self._out(stream_content)
        else:
            self._out(stream_content)
        if link:
            self.link(x, y, w, h, link)

        self._resource_catalog.add(
            PDFResourceType.X_OBJECT, info["i"], self.page  # type: ignore
        )
        info["rendered_width"] = w
        info["rendered_height"] = h
        return info

    def x_by_align(
        self,
        x: Align | str,
        w: float,
        h: float,
        img_info: RasterImageInfo | VectorImageInfo,
        keep_aspect_ratio: bool,
    ) -> float:
        if keep_aspect_ratio:
            _, _, w, h = img_info.scale_inside_box(0, 0, w, h)
        x = Align.coerce(x)
        if x == Align.C:
            return (self.w - w) / 2
        if x == Align.R:
            return self.w - w - self.r_margin
        if x == Align.L:
            return self.l_margin
        raise ValueError(f"Unsupported 'x' value passed to .image(): {x}")

    def _vector_image(
        self,
        name: str,
        svg: SVGObject,
        info: VectorImageInfo,
        x: Optional[float | Align] = None,
        y: Optional[float] = None,
        w: float = 0,
        h: float = 0,
        link: Optional[str | int] = "",
        title: Optional[str] = None,
        alt_text: Optional[str] = None,
        keep_aspect_ratio: bool = False,
    ) -> VectorImageInfo:
        if not svg.viewbox and svg.width and svg.height:
            warnings.warn(
                '<svg> has no "viewBox", using its "width" & "height" as default "viewBox"',
                stacklevel=get_stack_level(),
            )
            svg.viewbox = [float(0), float(0), svg.width, svg.height]
        if w == 0 and h == 0:
            if svg.width and svg.height:
                w = (
                    svg.width * self.epw / 100
                    if isinstance(svg.width, Percent)
                    else svg.width
                )
                h = (
                    svg.height * self.eph / 100
                    if isinstance(svg.height, Percent)
                    else svg.height
                )
            elif svg.viewbox:
                _, _, w, h = svg.viewbox
            else:
                svg_id = "<svg>" if isinstance(name, bytes) else name
                raise ValueError(
                    f'{svg_id} has no "viewBox" nor "height" / "width": w= and h= must be provided to FPDF.image()'
                )
        elif w == 0 or h == 0:
            if svg.width and svg.height:
                svg_width, svg_height = svg.width, svg.height
            elif svg.viewbox:
                _, _, svg_width, svg_height = svg.viewbox
            else:
                raise ValueError(
                    '<svg> has no "viewBox" nor "height" / "width": w= and h= must be provided to FPDF.image()'
                )
            if w == 0:
                w = h * svg_width / svg_height
            else:  # h == 0
                h = w * svg_height / svg_width

        # Flowing mode
        if y is None:
            self._perform_page_break_if_need_be(h)
            y = self.y
            self.y += h
        if x is None:
            x = self.x

        if not isinstance(x, NumberClass):
            x = self.x_by_align(x, w, h, info, keep_aspect_ratio)
        x = float(x)
        if keep_aspect_ratio:
            x, y, w, h = info.scale_inside_box(x, y, w, h)

        _, _, path = svg.transform_to_rect_viewport(
            scale=1, width=w, height=h, ignore_svg_top_attrs=True
        )
        assert path.transform is not None
        path.transform = path.transform @ Transform.translation(x, y)

        old_x, old_y = self.x, self.y
        try:
            self.set_xy(0, 0)
            if title or alt_text:
                # Alt text of vector graphics does NOT show as tool-tip in viewers, but should
                # be processed by screen readers.
                with self._marked_sequence(title=title, alt_text=alt_text):
                    self.draw_path(path, copy=False)
            else:
                self.draw_path(path, copy=False)
        finally:
            self.set_xy(old_x, old_y)
        if link:
            self.link(x, y, w, h, link)

        return VectorImageInfo(rendered_width=w, rendered_height=h)

    def _downscale_image(
        self,
        name: str,
        img: ImageType,
        info: RasterImageInfo,
        w: float,
        h: float,
        scale: float,
    ) -> RasterImageInfo:
        images = self.image_cache.images
        width_in_pt, height_in_pt = w * scale, h * scale
        lowres_name = f"lowres-{name}"
        w = float(info["w"])  # type: ignore[arg-type]
        h = float(info["h"])  # type: ignore[arg-type]
        assert self.oversized_images is not None
        if (
            w > width_in_pt * self.oversized_images_ratio
            and h > height_in_pt * self.oversized_images_ratio
        ):
            factor = (
                min(w / width_in_pt, h / height_in_pt) / self.oversized_images_ratio
            )
            if self.oversized_images.lower().startswith("warn"):
                LOGGER.warning(
                    (
                        "OVERSIZED: Image %s with size %.1fx%.1fpx is rendered at size %.1fx%.1fpt."
                        " Set pdf.oversized_images = 'DOWNSCALE' to reduce embedded image size by a factor %.1f"
                    ),
                    name,
                    w,
                    h,
                    width_in_pt,
                    height_in_pt,
                    factor,
                )
            elif self.oversized_images.lower() == "downscale":
                dims = (
                    round(width_in_pt * self.oversized_images_ratio),
                    round(height_in_pt * self.oversized_images_ratio),
                )
                info["usages"] -= 1  # type: ignore[operator] # no need to embed highres version
                if info["usages"] == 0:
                    resources_per_page = self._resource_catalog.resources_per_page
                    for (_, rtype), resource in resources_per_page.items():
                        if rtype == PDFResourceType.X_OBJECT and info["i"] in resource:
                            resource.remove(cast(int, info["i"]))
                lowres_info = images.get(lowres_name)
                if lowres_info:  # Great, we've already done the job!
                    info = cast(RasterImageInfo, lowres_info)
                    lowres_w = float(info["w"])  # type: ignore[arg-type]
                    lowres_h = float(info["h"])  # type: ignore[arg-type]
                    if lowres_w * lowres_h < dims[0] * dims[1]:
                        # The existing low-res image is too small, we need a bigger low-res image:
                        info.update(
                            get_img_info(
                                name,
                                img or load_image(name),
                                self.image_cache.image_filter,
                                dims,
                            )
                        )
                        LOGGER.debug(
                            "OVERSIZED: Updated low-res image with name=%s id=%d to dims=%s",
                            lowres_name,
                            info["i"],
                            dims,
                        )
                    info["usages"] += 1  # type: ignore[operator]
                else:
                    info = RasterImageInfo(
                        get_img_info(
                            name,
                            img or load_image(name),
                            self.image_cache.image_filter,
                            dims,
                        )
                    )
                    info["i"] = len(images) + 1
                    info["usages"] = 1
                    images[lowres_name] = info
                    LOGGER.debug(
                        "OVERSIZED: Generated new low-res image with name=%s dims=%s id=%d",
                        lowres_name,
                        dims,
                        info["i"],
                    )
            else:
                raise ValueError(
                    f"Invalid value for attribute .oversized_images: {self.oversized_images}"
                )
        return info

    def preload_image(
        self,
        name: str | bytes | BinaryIO | Image | Path,
        dims: tuple[float, float] | None = None,
    ) -> tuple[
        str,
        SVGObject | Image | bytes | BinaryIO | Path | None,
        RasterImageInfo | VectorImageInfo,
    ]:
        """
        Read an image and load it into memory.

        .. deprecated:: 2.7.7
            Use `fpdf.image_parsing.preload_image` instead.
        """
        warnings.warn(
            (
                "FPDF.preload_image() is deprecated since v2.7.7 "
                "and will be removed in a future release. "
                "Use `fpdf.image_parsing.preload_image` instead."
            ),
            DeprecationWarning,
            stacklevel=get_stack_level(),
        )
        return preload_image(
            self.image_cache,
            name,  # pyright: ignore[reportArgumentType, reportReturnType]
            dims,
        )

    def preload_glyph_image(self, glyph_image_bytes: bytes | BinaryIO) -> tuple[
        str,
        SVGObject | Image | bytes | BinaryIO | Path | None,
        RasterImageInfo | VectorImageInfo,
    ]:
        return preload_image(
            image_cache=self.image_cache,
            name=glyph_image_bytes,
            dims=None,  # pyright: ignore[reportArgumentType, reportReturnType]
        )

    @contextmanager
    def _marked_sequence(self, **kwargs: Any) -> Iterator[StructElem]:
        """
        Can receive as named arguments any of the entries described in section 14.7.2 'Structure Hierarchy'
        of the PDF spec: iD, a, c, r, lang, e, actualText
        """
        mcid = self.struct_builder.next_mcid_for_page(self.page)
        struct_elem = self._add_marked_content(
            struct_type="/Figure", mcid=mcid, **kwargs
        )
        start_page = self.page
        self._out(f"/P <</MCID {mcid}>> BDC")
        yield struct_elem
        if self.page != start_page:
            raise FPDFException("A page jump occurred inside a marked sequence")
        self._out("EMC")

    def _add_marked_content(self, **kwargs: Any) -> StructElem:
        """
        Can receive as named arguments any of the entries described in section 14.7.2 'Structure Hierarchy'
        of the PDF spec: iD, a, c, r, lang, e, actualText
        """
        struct_elem, spid = self.struct_builder.add_marked_content(
            page_number=self.page, **kwargs
        )
        self.pages[self.page].struct_parents = spid
        self._set_min_pdf_version("1.4")  # due to using /MarkInfo
        return struct_elem

    @check_page
    def ln(self, h: Optional[float] = None) -> None:
        """
        Line Feed.
        The current abscissa goes back to the left margin and the ordinate increases by
        the amount passed as parameter.

        Args:
            h (float): The height of the break.
                By default, the value equals the height of the last printed text line
                (except when written by `.text()`). If no text has been written yet to
                the document, then the current font height is used.
        """
        self.x = self.l_margin
        if h is not None:
            self.y += h
        elif self._lasth:
            self.y += self._lasth
        else:
            self.y += self.font_size

    def get_x(self) -> float:
        """Returns the abscissa of the current position."""
        return self.x

    def set_x(self, x: float) -> None:
        """
        Defines the abscissa of the current position.
        If the value provided is negative, it is relative to the right of the page.

        Args:
            x (float): the new current abscissa
        """
        self.x = x if x >= 0 else self.w + x

    def get_y(self) -> float:
        """Returns the ordinate of the current position."""
        if self._in_unbreakable:
            raise FPDFException(
                "Using get_y() inside an unbreakable() code block is error-prone"
            )
        return self.y

    def set_y(self, y: float) -> None:
        """
        Moves the current abscissa back to the left margin and sets the ordinate.
        If the value provided is negative, it is relative to the bottom of the page.

        Args:
            y (float): the new current ordinate
        """
        self.x = self.l_margin
        self.y = y if y >= 0 else self.h + y

    def set_xy(self, x: float, y: float) -> None:
        """
        Defines the abscissa and ordinate of the current position.
        If the values provided are negative, they are relative respectively to the right and bottom of the page.

        Args:
            x (float): the new current abscissa
            y (float): the new current ordinate
        """
        self.set_y(y)
        self.set_x(x)

    def normalize_text(self, text: str) -> str:
        """Check that text input is in the correct format/encoding"""
        # - for TTF unicode fonts: unicode object (utf8 encoding)
        # - for built-in fonts: string instances (encoding: latin-1, cp1252)
        if not self.is_ttf_font and self.core_fonts_encoding:
            try:
                return text.encode(self.core_fonts_encoding).decode("latin-1")
            except UnicodeEncodeError as error:
                raise FPDFUnicodeEncodingException(
                    text_index=error.start,
                    character=text[error.start],
                    font_name=self.font_family + self.font_style,
                ) from error
        return text

    def sign_pkcs12(
        self,
        pkcs_filepath: str | Path,
        password: Optional[bytes] = None,
        hashalgo: str = "sha256",
        contact_info: Optional[str] = None,
        location: Optional[str] = None,
        signing_time: Optional[datetime] = None,
        reason: Optional[str] = None,
        flags: tuple[AnnotationFlag | str, ...] = (
            AnnotationFlag.PRINT,
            AnnotationFlag.LOCKED,
        ),
    ) -> None:
        """
        Args:
            pkcs_filepath (str): file path to a .pfx or .p12 PKCS12,
                in the binary format described by RFC 7292
            password (bytes-like): the password to use to decrypt the data.
                `None` if the PKCS12 is not encrypted.
            hashalgo (str): hashing algorithm used, passed to `hashlib.new`
            contact_info (str): optional information provided by the signer to enable
                a recipient to contact the signer to verify the signature
            location (str): optional CPU host name or physical location of the signing
            signing_time (datetime): optional time of signing
            reason (str): optional signing reason
            flags (Tuple[fpdf.enums.AnnotationFlag], Tuple[str]): optional list of flags defining annotation properties
        """
        if not signer:
            raise EnvironmentError(
                "endesive.signer not available - PDF cannot be signed - Try: pip install endesive"
            )
        with open(pkcs_filepath, "rb") as pkcs_file:
            key, cert, extra_certs = (
                pkcs12.load_key_and_certificates(  # pyright: ignore[reportOptionalMemberAccess]
                    pkcs_file.read(), password
                )
            )
        assert cert is not None
        self.sign(
            key=key,
            cert=cert,
            extra_certs=extra_certs,
            hashalgo=hashalgo,
            contact_info=contact_info,
            location=location,
            signing_time=signing_time,
            reason=reason,
            flags=flags,
        )

    @check_page
    def sign(
        self,
        key: Optional["PrivateKeyTypes"],
        cert: "Certificate",
        extra_certs: Optional[list["Certificate"]] = None,
        hashalgo: str = "sha256",
        contact_info: Optional[str] = None,
        location: Optional[str] = None,
        signing_time: Optional[datetime] = None,
        reason: Optional[str] = None,
        flags: tuple[AnnotationFlag | str, ...] = (
            AnnotationFlag.PRINT,
            AnnotationFlag.LOCKED,
        ),
    ) -> None:
        """
        Args:
            key: certificate private key
            cert (cryptography.x509.Certificate): certificate
            extra_certs (list[cryptography.x509.Certificate]): list of additional PKCS12 certificates
            hashalgo (str): hashing algorithm used, passed to `hashlib.new`
            contact_info (str): optional information provided by the signer to enable
                a recipient to contact the signer to verify the signature
            location (str): optional CPU host name or physical location of the signing
            signing_time (datetime): optional time of signing
            reason (str): optional signing reason
            flags (Tuple[fpdf.enums.AnnotationFlag], Tuple[str]): optional list of flags defining annotation properties
        """
        if not signer:
            raise EnvironmentError(
                "endesive.signer not available - PDF cannot be signed - Try: pip install endesive"
            )
        if self._sign_key:
            raise FPDFException(".sign* methods should be called only once")

        self._sign_key = key
        self._sign_cert = cert
        self._sign_extra_certs = extra_certs if extra_certs is not None else []
        self._sign_hashalgo = hashalgo
        self._sign_time: datetime = signing_time or self.creation_date

        annotation = PDFAnnotation(
            "Widget",
            field_type="Sig",
            x=0,
            y=0,
            width=0,
            height=0,
            flags=flags,
            title="signature",
            value=Signature(
                contact_info=contact_info,
                location=location,
                m=PDFDate(self._sign_time),
                reason=reason,
            ),
        )
        self.pages[self.page].add_annotation(annotation)

    def _insert_table_of_contents(self) -> None:
        # Doc has been closed but we want to write to self.pages[self.page] instead of self.buffer:
        tocp = self.toc_placeholder
        assert tocp is not None
        prev_page, prev_y = self.page, self.y
        self.page, self.y = tocp.start_page, tocp.y
        # flag rendering ToC for page breaking function
        self.in_toc_rendering = True
        self._set_orientation(tocp.page_orientation, self.dw_pt, self.dh_pt)
        tocp.render_function(self, self._outline)
        self.in_toc_rendering = False  # set ToC rendering flag off
        expected_final_page = tocp.start_page + tocp.pages - 1
        if self.page != expected_final_page and not self._toc_allow_page_insertion:
            too = "many" if self.page > expected_final_page else "few"
            error_msg = f"The rendering function passed to FPDF.insert_toc_placeholder triggered too {too} page breaks: "
            error_msg += f"ToC ended on page {self.page} while it was expected to span exactly {tocp.pages} pages"
            raise FPDFException(error_msg)
        if self._toc_inserted_pages:
            # Generating final page footer after more pages were inserted:
            self._render_footer()
            # We need to reorder the pages, because some new pages have been inserted in the ToC,
            # but they have been inserted at the end of self.pages:
            new_pages = [
                self.pages.pop(len(self.pages)) for _ in range(self._toc_inserted_pages)
            ]
            new_pages = list(reversed(new_pages))
            indices_remap: dict[int, int] = {}
            for page_index in range(
                tocp.start_page + 1, self.pages_count + len(new_pages) + 1
            ):
                if page_index in self.pages:
                    new_pages.append(self.pages.pop(page_index))
                page = self.pages[page_index] = new_pages.pop(0)
                # Fix page indices:
                indices_remap[page.index()] = page_index
                page.set_index(page_index)
                # Fix page labels:
                if tocp.reset_page_indices is False:
                    page.get_page_label().st = page_index  # type: ignore[union-attr]
            assert len(new_pages) == 0, f"#new_pages: {len(new_pages)}"
            # Fix links:
            for dest in self.links.values():
                assert dest.page_number is not None
                new_index = indices_remap.get(dest.page_number)
                if new_index is not None:
                    dest.page_number = new_index
            # Fix outline:
            for section in self._outline:
                new_index = indices_remap.get(section.page_number)
                if new_index is not None:
                    section.dest = section.dest.replace(page=new_index)
                    section.page_number = new_index
                    if section.struct_elem:
                        # pylint: disable=protected-access
                        section.struct_elem._page_number = (  # pyright: ignore[reportPrivateUsage]
                            new_index
                        )
            # Fix resource catalog:
            resources_per_page = self._resource_catalog.resources_per_page
            new_resources_per_page: dict[
                tuple[int, PDFResourceType], set[ResourceTypes]
            ] = defaultdict(set)
            for (page_number, resource_type), resource in resources_per_page.items():
                key = (indices_remap.get(page_number, page_number), resource_type)
                new_resources_per_page[key] = resource
            self._resource_catalog.resources_per_page = new_resources_per_page
        self.page, self.y = prev_page, prev_y

    def file_id(self) -> Optional[str | Literal[-1]]:  # pylint: disable=no-self-use
        """
        This method can be overridden in inherited classes
        in order to define a custom file identifier.
        Its output must have the format "<hex_string1><hex_string2>".
        If this method returns a falsy value (None, empty string),
        no /ID will be inserted in the generated PDF document.
        """
        return -1

    def _default_file_id(self, buffer: bytearray) -> str:
        # Quoting the PDF 1.7 spec, section 14.4 File Identifiers:
        # > The value of this entry shall be an array of two byte strings.
        # > The first byte string shall be a permanent identifier
        # > based on the contents of the file at the time it was originally created
        # > and shall not change when the file is incrementally updated.
        # > The second byte string shall be a changing identifier
        # > based on the file’s contents at the time it was last updated.
        # > When a file is first written, both identifiers shall be set to the same value.
        id_hash = hashlib.new("md5", usedforsecurity=False)  # nosec B324
        id_hash.update(buffer)
        if self.creation_date:
            id_hash.update(self.creation_date.strftime("%Y%m%d%H%M%S").encode("utf8"))
        hash_hex = id_hash.hexdigest().upper()
        return f"<{hash_hex}><{hash_hex}>"

    def _do_underline(
        self, x: float, y: float, w: float, font: Optional[CoreFont | TTFFont] = None
    ) -> str:
        """
        Draw an horizontal line under some text,
        starting from (x, y) with a length equal to 'w'
        """
        if font is None:
            font = self.current_font
        assert font is not None
        return (
            f"{x * self.k:.2f} "
            f"{(self.h - y + font.up / 1000 * self.font_size) * self.k:.2f} "  # pyright: ignore[reportUnknownMemberType]
            f"{w * self.k:.2f} "
            f"{-font.ut / 1000 * self.font_size_pt:.2f} re f"  # pyright: ignore[reportUnknownMemberType]
        )

    def _do_strikethrough(
        self, x: float, y: float, w: float, font: Optional[CoreFont | TTFFont] = None
    ) -> str:
        """
        Draw an horizontal line through some text,
        starting from (x, y) with a length equal to 'w'
        """
        if font is None:
            font = self.current_font
        assert font is not None
        return (
            f"{x * self.k:.2f} "
            f"{(self.h - y + font.sp / 1000 * self.font_size) * self.k:.2f} "  # pyright: ignore[reportUnknownMemberType]
            f"{w * self.k:.2f} "
            f"{-font.ss / 1000 * self.font_size_pt:.2f} re f"  # pyright: ignore[reportUnknownMemberType]
        )

    def _out(self, s: str | bytes) -> None:
        if self.buffer:
            raise FPDFException(
                "Content cannot be added on a finalized document, after calling output()"
            )
        if not isinstance(s, bytes):
            if not isinstance(s, str):
                s = str(s)
            s = s.encode("latin1")
        if not self.page:
            raise FPDFException("No page open, you need to call add_page() first")
        page_contents = self.pages[self.page].contents
        if isinstance(page_contents, bytearray):
            page_contents.extend(s)
            page_contents.append(0x0A)  # newline
        else:
            page_contents += s + b"\n"  # type: ignore[operator]

    @check_page
    @support_deprecated_txt_arg
    def interleaved2of5(
        self, text: str, x: float, y: float, w: float = 1, h: float = 10
    ) -> None:
        """Barcode I2of5 (numeric), adds a 0 if odd length"""
        narrow = w / 3
        wide = w

        # wide/narrow codes for the digits
        bar_char = {
            "0": "nnwwn",
            "1": "wnnnw",
            "2": "nwnnw",
            "3": "wwnnn",
            "4": "nnwnw",
            "5": "wnwnn",
            "6": "nwwnn",
            "7": "nnnww",
            "8": "wnnwn",
            "9": "nwnwn",
            "A": "nn",
            "Z": "wn",
        }
        # The caller should do this, or we can't rotate the thing.
        # self.set_fill_color(0)
        code = text
        # add leading zero if code-length is odd
        if len(code) % 2 != 0:
            code = f"0{code}"

        # add start and stop codes
        code = f"AA{code.lower()}ZA"

        for i in range(0, len(code), 2):
            # choose next pair of digits
            char_bar = code[i]
            char_space = code[i + 1]
            # check whether it is a valid digit
            if char_bar not in bar_char:
                raise RuntimeError(f'Char "{char_bar}" invalid for I25:')
            if char_space not in bar_char:
                raise RuntimeError(f'Char "{char_space}" invalid for I25: ')

            # create a wide/narrow-seq (first digit=bars, second digit=spaces)
            seq = "".join(
                f"{cb}{cs}" for cb, cs in zip(bar_char[char_bar], bar_char[char_space])
            )

            for bar_index, char in enumerate(seq):
                # set line_width depending on value
                line_width = narrow if char == "n" else wide

                # draw every second value, the other is represented by space
                if bar_index % 2 == 0:
                    self.rect(x, y, line_width, h, "F")

                x += line_width

    @check_page
    @support_deprecated_txt_arg
    def code39(
        self, text: str, x: float, y: float, w: float = 1.5, h: float = 5
    ) -> None:
        """Barcode 3of9"""
        dim = {"w": w, "n": w / 3}
        if not text.startswith("*") or not text.endswith("*"):
            warnings.warn(
                (
                    "Code 39 input must start and end with a '*' character to be valid."
                    " This method does not insert it automatically."
                ),
                stacklevel=get_stack_level(),
            )
        chars = {
            "0": "nnnwwnwnn",
            "1": "wnnwnnnnw",
            "2": "nnwwnnnnw",
            "3": "wnwwnnnnn",
            "4": "nnnwwnnnw",
            "5": "wnnwwnnnn",
            "6": "nnwwwnnnn",
            "7": "nnnwnnwnw",
            "8": "wnnwnnwnn",
            "9": "nnwwnnwnn",
            "A": "wnnnnwnnw",
            "B": "nnwnnwnnw",
            "C": "wnwnnwnnn",
            "D": "nnnnwwnnw",
            "E": "wnnnwwnnn",
            "F": "nnwnwwnnn",
            "G": "nnnnnwwnw",
            "H": "wnnnnwwnn",
            "I": "nnwnnwwnn",
            "J": "nnnnwwwnn",
            "K": "wnnnnnnww",
            "L": "nnwnnnnww",
            "M": "wnwnnnnwn",
            "N": "nnnnwnnww",
            "O": "wnnnwnnwn",
            "P": "nnwnwnnwn",
            "Q": "nnnnnnwww",
            "R": "wnnnnnwwn",
            "S": "nnwnnnwwn",
            "T": "nnnnwnwwn",
            "U": "wwnnnnnnw",
            "V": "nwwnnnnnw",
            "W": "wwwnnnnnn",
            "X": "nwnnwnnnw",
            "Y": "wwnnwnnnn",
            "Z": "nwwnwnnnn",
            "-": "nwnnnnwnw",
            ".": "wwnnnnwnn",
            " ": "nwwnnnwnn",
            "*": "nwnnwnwnn",
            "$": "nwnwnwnnn",
            "/": "nwnwnnnwn",
            "+": "nwnnnwnwn",
            "%": "nnnwnwnwn",
        }
        # The caller should do this, or we can't rotate the thing.
        # self.set_fill_color(0)
        for c in text.upper():
            if c not in chars:
                raise RuntimeError(f'Invalid char "{c}" for Code39')
            for i, d in enumerate(chars[c]):
                if i % 2 == 0:
                    self.rect(x, y, dim[d], h, "F")
                x += dim[d]
            x += dim["n"]

    @check_page
    @contextmanager
    def rect_clip(self, x: float, y: float, w: float, h: float) -> Iterator[None]:
        """
        Context manager that defines a rectangular crop zone,
        useful to render only part of an image.

        Args:
            x (float): abscissa of the clipping region top left corner
            y (float): ordinate of the clipping region top left corner
            w (float): width of the clipping region
            h (float): height of the clipping region
        """
        self._out(
            (
                f"q {x * self.k:.2f} {(self.h - y - h) * self.k:.2f} {w * self.k:.2f} "
                f"{h * self.k:.2f} re W n"
            )
        )
        yield
        self._out("Q")

    @check_page
    @contextmanager
    def elliptic_clip(self, x: float, y: float, w: float, h: float) -> Iterator[None]:
        """
        Context manager that defines an elliptic crop zone,
        useful to render only part of an image.

        Args:
            x (float): abscissa of the clipping region top left corner
            y (float): ordinate of the clipping region top left corner
            w (float): ellipse width
            h (float): ellipse height
        """
        self._out("q")
        self._draw_ellipse(x, y, w, h, "W n")
        yield
        self._out("Q")

    @check_page
    @contextmanager
    def round_clip(self, x: float, y: float, r: float) -> Iterator[None]:
        """
        Context manager that defines a circular crop zone,
        useful to render only part of an image.

        Args:
            x (float): abscissa of the clipping region top left corner
            y (float): ordinate of the clipping region top left corner
            r (float): radius of the clipping region
        """
        with self.elliptic_clip(x, y, r, r):
            yield

    @contextmanager
    def unbreakable(self) -> Iterator[FPDFRecorder]:
        """
        Ensures that all rendering performed in this context appear on a single page
        by performing page break beforehand if need be.

        Detailed documentation on page breaks: https://py-pdf.github.io/fpdf2/PageBreaks.html

        Notes
        -----

        Using this method means to duplicate the FPDF `bytearray` buffer:
        when generating large PDFs, doubling memory usage may be troublesome.
        """
        prev_page, prev_y = self.page, self.y
        recorder = FPDFRecorder(self, accept_page_break=False)
        recorder.page_break_triggered = False
        self._in_unbreakable = True
        LOGGER.debug("Starting unbreakable block")
        yield recorder
        y_scroll = recorder.y - prev_y + (recorder.page - prev_page) * self.eph
        if prev_y + y_scroll > self.page_break_trigger or recorder.page > prev_page:
            LOGGER.debug("Performing page jump due to unbreakable height")
            recorder.rewind()
            # pylint: disable=protected-access
            # Performing this call through .pdf so that it does not get recorded & replayed:
            recorder.pdf._perform_page_break()
            recorder.replay()
            recorder.page_break_triggered = True
        self._in_unbreakable = False
        LOGGER.debug("Ending unbreakable block")

    @contextmanager
    def offset_rendering(self) -> Iterator[FPDFRecorder]:
        """
        All rendering performed in this context is made on a dummy FPDF object.
        This allows to test the results of some operations on the global layout
        before performing them "for real".
        """
        prev_page, prev_y = self.page, self.y
        recorder = FPDFRecorder(self, accept_page_break=False)
        recorder.page_break_triggered = False
        yield recorder
        y_scroll = recorder.y - prev_y + (recorder.page - prev_page) * self.eph
        if prev_y + y_scroll > self.page_break_trigger or recorder.page > prev_page:
            recorder.page_break_triggered = True
        recorder.rewind()

    @check_page
    def insert_toc_placeholder(
        self,
        render_toc_function: Callable[["FPDF", list[OutlineSection]], None],
        pages: int = 1,
        allow_extra_pages: bool = False,
        reset_page_indices: bool = True,
    ) -> None:
        """
        Configure Table Of Contents rendering at the end of the document generation,
        and reserve some vertical space right now in order to insert it.
        At least one page break is triggered by this method.

        Args:
            render_toc_function (function): a function that will be invoked to render the ToC.
                This function will receive 2 parameters: `pdf`, an instance of FPDF, and `outline`,
                a list of `fpdf.outline.OutlineSection`.
            pages (int): the number of pages that the Table of Contents will span,
                including the current one that will. As many page breaks as the value of this argument
                will occur immediately after calling this method.
            allow_extra_pages (bool): If set to `True`, allows for an unlimited number of
                extra pages in the ToC, which may cause discrepancies with pre-rendered
                page numbers. For consistent numbering, using page labels to create a
                separate numbering style for the ToC is recommended.
            reset_page_indices (bool): Whether to reset the pages indices after the ToC. Default to True.
        """
        if pages < 1:
            raise ValueError(
                f"'pages' parameter must be equal or greater than 1: {pages}"
            )
        if not callable(render_toc_function):
            raise TypeError(
                f"The first argument must be a callable, got: {type(render_toc_function)}"
            )
        if self.toc_placeholder:
            raise FPDFException(
                "A placeholder for the table of contents has already been defined"
                f" on page {self.toc_placeholder.start_page}"
            )
        self.toc_placeholder = ToCPlaceholder(
            render_toc_function,
            self.page,
            self.y,
            self.cur_orientation,
            pages,
            reset_page_indices,
        )
        self._toc_allow_page_insertion = allow_extra_pages
        for _ in range(pages):
            self._perform_page_break()

    def set_section_title_styles(
        self,
        level0: TextStyle,
        level1: Optional[TextStyle] = None,
        level2: Optional[TextStyle] = None,
        level3: Optional[TextStyle] = None,
        level4: Optional[TextStyle] = None,
        level5: Optional[TextStyle] = None,
        level6: Optional[TextStyle] = None,
    ) -> None:
        """
        Defines a style for section titles.
        After calling this method, calls to `FPDF.start_section` will render section names visually.

        Args:
            level0 (TextStyle): style for the top level section titles
            level1 (TextStyle): optional style for the level 1 section titles
            level2 (TextStyle): optional style for the level 2 section titles
            level3 (TextStyle): optional style for the level 3 section titles
            level4 (TextStyle): optional style for the level 4 section titles
            level5 (TextStyle): optional style for the level 5 section titles
            level6 (TextStyle): optional style for the level 6 section titles
        """
        index: int
        level: Optional[TextStyle]
        for index, level in enumerate(
            [level0, level1, level2, level3, level4, level5, level6]
        ):
            if level is not None:
                if not isinstance(level, TextStyle):
                    raise TypeError(
                        f"Arguments must all be TextStyle instances, got: {type(level)}"
                    )
                self.section_title_styles[index] = level

    @check_page
    def start_section(self, name: str, level: int = 0, strict: bool = True) -> None:
        """
        Start a section in the document outline.
        If section_title_styles have been configured,
        render the section name visually as a title.

        Args:
            name (str): section name
            level (int): section level in the document outline. 0 means top-level.
            strict (bool): whether to raise an exception if levels increase incorrectly,
                for example with a level-3 section following a level-1 section.
        """
        if level < 0:
            raise ValueError('"level" mut be equal or greater than zero')
        if strict and self._outline and level > self._outline[-1].level + 1:
            raise ValueError(
                f"Incoherent hierarchy: cannot start a level {level} section after a level {self._outline[-1].level} one"
            )
        dest = DestinationXYZ(self.page, top=self.h_pt - self.y * self.k)
        outline_struct_elem = None
        if self.section_title_styles:
            text_style = self.section_title_styles[level]
            # We first check if adding this multi-cell will trigger a page break:
            if text_style.size_pt is not None:
                prev_font_size_pt = self.font_size_pt
                self.font_size_pt = text_style.size_pt
            # check if l_margin value is of type Align or string
            align = Align.L
            if isinstance(text_style.l_margin, (Align, str)):
                align = Align.coerce(text_style.l_margin)
            page_break_triggered = self.multi_cell(
                w=self.epw,
                h=self.font_size,
                text=name,
                new_x=XPos.LMARGIN,
                new_y=YPos.NEXT,
                dry_run=True,  # => does not produce any output
                output=MethodReturnValue.PAGE_BREAK,
                align=align,
                padding=Padding(
                    top=text_style.t_margin or 0,
                    left=(
                        text_style.l_margin
                        if isinstance(text_style.l_margin, (int, float))
                        else 0
                    ),
                    bottom=text_style.b_margin or 0,
                ),
            )
            if text_style.size_pt is not None:
                self.font_size_pt = (
                    prev_font_size_pt  # pyright: ignore[reportPossiblyUnboundVariable]
                )
            if page_break_triggered:
                # If so, we trigger a page break manually beforehand:
                self.add_page()
            with self._marked_sequence(title=name) as struct_elem:
                outline_struct_elem = struct_elem
                with self.use_text_style(text_style):
                    self.multi_cell(
                        w=self.epw,
                        h=self.font_size,
                        text=name,
                        align=align,
                        new_x=XPos.LMARGIN,
                        new_y=YPos.NEXT,
                        center=text_style.l_margin == Align.C,
                    )
        self._outline.append(
            OutlineSection(name, level, self.page, dest, outline_struct_elem)
        )

    @contextmanager
    def use_text_style(self, text_style: TextStyle) -> Iterator[None]:
        prev_l_margin = None
        if text_style:
            if text_style.t_margin:
                self.ln(text_style.t_margin)
            if text_style.l_margin:
                if isinstance(text_style.l_margin, (float, int)):
                    prev_l_margin = self.l_margin
                    self.l_margin = text_style.l_margin
                    self.x = self.l_margin
                else:
                    LOGGER.debug(
                        "Unsupported '%s' value provided as l_margin to .use_text_style()",
                        text_style.l_margin,
                    )
        with self.use_font_face(text_style):
            yield
        if text_style and text_style.b_margin:
            self.ln(text_style.b_margin)
        if prev_l_margin is not None:
            self.l_margin = prev_l_margin
            self.x = self.l_margin

    @contextmanager
    def use_font_face(self, font_face: FontFace) -> Iterator[None]:
        """
        Sets the provided `fpdf.fonts.FontFace` in a local context,
        then restore font settings back to they were initially.
        This method must be used as a context manager using `with`:

            with pdf.use_font_face(FontFace(emphasis="BOLD", color=255, size_pt=42)):
                put_some_text()

        Known limitation: in case of a page jump in this local context,
        the temporary style may "leak" in the header() & footer().
        """
        if not font_face:
            yield
            return
        prev_font = (self.font_family, self.font_style, self.font_size_pt)
        self.set_font(
            font_face.family or self.font_family,
            (
                font_face.emphasis.style
                if font_face.emphasis is not None
                else self.font_style
            ),
            font_face.size_pt or self.font_size_pt,
        )
        self.current_font_is_set_on_page = False
        prev_text_color = self.text_color
        if font_face.color is not None and font_face.color != self.text_color:
            self.set_text_color(font_face.color)
        prev_fill_color = self.fill_color
        if font_face.fill_color is not None:
            self.set_fill_color(font_face.fill_color)
        yield
        if font_face.fill_color is not None:
            assert prev_fill_color is not None
            self.set_fill_color(prev_fill_color)
        self.text_color = prev_text_color
        self.set_font(*prev_font)

    @check_page
    @contextmanager
    def table(self, *args: Any, **kwargs: Any) -> Iterator[Table]:
        """
        Inserts a table, that can be built using the `fpdf.table.Table` object yield.
        Detailed usage documentation: https://py-pdf.github.io/fpdf2/Tables.html

        Args:
            rows: optional. Sequence of rows (iterable) of str to initiate the table cells with text content.
            align (str, fpdf.enums.Align): optional, default to CENTER. Sets the table horizontal position
                relative to the page, when it's not using the full page width.
            borders_layout (str, fpdf.enums.TableBordersLayout): optional, default to ALL. Control what cell
                borders are drawn.
            cell_fill_color (int, tuple, fpdf.drawing.DeviceCMYK, fpdf.drawing.DeviceGray, fpdf.drawing.DeviceRGB): optional.
                Defines the cells background color.
            cell_fill_mode (str, fpdf.enums.TableCellFillMode): optional. Defines which cells are filled
                with color in the background.
            col_widths (int, tuple): optional. Sets column width. Can be a single number or a sequence of numbers.
            first_row_as_headings (bool): optional, default to True. If False, the first row of the table
                is not styled differently from the others.
            gutter_height (float): optional vertical space between rows.
            gutter_width (float): optional horizontal space between columns.
            headings_style (fpdf.fonts.FontFace): optional, default to bold.
                Defines the visual style of the top headings row: size, color, emphasis...
            line_height (number): optional. Defines how much vertical space a line of text will occupy.
            markdown (bool): optional, default to False. Enable markdown interpretation of cells textual content.
            text_align (str, fpdf.enums.Align): optional, default to JUSTIFY. Control text alignment inside cells.
            v_align (str, fpdf.enums.VAlign): optional, default to CENTER. Control vertical alignment of cells content.
            width (number): optional. Sets the table width.
            wrapmode (fpdf.enums.WrapMode): "WORD" for word based line wrapping (default),
                "CHAR" for character based line wrapping.
            padding (number, tuple, Padding): optional. Sets the cell padding. Can be a single number or a sequence
                of numbers, default:0
                If padding for left or right ends up being non-zero then the respective c_margin is ignored.
            outer_border_width (number): optional. The outer_border_width will trigger rendering of the outer
                border of the table with the given width regardless of any other defined border styles.
            num_heading_rows (number): optional. Sets the number of heading rows, default value is 1. If this value is not 1,
                first_row_as_headings needs to be True if num_heading_rows>1 and False if num_heading_rows=0. For backwards compatibility,
                first_row_as_headings is used in case num_heading_rows is 1.
            repeat_headings (fpdf.enums.TableHeadingsDisplay): optional, indicates whether to print table headings on every page, default to 1.
        """
        table = Table(self, *args, **kwargs)
        yield table
        table.render()

    @overload
    def output(  # type: ignore[overload-overlap]
        self,
        name: Optional[Literal[""]] = "",
        *,
        linearize: bool = False,
        output_producer_class: Type[OutputProducer] = OutputProducer,
    ) -> bytearray: ...
    @overload
    def output(
        self,
        name: str | os.PathLike[str] | BinaryIO,
        *,
        linearize: bool = False,
        output_producer_class: Type[OutputProducer] = OutputProducer,
    ) -> None: ...
    @deprecated_parameter([("dest", "2.2.0")])
    def output(
        self,
        name: Optional[str | os.PathLike[str] | BinaryIO] = "",
        *,
        linearize: bool = False,
        output_producer_class: Type[OutputProducer] = OutputProducer,
    ) -> Optional[bytearray]:
        """
        Output PDF to some destination.
        The method first calls [close](close.md) if necessary to terminate the document.
        After calling this method, content cannot be added to the document anymore.

        By default the bytearray buffer is returned.
        If a `name` is given, the PDF is written to a new file.

        Args:
            name (str): optional File object or file path where to save the PDF under
            output_producer_class (class): use a custom class for PDF file generation
        """
        # Clear cache of cached functions to free up memory after output
        get_unicode_script.cache_clear()
        # Finish document if necessary:
        if not self.buffer:
            if self.page == 0:
                self.add_page()
            # Generating final page footer:
            self._render_footer()
            # Generating .buffer based on .pages:
            if self.toc_placeholder:
                self._insert_table_of_contents()
            if self.str_alias_nb_pages:
                for page in self.pages.values():
                    for substitution_item in page.get_text_substitutions():
                        page.contents = page.contents.replace(  # type: ignore[union-attr]
                            substitution_item.get_placeholder_string().encode(
                                "latin-1"
                            ),
                            substitution_item.render_text_substitution(
                                str(self.pages_count)
                            ).encode("latin-1"),
                        )
            for _, font in self.fonts.items():
                if isinstance(font, TTFFont) and font.color_font:
                    font.color_font.load_glyphs()
            if self._compliance and self._compliance.profile == "PDFA":
                if len(self._output_intents) == 0:
                    self.add_output_intent(
                        OutputIntentSubType.PDFA,
                        output_condition_identifier="sRGB",
                        output_condition="IEC 61966-2-1:1999",
                        registry_name="http://www.color.org",
                        dest_output_profile=PDFICCProfile(
                            contents=builtin_srgb2014_bytes(),
                            n=3,
                            alternate="DeviceRGB",
                        ),
                        info="sRGB2014 (v2)",
                    )
                if (
                    self._compliance.part == 4
                    and self._compliance.conformance == "F"
                    and len(self.embedded_files) == 0
                ):
                    raise PDFAComplianceError(
                        f"{self._compliance.label} requires at least one embedded file"
                    )
            if linearize:
                output_producer_class = LinearizedOutputProducer
            output_producer = output_producer_class(self)
            self.buffer = output_producer.bufferize()
        if name:
            if isinstance(name, (str, os.PathLike)):
                Path(name).write_bytes(self.buffer)
            else:
                name.write(self.buffer)
            return None
        return self.buffer


# Pattern from sir Guido Von Rossum: https://stackoverflow.com/a/72911884/636849
# > a module can define a class with the desired functionality, and then at
# > the end, replace itself in sys.modules with an instance of that class
sys.modules[__name__].__class__ = WarnOnDeprecatedModuleAttributes


__pdoc__ = {"FPDF.add_highlight": False}  # Replaced by FPDF.highlight

__all__ = [
    "FPDF",
    "XPos",
    "YPos",
    "get_page_format",
    "ImageInfo",
    "RasterImageInfo",
    "VectorImageInfo",
    "TextMode",
    "TitleStyle",
    "PAGE_FORMATS",
]