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
|
"""
Vector drawing: managing colors, graphics states, paths, transforms...
The contents of this module are internal to fpdf2, and not part of the public API.
They may change at any time without prior warning or any deprecation period,
in non-backward-compatible ways.
Usage documentation at: <https://py-pdf.github.io/fpdf2/Drawing.html>
"""
import math
from collections import OrderedDict
from contextlib import contextmanager
from copy import deepcopy
from dataclasses import dataclass
from types import EllipsisType
from typing import (
TYPE_CHECKING,
Any,
Generator,
Iterator,
NamedTuple,
Optional,
Protocol,
Sequence,
TypeAlias,
TypeVar,
Union,
cast,
runtime_checkable,
)
from fontTools.pens.basePen import BasePen
from .drawing_primitives import (
Color,
DeviceCMYK,
DeviceGray,
DeviceRGB,
Point,
Transform,
check_range,
color_from_hex_string,
force_nodocument,
)
from .enums import (
BlendMode,
ClippingPathIntersectionRule,
CompositingOperation,
GradientSpreadMethod,
GradientUnits,
IntersectionRule,
PathPaintRule,
PDFResourceType,
PDFStyleKeys,
StrokeCapStyle,
StrokeJoinStyle,
)
from .pattern import (
Gradient,
LinearGradient,
MeshShading,
Pattern,
RadialGradient,
SweepGradient,
shape_linear_gradient,
shape_radial_gradient,
)
from .syntax import Name, PDFObject, Raw, render_pdf_primitive
from .util import FloatTolerance, Number, NumberClass, number_to_str
if TYPE_CHECKING:
from fontTools.ttLib import ttGlyphSet
from .fonts import CoreFont, TTFFont
from .output import PDFFont, PDFType3Font, ResourceCatalog
InheritType: TypeAlias = EllipsisType
class GradientPaint:
"""Fill/stroke paint using a gradient"""
__slots__ = (
"gradient",
"units",
"gradient_transform",
"apply_page_ctm",
"skip_alpha",
"spread_method",
)
def __init__(
self,
gradient: Union["Gradient", "SweepGradient"],
units: Union[GradientUnits, str] = GradientUnits.USER_SPACE_ON_USE,
gradient_transform: Optional["Transform"] = None,
apply_page_ctm: bool = True,
spread_method: Optional[Union[str, GradientSpreadMethod]] = None,
):
self.gradient = gradient
self.units = GradientUnits.coerce(units)
self.gradient_transform = gradient_transform or Transform.identity()
self.apply_page_ctm = apply_page_ctm
self.skip_alpha = False
self.spread_method = (
GradientSpreadMethod.coerce(spread_method)
if spread_method is not None
else GradientSpreadMethod.PAD
)
def _matrix_for(self, bbox: Optional["BoundingBox"]) -> "Transform":
"""Return the final /Matrix for this gradient, given an optional bbox."""
if self.units == GradientUnits.OBJECT_BOUNDING_BOX:
if bbox is None:
raise RuntimeError(
"GradientPaint requires bbox for objectBoundingBox units"
)
# Map [0,1]x[0,1] object space, then apply gradient_transform
matrix_bbox = Transform(
a=bbox.width, b=0, c=0, d=bbox.height, e=bbox.x0, f=bbox.y0
)
return self.gradient_transform @ matrix_bbox
# userSpaceOnUse: only the provided gradient_transform
return self.gradient_transform
def _register_pattern(
self,
resource_catalog: "ResourceCatalog",
gradient: Gradient | MeshShading,
matrix: "Transform",
) -> str:
"""Create a Pattern with the given matrix, register shading+pattern, return pattern name."""
resource_catalog.add(PDFResourceType.SHADING, gradient, None)
pattern = Pattern(gradient).set_matrix(matrix)
pattern.set_apply_page_ctm(self.apply_page_ctm)
resource_id = resource_catalog.add(PDFResourceType.PATTERN, pattern, None)
assert resource_id is not None
return resource_id
def emit_fill(
self, resource_catalog: "ResourceCatalog", bbox: Optional["BoundingBox"]
) -> str:
domain_bbox = (
BoundingBox(0.0, 0.0, 1.0, 1.0)
if self.units == GradientUnits.OBJECT_BOUNDING_BOX
else bbox
)
gradient = self._get_gradient_with_spread_method(domain_bbox)
matrix = self._matrix_for(bbox)
pattern_name = self._register_pattern(resource_catalog, gradient, matrix)
return f"/Pattern cs /{pattern_name} scn"
def emit_stroke(
self, resource_catalog: "ResourceCatalog", bbox: Optional["BoundingBox"]
) -> str:
domain_bbox = (
BoundingBox(0.0, 0.0, 1.0, 1.0)
if self.units == GradientUnits.OBJECT_BOUNDING_BOX
else bbox
)
gradient = self._get_gradient_with_spread_method(domain_bbox)
matrix = self._matrix_for(bbox)
pattern_name = self._register_pattern(resource_catalog, gradient, matrix)
return f"/Pattern CS /{pattern_name} SCN"
def has_alpha(self) -> bool:
return self.gradient.has_alpha() and not self.skip_alpha
def _register_alpha_pattern(
self,
resource_catalog: "ResourceCatalog",
matrix: "Transform",
bbox: "BoundingBox",
) -> str:
alpha_shading = self.gradient.get_alpha_shading_object(bbox)
if alpha_shading is None:
raise RuntimeError("Alpha gradient requested but no alpha ramp found")
# Register the shading and wrap it into a Pattern using the same matrix
resource_catalog.add(PDFResourceType.SHADING, alpha_shading, None)
alpha_pattern = Pattern(alpha_shading).set_matrix(matrix)
alpha_pattern.set_apply_page_ctm(False)
pattern_id = resource_catalog.add(PDFResourceType.PATTERN, alpha_pattern, None)
assert isinstance(pattern_id, str)
return pattern_id
def _get_gradient_with_spread_method(
self, bbox: Optional["BoundingBox"]
) -> Gradient | MeshShading:
"""
Now that the bbox is known, we can construct a new gradient stop line to apply
the spread method reflect or repeat.
"""
if isinstance(self.gradient, SweepGradient):
self.gradient.spread_method = self.spread_method
assert bbox is not None
return self.gradient.get_shading_object(bbox)
if self.spread_method == GradientSpreadMethod.PAD:
return self.gradient # nothing to do
if isinstance(self.gradient, LinearGradient):
x1, y1, x2, y2 = self.gradient.coords
raw_stops = getattr(self.gradient, "raw_stops", None)
if raw_stops is None:
colors = self.gradient.colors
bounds = self.gradient.bounds
stops = (
[(0.0, colors[0])]
+ list(zip(bounds, colors[1:-1]))
+ [(1.0, colors[-1])]
)
else:
stops = raw_stops
spread_bbox = bbox
if bbox is not None and self.units == GradientUnits.USER_SPACE_ON_USE:
try:
spread_bbox = bbox.transformed(self.gradient_transform.inverse())
except ValueError:
spread_bbox = bbox
return shape_linear_gradient(
x1,
y1,
x2,
y2,
stops,
spread_method=self.spread_method,
bbox=spread_bbox,
)
if isinstance(self.gradient, RadialGradient):
fx, fy, fr, cx, cy, r = self.gradient.coords
raw_stops = getattr(self.gradient, "raw_stops", None)
if raw_stops is None:
colors = self.gradient.colors
bounds = self.gradient.bounds
stops = (
[(0.0, colors[0])]
+ list(zip(bounds, colors[1:-1]))
+ [(1.0, colors[-1])]
)
else:
stops = raw_stops
spread_bbox = bbox
if bbox is not None and self.units == GradientUnits.USER_SPACE_ON_USE:
try:
spread_bbox = bbox.transformed(self.gradient_transform.inverse())
except ValueError:
spread_bbox = bbox
return shape_radial_gradient(
cx,
cy,
r,
stops,
fx=fx,
fy=fy,
fr=fr,
spread_method=self.spread_method,
bbox=spread_bbox,
)
return self.gradient # unknown gradient type, return as is
class _AlphaGradientPaint(GradientPaint):
def emit_fill(
self, resource_catalog: "ResourceCatalog", bbox: Optional["BoundingBox"]
) -> str:
domain_bbox = (
BoundingBox(0.0, 0.0, 1.0, 1.0)
if self.units == GradientUnits.OBJECT_BOUNDING_BOX
else bbox
)
assert domain_bbox is not None
matrix = self._matrix_for(bbox)
pattern_name = self._register_alpha_pattern(
resource_catalog, matrix, domain_bbox
)
return f"/Pattern cs /{pattern_name} scn"
def emit_stroke(
self, resource_catalog: "ResourceCatalog", bbox: Optional["BoundingBox"]
) -> str:
domain_bbox = (
BoundingBox(0.0, 0.0, 1.0, 1.0)
if self.units == GradientUnits.OBJECT_BOUNDING_BOX
else bbox
)
assert domain_bbox is not None
matrix = self._matrix_for(bbox)
pattern_name = self._register_alpha_pattern(
resource_catalog, matrix, domain_bbox
)
return f"/Pattern CS /{pattern_name} SCN"
def has_alpha(self) -> bool:
return False # already on the alpha gradient, can't alpha the alpha
class BoundingBox(NamedTuple):
"""Represents a bounding box, with utility methods for creating and manipulating them."""
x0: float
y0: float
x1: float
y1: float
@classmethod
def empty(cls) -> "BoundingBox":
"""
Return an 'empty' bounding box with extreme values that collapse on merge.
"""
return cls(float("inf"), float("inf"), float("-inf"), float("-inf"))
def is_valid(self) -> bool:
"""Return True if the bounding box is not empty."""
return self.x0 <= self.x1 and self.y0 <= self.y1
@classmethod
def from_points(cls, points: list[Point]) -> "BoundingBox":
"""Given a list of points, create a bounding box that encloses them all."""
xs = [float(p.x) for p in points]
ys = [float(p.y) for p in points]
return cls(min(xs), min(ys), max(xs), max(ys))
def merge(self, other: "BoundingBox") -> "BoundingBox":
"""Expand this bounding box to include another one."""
if not self.is_valid():
return other
if not other.is_valid():
return self
return BoundingBox(
min(self.x0, other.x0),
min(self.y0, other.y0),
max(self.x1, other.x1),
max(self.y1, other.y1),
)
def transformed(self, tf: Transform) -> "BoundingBox":
"""
Return a new bounding box resulting from applying a transform to this one.
"""
corners = [
Point(self.x0, self.y0),
Point(self.x1, self.y0),
Point(self.x0, self.y1),
Point(self.x1, self.y1),
]
transformed_points = [pt @ tf for pt in corners]
return BoundingBox.from_points(transformed_points)
def expanded(self, dx: float, dy: Optional[float] = None) -> "BoundingBox":
"""Return a new bounding box expanded by the given amounts in each direction."""
if dy is None:
dy = dx
return BoundingBox(self.x0 - dx, self.y0 - dy, self.x1 + dx, self.y1 + dy)
def expanded_to_stroke(
self, style: "GraphicsStyle", row_norms: tuple[float, float] = (1.0, 1.0)
) -> "BoundingBox":
"""Expand this bbox to include stroke coverage, given a graphics style."""
# 1) Is there any stroke to consider?
if not style.resolve_paint_rule() in (
PathPaintRule.STROKE,
PathPaintRule.STROKE_FILL_NONZERO,
PathPaintRule.STROKE_FILL_EVENODD,
):
return self
# If stroke opacity resolves to 0, no visible stroke => no expansion
if isinstance(style.stroke_opacity, NumberClass):
if float(style.stroke_opacity) <= 0.0:
return self
# 2) Effective stroke width (PDF default is 1 if unset/inherit)
w = (
1.00
if style.stroke_width is None or isinstance(style.stroke_width, InheritType)
else style.stroke_width
)
if w == 0.0:
return self
r = 0.5 * w
# 3) Row norms from CTM to scale the half-stroke in X/Y
nx, ny = row_norms
return self.expanded(r * nx, r * ny)
def to_tuple(self) -> tuple[float, float, float, float]:
"""Convert bounding box to a 4-tuple."""
return (self.x0, self.y0, self.x1, self.y1)
def to_pdf_array(self) -> str:
"""Convert bounding box to a PDF array string."""
return f"[{number_to_str(self.x0)} {number_to_str(self.y0)} {number_to_str(self.x1)} {number_to_str(self.y1)}]"
def corners(
self,
) -> tuple[
tuple[float, float],
tuple[float, float],
tuple[float, float],
tuple[float, float],
]:
"""Clockwise corners (x,y): (x0,y0),(x1,y0),(x1,y1),(x0,y1)."""
return (
(self.x0, self.y0),
(self.x1, self.y0),
(self.x1, self.y1),
(self.x0, self.y1),
)
def project_interval_on_axis(
self, x1: float, y1: float, x2: float, y2: float
) -> tuple[float, float, float]:
"""
Project bbox corners onto the axis from (x1,y1) to (x2,y2).
Returns (tmin, tmax, L) where:
- L is the axis length
- t are distances along the axis with t=0 at (x1,y1)
"""
vx, vy = (x2 - x1), (y2 - y1)
L = math.hypot(vx, vy)
if L == 0.0:
return 0.0, 0.0, 0.0
ux, uy = vx / L, vy / L
ts: list[float] = []
for X, Y in self.corners():
dx, dy = (X - x1), (Y - y1)
ts.append(dx * ux + dy * uy) # dot with unit axis
return min(ts), max(ts), L
def max_distance_to_point(self, cx: float, cy: float) -> float:
"""Max Euclidean distance from (cx,cy) to any bbox corner."""
return max(math.hypot(X - cx, Y - cy) for (X, Y) in self.corners())
@property
def width(self) -> float:
"""Return the width of the bounding box."""
return self.x1 - self.x0
@property
def height(self) -> float:
"""Return the height of the bounding box."""
return self.y1 - self.y0
def __str__(self) -> str:
return f"BoundingBox({self.x0}, {self.y0}, {self.x1}, {self.y1})"
def __eq__(self, other: object) -> bool:
if not isinstance(other, BoundingBox):
return False
return (
FloatTolerance.equal(self.x0, other.x0)
and FloatTolerance.equal(self.y0, other.y0)
and FloatTolerance.equal(self.x1, other.x1)
and FloatTolerance.equal(self.y1, other.y1)
)
def __hash__(self) -> int:
# Round to match the tolerance used in __eq__
return hash(
(
round(self.x0, 6),
round(self.y0, 6),
round(self.x1, 6),
round(self.y1, 6),
)
)
GS = TypeVar("GS", bound="GraphicsStyle")
class GraphicsStyle:
"""
A class representing various style attributes that determine drawing appearance.
This class uses the convention that the global Python singleton ellipsis (`...`) is
exclusively used to represent values that are inherited from the parent style. This
is to disambiguate the value None which is used for several values to signal an
explicitly disabled style. An example of this is the fill/stroke color styles,
which use None as hints to the auto paint style detection code.
"""
_PRIVATE_SLOTS = (
"_allow_transparency",
"_auto_close",
"_fill_color",
"_intersection_rule",
"_paint_rule",
"_stroke_color",
"_stroke_dash_pattern",
"_stroke_dash_phase",
)
__slots__ = _PRIVATE_SLOTS + tuple(
k.value
for k in PDFStyleKeys
# we do not store STROKE_DASH_PATTERN under its PDF key; it's in _stroke_dash_pattern
if k is not PDFStyleKeys.STROKE_DASH_PATTERN
)
INHERIT = ...
"""Singleton specifying a style parameter should be inherited from the parent context."""
# order is be important here because some of these properties are entangled, e.g.
# fill_color and fill_opacity
MERGE_PROPERTIES = (
"paint_rule",
"allow_transparency",
"auto_close",
"intersection_rule",
"fill_color",
"fill_opacity",
"stroke_color",
"stroke_opacity",
"blend_mode",
"stroke_width",
"stroke_cap_style",
"stroke_join_style",
"stroke_miter_limit",
"stroke_dash_pattern",
"stroke_dash_phase",
"soft_mask",
)
"""An ordered collection of properties to use when merging two GraphicsStyles."""
TRANSPARENCY_KEYS = (
PDFStyleKeys.FILL_ALPHA.value,
PDFStyleKeys.STROKE_ALPHA.value,
PDFStyleKeys.BLEND_MODE.value,
PDFStyleKeys.SOFT_MASK.value,
)
"""An ordered collection of attributes not to emit in no transparency mode."""
PDF_STYLE_KEYS = (
*(k.value for k in PDFStyleKeys if k is not PDFStyleKeys.STROKE_DASH_PATTERN),
)
"""An ordered collection of keys to directly emit when serializing the style."""
_PAINT_RULE_LOOKUP: dict[frozenset[str | IntersectionRule], PathPaintRule] = {
frozenset({}): PathPaintRule.DONT_PAINT,
frozenset({"stroke"}): PathPaintRule.STROKE,
frozenset({"fill", IntersectionRule.NONZERO}): PathPaintRule.FILL_NONZERO,
frozenset({"fill", IntersectionRule.EVENODD}): PathPaintRule.FILL_EVENODD,
frozenset(
{"stroke", "fill", IntersectionRule.NONZERO}
): PathPaintRule.STROKE_FILL_NONZERO,
frozenset(
{"stroke", "fill", IntersectionRule.EVENODD}
): PathPaintRule.STROKE_FILL_EVENODD,
}
"""A dictionary for resolving `PathPaintRule.AUTO`"""
@classmethod
def merge(cls, parent: "GraphicsStyle", child: "GraphicsStyle") -> "GraphicsStyle":
"""
Merge parent and child into a single GraphicsStyle.
The result contains the properties of the parent as overridden by any properties
explicitly set on the child. If both the parent and the child specify to
inherit a given property, that property will preserve the inherit value.
"""
new = deepcopy(child)
for prop in cls.__slots__:
cval = getattr(new, prop)
if cval is cls.INHERIT:
setattr(new, prop, getattr(parent, prop))
return new
def __init__(self) -> None:
for key in self.__slots__:
setattr(self, key, self.INHERIT)
def __deepcopy__(self: GS, memo: dict[int, Any]) -> GS:
cls = self.__class__
new = cls.__new__(cls) # bypass __init__
# copy private slots directly
for s in cls._PRIVATE_SLOTS:
object.__setattr__(new, s, getattr(self, s, cls.INHERIT))
# copy PDF-exposed slots (BM, ca, CA, etc.)
for key in cls.PDF_STYLE_KEYS:
object.__setattr__(new, key, getattr(self, key, cls.INHERIT))
return new
def __setattr__(self, name: str, value: Any) -> None:
try:
super().__setattr__(name, value)
except AttributeError as e:
raise AttributeError(
f'{self.__class__} does not have style "{name}" (a typo?)'
) from e
# at some point it probably makes sense to turn this into a general compliance
# property, but for now this is the simple approach.
@property
def allow_transparency(self) -> bool | InheritType:
allow_transparency = getattr(self, "_allow_transparency", self.INHERIT)
if allow_transparency is self.INHERIT:
return self.INHERIT
return cast(bool, allow_transparency)
@allow_transparency.setter
def allow_transparency(self, new: bool | InheritType) -> None:
return super().__setattr__("_allow_transparency", new)
# If these are used in a nested graphics context inside of a painting path
# operation, they are no-ops. However, they can be used for outer GraphicsContexts
# that painting paths inherit from.
@property
def paint_rule(self) -> PathPaintRule | InheritType | None:
"""The paint rule to use for this path/group."""
paint_rule = getattr(self, "_paint_rule", self.INHERIT)
if paint_rule is self.INHERIT or paint_rule is None:
return paint_rule
return cast(PathPaintRule, paint_rule)
@paint_rule.setter
def paint_rule(self, new: PathPaintRule | InheritType | str | None) -> None:
if new is None:
super().__setattr__("_paint_rule", PathPaintRule.DONT_PAINT)
elif isinstance(new, InheritType):
super().__setattr__("_paint_rule", new)
else:
super().__setattr__("_paint_rule", PathPaintRule.coerce(new))
@property
def auto_close(self) -> bool | InheritType:
"""If True, unclosed paths will be automatically closed before stroking."""
auto_close = getattr(self, "_auto_close", self.INHERIT)
if auto_close is self.INHERIT:
return auto_close
return cast(bool, auto_close)
@auto_close.setter
def auto_close(self, new: bool | InheritType) -> None:
if new not in {True, False, self.INHERIT}:
raise TypeError(f"auto_close must be a bool or self.INHERIT, not {new}")
super().__setattr__("_auto_close", new)
@property
def intersection_rule(self) -> IntersectionRule | InheritType:
"""The desired intersection rule for this path/group."""
intersection_rule = getattr(self, "_intersection_rule", self.INHERIT)
if intersection_rule is self.INHERIT:
return intersection_rule
return cast(IntersectionRule, intersection_rule)
@intersection_rule.setter
def intersection_rule(self, new: IntersectionRule | InheritType | str) -> None:
# don't allow None for this one.
if isinstance(new, InheritType):
super().__setattr__("_intersection_rule", new)
else:
super().__setattr__("_intersection_rule", IntersectionRule.coerce(new))
@property
def fill_color(self) -> Color | GradientPaint | InheritType | str | None:
"""
The desired fill color for this path/group.
When setting this property, if the color specifies an opacity value, that will
be used to set the fill_opacity property as well.
"""
fill_color = getattr(self, "_fill_color", self.INHERIT)
if fill_color is self.INHERIT or fill_color is None:
return fill_color
assert isinstance(
fill_color, (DeviceRGB, DeviceGray, DeviceCMYK, GradientPaint)
)
return fill_color
@fill_color.setter
def fill_color(
self, color: Color | GradientPaint | str | InheritType | None
) -> None:
if isinstance(color, str):
color = color_from_hex_string(color)
if isinstance(color, (DeviceRGB, DeviceGray, DeviceCMYK, GradientPaint)):
super().__setattr__("_fill_color", color)
if getattr(color, "a", None) is not None and not isinstance(
color, GradientPaint
):
self.fill_opacity = color.a
elif (color is None) or (color is self.INHERIT):
super().__setattr__("_fill_color", color)
else:
raise TypeError(f"{color} doesn't look like a drawing color")
@property
def fill_opacity(self) -> float | InheritType | None:
"""The desired fill opacity for this path/group."""
fill_opacity = getattr(self, PDFStyleKeys.FILL_ALPHA.value, self.INHERIT)
if fill_opacity is self.INHERIT or fill_opacity is None:
return fill_opacity
return cast(float, fill_opacity)
@fill_opacity.setter
def fill_opacity(self, new: float | InheritType | None) -> None:
if new not in {None, self.INHERIT}:
assert isinstance(new, NumberClass)
check_range(new)
super().__setattr__(PDFStyleKeys.FILL_ALPHA.value, new)
@property
def stroke_color(self) -> Color | GradientPaint | InheritType | None:
"""
The desired stroke color for this path/group.
When setting this property, if the color specifies an opacity value, that will
be used to set the fill_opacity property as well.
"""
stroke_color = getattr(self, "_stroke_color", self.INHERIT)
if stroke_color is self.INHERIT or stroke_color is None:
return stroke_color
assert isinstance(
stroke_color, (DeviceRGB, DeviceGray, DeviceCMYK, GradientPaint)
)
return stroke_color
@stroke_color.setter
def stroke_color(
self, color: Color | GradientPaint | str | InheritType | None
) -> None:
if isinstance(color, str):
color = color_from_hex_string(color)
if isinstance(color, (DeviceRGB, DeviceGray, DeviceCMYK, GradientPaint)):
super().__setattr__("_stroke_color", color)
if getattr(color, "a", None) is not None and not isinstance(
color, GradientPaint
):
self.stroke_opacity = color.a
if self.stroke_width is self.INHERIT:
self.stroke_width = 1
elif (color is None) or (color is self.INHERIT):
super().__setattr__("_stroke_color", color)
else:
raise TypeError(f"{color} doesn't look like a drawing color")
@property
def stroke_opacity(self) -> float | InheritType | None:
"""The desired stroke opacity for this path/group."""
stroke_opacity = getattr(self, PDFStyleKeys.STROKE_ALPHA.value, self.INHERIT)
if stroke_opacity is self.INHERIT or stroke_opacity is None:
return stroke_opacity
assert isinstance(stroke_opacity, NumberClass)
return float(stroke_opacity)
@stroke_opacity.setter
def stroke_opacity(self, new: float | InheritType | None) -> None:
if new not in (None, self.INHERIT):
assert isinstance(new, NumberClass)
check_range(new)
super().__setattr__(PDFStyleKeys.STROKE_ALPHA.value, new)
@property
def blend_mode(self) -> BlendMode | InheritType:
"""The desired blend mode for this path/group."""
blend_mode = getattr(self, PDFStyleKeys.BLEND_MODE.value, self.INHERIT)
if blend_mode is self.INHERIT:
return blend_mode
return cast(BlendMode, blend_mode)
@blend_mode.setter
def blend_mode(self, value: BlendMode | str | InheritType) -> None:
if isinstance(value, InheritType):
super().__setattr__(PDFStyleKeys.BLEND_MODE.value, value)
else:
super().__setattr__(
PDFStyleKeys.BLEND_MODE.value, BlendMode.coerce(value).value
)
@property
def stroke_width(self) -> float | InheritType | None:
"""The desired stroke width for this path/group."""
stroke_width = getattr(self, PDFStyleKeys.STROKE_WIDTH.value, self.INHERIT)
if stroke_width is self.INHERIT or stroke_width is None:
return stroke_width
assert isinstance(stroke_width, NumberClass)
return float(stroke_width)
@stroke_width.setter
def stroke_width(self, width: float | InheritType | None) -> None:
if width not in (None, self.INHERIT) and not isinstance(width, NumberClass):
raise TypeError(f"stroke_width must be a number, not {type(width)}")
super().__setattr__(PDFStyleKeys.STROKE_WIDTH.value, width)
@property
def stroke_cap_style(self) -> StrokeCapStyle | InheritType:
"""The desired stroke cap style for this path/group."""
stroke_cap_style = getattr(
self, PDFStyleKeys.STROKE_CAP_STYLE.value, self.INHERIT
)
if stroke_cap_style is self.INHERIT:
return stroke_cap_style
return cast(StrokeCapStyle, stroke_cap_style)
@stroke_cap_style.setter
def stroke_cap_style(self, value: StrokeCapStyle | str | InheritType) -> None:
if isinstance(value, InheritType):
super().__setattr__(PDFStyleKeys.STROKE_CAP_STYLE.value, value)
else:
super().__setattr__(
PDFStyleKeys.STROKE_CAP_STYLE.value, StrokeCapStyle.coerce(value)
)
@property
def stroke_join_style(self) -> StrokeJoinStyle | InheritType:
"""The desired stroke join style for this path/group."""
stroke_join_style = getattr(
self, PDFStyleKeys.STROKE_JOIN_STYLE.value, self.INHERIT
)
if stroke_join_style is self.INHERIT:
return stroke_join_style
return cast(StrokeJoinStyle, stroke_join_style)
@stroke_join_style.setter
def stroke_join_style(self, value: StrokeJoinStyle | str | InheritType) -> None:
if isinstance(value, InheritType):
super().__setattr__(PDFStyleKeys.STROKE_JOIN_STYLE.value, value)
else:
super().__setattr__(
PDFStyleKeys.STROKE_JOIN_STYLE.value, StrokeJoinStyle.coerce(value)
)
@property
def stroke_miter_limit(self) -> float | InheritType:
"""The desired stroke miter limit for this path/group."""
stroke_miter_limit = getattr(
self, PDFStyleKeys.STROKE_MITER_LIMIT.value, self.INHERIT
)
if stroke_miter_limit is self.INHERIT:
return stroke_miter_limit
assert isinstance(stroke_miter_limit, NumberClass)
return float(stroke_miter_limit)
@stroke_miter_limit.setter
def stroke_miter_limit(self, value: Number | InheritType) -> None:
if (value is self.INHERIT) or isinstance(value, NumberClass):
super().__setattr__(PDFStyleKeys.STROKE_MITER_LIMIT.value, value)
else:
raise TypeError(f"{value} is not a number")
@property
def stroke_dash_pattern(self) -> Optional[InheritType | tuple[float, ...]]:
"""The desired stroke dash pattern for this path/group."""
stroke_dash_pattern = getattr(self, "_stroke_dash_pattern", self.INHERIT)
if stroke_dash_pattern is self.INHERIT:
return stroke_dash_pattern
return cast(tuple[float, ...], stroke_dash_pattern)
@stroke_dash_pattern.setter
def stroke_dash_pattern(
self, value: None | InheritType | Number | Sequence[Number]
) -> None:
result: None | InheritType | Number | Sequence[Number]
if value is None:
result = ()
elif isinstance(value, InheritType):
result = self.INHERIT
elif isinstance(value, NumberClass):
result = (float(value),)
elif isinstance(value, (str, bytes, bytearray)):
raise TypeError(
f"stroke_dash_pattern {value!r} must be a number or sequence of numbers"
)
else:
try:
accum: list[float] = []
for item in value:
if isinstance(item, (str, bytes, bytearray)):
raise TypeError
accum.append(float(item))
except (TypeError, ValueError):
raise TypeError(
f"stroke_dash_pattern {value!r} must be a number or sequence of numbers"
) from None
result = (*accum,)
super().__setattr__("_stroke_dash_pattern", result)
@property
def stroke_dash_phase(self) -> InheritType | float:
"""The desired stroke dash pattern phase offset for this path/group."""
stroke_dash_phase = getattr(self, "_stroke_dash_phase", self.INHERIT)
if stroke_dash_phase is self.INHERIT:
return stroke_dash_phase
assert isinstance(stroke_dash_phase, NumberClass)
return float(stroke_dash_phase)
@stroke_dash_phase.setter
def stroke_dash_phase(self, value: InheritType | Number) -> None:
if value is self.INHERIT or isinstance(value, NumberClass):
return super().__setattr__("_stroke_dash_phase", value)
raise TypeError(f"{value} isn't a number or GraphicsStyle.INHERIT")
@property
def soft_mask(self) -> Union[InheritType, "PaintSoftMask", "ImageSoftMask"]:
paint_soft_mask = getattr(self, PDFStyleKeys.SOFT_MASK.value, self.INHERIT)
if paint_soft_mask is self.INHERIT:
return paint_soft_mask
return cast(Union[PaintSoftMask, ImageSoftMask], paint_soft_mask)
@soft_mask.setter
def soft_mask(
self, value: Union[InheritType, "PaintSoftMask", "ImageSoftMask"]
) -> None:
if value is self.INHERIT or isinstance(value, (PaintSoftMask, ImageSoftMask)):
return super().__setattr__(PDFStyleKeys.SOFT_MASK.value, value)
raise TypeError(
f"{value} isn't a PaintSoftMask, ImageSoftMask or GraphicsStyle.INHERIT"
)
def serialize(self) -> Optional[Raw]:
"""
Convert this style object to a PDF dictionary with appropriate style keys.
Only explicitly specified values are emitted.
"""
result: dict[Name, Any] = OrderedDict()
for key in self.PDF_STYLE_KEYS:
value = getattr(self, key, self.INHERIT)
if (value is not self.INHERIT) and (value is not None):
# None is used for out-of-band signaling on these, e.g. a stroke_width
# of None doesn't need to land here because it signals the
# PathPaintRule auto resolution only.
result[key] = value
# There is additional logic in GraphicsContext to ensure that this will work
if self.stroke_dash_pattern and self.stroke_dash_pattern is not self.INHERIT:
result[PDFStyleKeys.STROKE_DASH_PATTERN.value] = [
self.stroke_dash_pattern,
self.stroke_dash_phase,
]
if self.allow_transparency is False:
for key in self.TRANSPARENCY_KEYS:
if key in result:
del result[key]
if result:
# Only insert this key if there is at least one other item in the result so
# that we don't junk up the output PDF with empty ExtGState dictionaries.
type_name = Name("Type")
result[type_name] = Name("ExtGState")
result.move_to_end(type_name, last=False) # type: ignore[attr-defined]
return render_pdf_primitive(result)
# this signals to the graphics state registry that there is nothing to
# register. This is a success case.
return None
@force_nodocument
def resolve_paint_rule(self) -> PathPaintRule:
"""
Resolve `PathPaintRule.AUTO` to a real paint rule based on this style.
Returns:
the resolved `PathPaintRule`.
"""
if self.paint_rule is PathPaintRule.AUTO:
want: set[str | IntersectionRule] = set()
stroke_color = self.stroke_color
if self.stroke_width is not None and stroke_color is not None:
want.add("stroke")
fill_color = self.fill_color
if fill_color is not None:
intersection_rule = (
self.intersection_rule
if isinstance(self.intersection_rule, IntersectionRule)
else IntersectionRule.NONZERO
)
want.add("fill")
# we need to guarantee that this will not be None. The default will
# be "nonzero".
want.add(intersection_rule)
try:
paint_rule: PathPaintRule = self._PAINT_RULE_LOOKUP[frozenset(want)]
except KeyError:
# don't default to DONT_PAINT because that's almost certainly not a very
# good default.
paint_rule = PathPaintRule.STROKE_FILL_NONZERO
return paint_rule
if isinstance(self.paint_rule, InheritType) or self.paint_rule is None:
# this shouldn't happen under normal usage, but certain API (ab)use can end
# up in this state. We can't resolve anything meaningful, so fall back to a
# sane(?) default.
return PathPaintRule.STROKE_FILL_NONZERO
return self.paint_rule
@runtime_checkable
class Renderable(Protocol):
"""
Structural type for things that can render themselves into PDF operators
and report a geometric bounding box.
"""
def render(
self,
resource_registry: "ResourceCatalog",
style: GraphicsStyle,
last_item: "Renderable",
initial_point: Point,
) -> tuple[str, "Renderable", Point]: ...
def bounding_box(self, start: Point) -> tuple[BoundingBox, Point]: ...
@property
def end_point(self) -> Point: ...
def _render_move(pt: Point) -> str:
return f"{pt.render()} m"
def _render_line(pt: Point) -> str:
return f"{pt.render()} l"
def _render_curve(ctrl1: Point, ctrl2: Point, end: Point) -> str:
return f"{ctrl1.render()} {ctrl2.render()} {end.render()} c"
class Move(NamedTuple):
"""
A path move element.
If a path has been created but not yet painted, this will create a new subpath.
See: `PaintedPath.move_to`
"""
pt: Point
"""The point to which to move."""
@property
def end_point(self) -> Point:
"""The end point of this path element."""
return self.pt
# pylint: disable=unused-argument
def bounding_box(self, start: Point) -> tuple[BoundingBox, Point]:
bbox = BoundingBox.empty()
return bbox, self.pt
@force_nodocument
def render(
self,
resource_registry: "ResourceCatalog",
style: GraphicsStyle,
last_item: Renderable,
initial_point: Point,
) -> tuple[str, Renderable, Point]:
"""
Render this path element to its PDF representation.
Args:
resource_registry (ResourceCatalog): the owner's graphics state
dictionary registry.
style (GraphicsStyle): the current resolved graphics style
last_item: the previous path element.
initial_point: last position set by a "M" or "m" command
Returns:
a tuple of `(str, new_last_item)`, where `new_last_item` is `self`
"""
return _render_move(self.pt), self, self.pt
class RelativeMove(NamedTuple):
"""
A path move element with an end point relative to the end of the previous path
element.
If a path has been created but not yet painted, this will create a new subpath.
See: `PaintedPath.move_relative`
"""
pt: Point
"""The offset by which to move."""
@property
def end_point(self) -> Point:
raise NotImplementedError
def bounding_box(self, start: Point) -> tuple[BoundingBox, Point]:
"""RelativeMove doesn't draw anything, so it has no bounding box."""
return BoundingBox.empty(), start + self.pt
@force_nodocument
def render(
self,
resource_registry: "ResourceCatalog",
style: GraphicsStyle,
last_item: Renderable,
initial_point: Point,
) -> tuple[str, Renderable, Point]:
"""
Render this path element to its PDF representation.
Args:
resource_registry (ResourceCatalog): the owner's graphics state
dictionary registry.
style (GraphicsStyle): the current resolved graphics style
last_item: the previous path element.
initial_point: last position set by a "M" or "m" command
Returns:
a tuple of `(str, new_last_item)`, where `new_last_item` is the resolved
`Move`
"""
# pylint: disable=unused-argument
point = last_item.end_point + self.pt
return _render_move(point), Move(point), point
class Line(NamedTuple):
"""
A path line element.
This draws a straight line from the end point of the previous path element to the
point specified by `pt`.
See: `PaintedPath.line_to`
"""
pt: Point
"""The point to which the line is drawn."""
@property
def end_point(self) -> Point:
"""The end point of this path element."""
return self.pt
def bounding_box(self, start: Point) -> tuple[BoundingBox, Point]:
"""Compute the bounding box of a line from the start point to the end point."""
return BoundingBox.from_points([start, self.pt]), self.pt
@force_nodocument
def render(
self,
resource_registry: "ResourceCatalog",
style: GraphicsStyle,
last_item: Renderable,
initial_point: Point,
) -> tuple[str, Renderable, Point]:
"""
Render this path element to its PDF representation.
Args:
resource_registry (ResourceCatalog): the owner's graphics state
dictionary registry.
style (GraphicsStyle): the current resolved graphics style
last_item: the previous path element.
initial_point: last position set by a "M" or "m" command
Returns:
a tuple of `(str, new_last_item)`, where `new_last_item` is `self`
"""
# pylint: disable=unused-argument
return _render_line(self.pt), self, initial_point
class RelativeLine(NamedTuple):
"""
A path line element with an endpoint relative to the end of the previous element.
This draws a straight line from the end point of the previous path element to the
point specified by `last_item.end_point + pt`. The absolute coordinates of the end
point are resolved during the rendering process.
See: `PaintedPath.line_relative`
"""
pt: Point
"""The endpoint of the line relative to the previous path element."""
@property
def end_point(self) -> Point:
raise NotImplementedError
def bounding_box(self, start: Point) -> tuple[BoundingBox, Point]:
"""Compute the bounding box of a relative line from the start point to the new end point."""
return BoundingBox.from_points([start, start + self.pt]), start + self.pt
@force_nodocument
def render(
self,
resource_registry: "ResourceCatalog",
style: GraphicsStyle,
last_item: Renderable,
initial_point: Point,
) -> tuple[str, Renderable, Point]:
"""
Render this path element to its PDF representation.
Args:
resource_registry (ResourceCatalog): the owner's graphics state
dictionary registry.
style (GraphicsStyle): the current resolved graphics style
last_item: the previous path element.
initial_point: last position set by a "M" or "m" command
Returns:
a tuple of `(str, new_last_item)`, where `new_last_item` is the resolved
`Line`.
"""
# pylint: disable=unused-argument
point = last_item.end_point + self.pt
return _render_line(point), Line(point), initial_point
class HorizontalLine(NamedTuple):
"""
A path line element that takes its ordinate from the end of the previous element.
See: `PaintedPath.horizontal_line_to`
"""
x: Number
"""The abscissa of the horizontal line's end point."""
@property
def end_point(self) -> Point:
raise NotImplementedError
def bounding_box(self, start: Point) -> tuple[BoundingBox, Point]:
"""Compute the bounding box of a horizontal line from the start point to the new x."""
end = Point(float(self.x), start.y)
return BoundingBox.from_points([start, end]), end
@force_nodocument
def render(
self,
resource_registry: "ResourceCatalog",
style: GraphicsStyle,
last_item: Renderable,
initial_point: Point,
) -> tuple[str, Renderable, Point]:
"""
Render this path element to its PDF representation.
Args:
resource_registry (ResourceCatalog): the owner's graphics state
dictionary registry.
style (GraphicsStyle): the current resolved graphics style
last_item: the previous path element.
initial_point: last position set by a "M" or "m" command
Returns:
a tuple of `(str, new_last_item)`, where `new_last_item` is the resolved
`Line`.
"""
# pylint: disable=unused-argument
end_point = Point(x=float(self.x), y=float(last_item.end_point.y))
return _render_line(end_point), Line(end_point), initial_point
class RelativeHorizontalLine(NamedTuple):
"""
A path line element that takes its ordinate from the end of the previous element and
computes its abscissa offset from the end of that element.
See: `PaintedPath.horizontal_line_relative`
"""
x: Number
"""
The abscissa of the horizontal line's end point relative to the abscissa of the
previous path element.
"""
@property
def end_point(self) -> Point:
raise NotImplementedError
def bounding_box(self, start: Point) -> tuple[BoundingBox, Point]:
"""Compute the bounding box of a relative horizontal line."""
end = Point(float(start.x) + float(self.x), start.y)
bbox = BoundingBox.from_points([start, end])
return bbox, end
@force_nodocument
def render(
self,
resource_registry: "ResourceCatalog",
style: GraphicsStyle,
last_item: Renderable,
initial_point: Point,
) -> tuple[str, Renderable, Point]:
"""
Render this path element to its PDF representation.
Args:
resource_registry (ResourceCatalog): the owner's graphics state
dictionary registry.
style (GraphicsStyle): the current resolved graphics style
last_item: the previous path element.
initial_point: last position set by a "M" or "m" command
Returns:
a tuple of `(str, new_last_item)`, where `new_last_item` is the resolved
`Line`.
"""
# pylint: disable=unused-argument
end_point = Point(
x=last_item.end_point.x + float(self.x), y=last_item.end_point.y
)
return _render_line(end_point), Line(end_point), initial_point
class VerticalLine(NamedTuple):
"""
A path line element that takes its abscissa from the end of the previous element.
See: `PaintedPath.vertical_line_to`
"""
y: Number
"""The ordinate of the vertical line's end point."""
@property
def end_point(self) -> Point:
raise NotImplementedError
def bounding_box(self, start: Point) -> tuple[BoundingBox, Point]:
"""Compute the bounding box of this vertical line."""
end = Point(start.x, float(self.y))
bbox = BoundingBox.from_points([start, end])
return bbox, end
@force_nodocument
def render(
self,
resource_registry: "ResourceCatalog",
style: GraphicsStyle,
last_item: Renderable,
initial_point: Point,
) -> tuple[str, Renderable, Point]:
"""
Render this path element to its PDF representation.
Args:
resource_registry (ResourceCatalog): the owner's graphics state
dictionary registry.
style (GraphicsStyle): the current resolved graphics style
last_item: the previous path element.
initial_point: last position set by a "M" or "m" command
Returns:
a tuple of `(str, new_last_item)`, where `new_last_item` is the resolved
`Line`.
"""
# pylint: disable=unused-argument
end_point = Point(x=last_item.end_point.x, y=float(self.y))
return _render_line(end_point), Line(end_point), initial_point
class RelativeVerticalLine(NamedTuple):
"""
A path line element that takes its abscissa from the end of the previous element and
computes its ordinate offset from the end of that element.
See: `PaintedPath.vertical_line_relative`
"""
y: Number
"""
The ordinate of the vertical line's end point relative to the ordinate of the
previous path element.
"""
@property
def end_point(self) -> Point:
raise NotImplementedError
def bounding_box(self, start: Point) -> tuple[BoundingBox, Point]:
"""Compute the bounding box of this relative vertical line."""
end = Point(start.x, float(start.y) + float(self.y))
bbox = BoundingBox.from_points([start, end])
return bbox, end
@force_nodocument
def render(
self,
resource_registry: "ResourceCatalog",
style: GraphicsStyle,
last_item: Renderable,
initial_point: Point,
) -> tuple[str, Renderable, Point]:
"""
Render this path element to its PDF representation.
Args:
resource_registry (ResourceCatalog): the owner's graphics state
dictionary registry.
style (GraphicsStyle): the current resolved graphics style
last_item: the previous path element.
initial_point: last position set by a "M" or "m" command
Returns:
a tuple of `(str, new_last_item)`, where `new_last_item` is the resolved
`Line`.
"""
# pylint: disable=unused-argument
end_point = Point(
x=last_item.end_point.x, y=last_item.end_point.y + float(self.y)
)
return _render_line(end_point), Line(end_point), initial_point
def _eval_cubic_bezier_1d(
t: float, p0: float, p1: float, p2: float, p3: float
) -> float:
"""Cubic Bézier scalar evaluation at t ∈ [0,1]."""
u = 1 - t
return (
(u * u * u) * p0
+ 3 * (u * u) * t * p1
+ 3 * u * (t * t) * p2
+ (t * t * t) * p3
)
def _cubic_bezier_critical_ts_1d(
p0: float, p1: float, p2: float, p3: float, eps: float = 1e-12
) -> list[float]:
"""t ∈ (0,1) where d/dt of the cubic Bézier equals 0 (possible extrema)."""
a = -3 * p0 + 9 * p1 - 9 * p2 + 3 * p3
b = 6 * p0 - 12 * p1 + 6 * p2
c = -3 * p0 + 3 * p1
ts: list[float] = []
if abs(a) < eps:
if abs(b) > eps:
t = -c / b
if 0 < t < 1:
ts.append(t)
else:
disc = b * b - 4 * a * c
if disc >= 0:
r = disc**0.5
for t in ((-b + r) / (2 * a), (-b - r) / (2 * a)):
if 0 < t < 1:
ts.append(t)
return ts
class BezierCurve(NamedTuple):
"""
A cubic Bézier curve path element.
This draws a Bézier curve parameterized by the end point of the previous path
element, two off-curve control points, and an end point.
See: `PaintedPath.curve_to`
"""
c1: Point
"""The curve's first control point."""
c2: Point
"""The curve's second control point."""
end: Point
"""The curve's end point."""
@property
def end_point(self) -> Point:
"""The end point of this path element."""
return self.end
def bounding_box(self, start: Point) -> tuple[BoundingBox, Point]:
"""Compute the bounding box of this cubic Bézier curve."""
# Evaluate all candidate t values (endpoints + extrema) for both axes
px = [start.x, self.c1.x, self.c2.x, self.end.x]
py = [start.y, self.c1.y, self.c2.y, self.end.y]
tx = [0, 1] + _cubic_bezier_critical_ts_1d(*px)
ty = [0, 1] + _cubic_bezier_critical_ts_1d(*py)
xs = [_eval_cubic_bezier_1d(t, *px) for t in tx]
ys = [_eval_cubic_bezier_1d(t, *py) for t in ty]
bbox = BoundingBox(min(xs), min(ys), max(xs), max(ys))
return bbox, self.end
@force_nodocument
def render(
self,
resource_registry: "ResourceCatalog",
style: GraphicsStyle,
last_item: Renderable,
initial_point: Point,
) -> tuple[str, Renderable, Point]:
"""
Render this path element to its PDF representation.
Args:
resource_registry (ResourceCatalog): the owner's graphics state
dictionary registry.
style (GraphicsStyle): the current resolved graphics style
last_item: the previous path element.
initial_point: last position set by a "M" or "m" command
Returns:
a tuple of `(str, new_last_item)`, where `new_last_item` is `self`
"""
# pylint: disable=unused-argument
return _render_curve(self.c1, self.c2, self.end), self, initial_point
class RelativeBezierCurve(NamedTuple):
"""
A cubic Bézier curve path element whose points are specified relative to the end
point of the previous path element.
See: `PaintedPath.curve_relative`
"""
c1: Point
"""
The curve's first control point relative to the end of the previous path element.
"""
c2: Point
"""
The curve's second control point relative to the end of the previous path element.
"""
end: Point
"""The curve's end point relative to the end of the previous path element."""
@property
def end_point(self) -> Point:
raise NotImplementedError
def bounding_box(self, start: Point) -> tuple[BoundingBox, Point]:
"""
Compute the bounding box of this relative cubic Bézier curve.
Args:
start (Point): The starting point of the curve (i.e., the end of the previous path element).
Returns:
A tuple containing:
- BoundingBox: the axis-aligned bounding box containing the entire curve.
- Point: the end point of the curve.
"""
# Resolve absolute coordinates
p0 = start
p1 = start + self.c1
p2 = start + self.c2
p3 = start + self.end
tx = [0, 1] + _cubic_bezier_critical_ts_1d(p0.x, p1.x, p2.x, p3.x)
ty = [0, 1] + _cubic_bezier_critical_ts_1d(p0.y, p1.y, p2.y, p3.y)
xs = [
_eval_cubic_bezier_1d(t, float(p0.x), float(p1.x), float(p2.x), float(p3.x))
for t in tx
]
ys = [
_eval_cubic_bezier_1d(t, float(p0.y), float(p1.y), float(p2.y), float(p3.y))
for t in ty
]
bbox = BoundingBox(min(xs), min(ys), max(xs), max(ys))
return bbox, p3
@force_nodocument
def render(
self,
resource_registry: "ResourceCatalog",
style: GraphicsStyle,
last_item: Renderable,
initial_point: Point,
) -> tuple[str, Renderable, Point]:
"""
Render this path element to its PDF representation.
Args:
resource_registry (ResourceCatalog): the owner's graphics state
dictionary registry.
style (GraphicsStyle): the current resolved graphics style
last_item: the previous path element.
initial_point: last position set by a "M" or "m" command
Returns:
a tuple of `(str, new_last_item)`, where `new_last_item` is the resolved
`BezierCurve`.
"""
# pylint: disable=unused-argument
last_point = last_item.end_point
c1 = last_point + self.c1
c2 = last_point + self.c2
end = last_point + self.end
return (
_render_curve(c1, c2, end),
BezierCurve(c1=c1, c2=c2, end=end),
initial_point,
)
class QuadraticBezierCurve(NamedTuple):
"""
A quadratic Bézier curve path element.
This draws a Bézier curve parameterized by the end point of the previous path
element, one off-curve control point, and an end point.
See: `PaintedPath.quadratic_curve_to`
"""
ctrl: Point
"""The curve's control point."""
end: Point
"""The curve's end point."""
@property
def end_point(self) -> Point:
"""The end point of this path element."""
return self.end
def to_cubic_curve(self, start_point: Point) -> BezierCurve:
ctrl = self.ctrl
end = self.end
ctrl1 = Point(
x=start_point.x + 2 * (ctrl.x - start_point.x) / 3,
y=start_point.y + 2 * (ctrl.y - start_point.y) / 3,
)
ctrl2 = Point(
x=end.x + 2 * (ctrl.x - end.x) / 3,
y=end.y + 2 * (ctrl.y - end.y) / 3,
)
return BezierCurve(ctrl1, ctrl2, end)
def bounding_box(self, start: Point) -> tuple[BoundingBox, Point]:
"""Compute the bounding box of this quadratic Bézier curve by converting it to a cubic Bézier."""
cubic = self.to_cubic_curve(start)
return cubic.bounding_box(start)
@force_nodocument
def render(
self,
resource_registry: "ResourceCatalog",
style: GraphicsStyle,
last_item: Renderable,
initial_point: Point,
) -> tuple[str, Renderable, Point]:
"""
Render this path element to its PDF representation.
Args:
resource_registry (ResourceCatalog): the owner's graphics state
dictionary registry.
style (GraphicsStyle): the current resolved graphics style
last_item: the previous path element.
initial_point: last position set by a "M" or "m" command
Returns:
a tuple of `(str, new_last_item)`, where `new_last_item` is `self`.
"""
return (
self.to_cubic_curve(last_item.end_point).render(
resource_registry, style, last_item, initial_point
)[0],
self,
initial_point,
)
class RelativeQuadraticBezierCurve(NamedTuple):
"""
A quadratic Bézier curve path element whose points are specified relative to the end
point of the previous path element.
See: `PaintedPath.quadratic_curve_relative`
"""
ctrl: Point
"""The curve's control point relative to the end of the previous path element."""
end: Point
"""The curve's end point relative to the end of the previous path element."""
@property
def end_point(self) -> Point:
raise NotImplementedError
def bounding_box(self, start: Point) -> tuple[BoundingBox, Point]:
"""Compute the bounding box of this relative quadratic Bézier curve."""
ctrl = start + self.ctrl
end = start + self.end
return QuadraticBezierCurve(ctrl=ctrl, end=end).bounding_box(start)
@force_nodocument
def render(
self,
resource_registry: "ResourceCatalog",
style: GraphicsStyle,
last_item: Renderable,
initial_point: Point,
) -> tuple[str, Renderable, Point]:
"""
Render this path element to its PDF representation.
Args:
resource_registry (ResourceCatalog): the owner's graphics state
dictionary registry.
style (GraphicsStyle): the current resolved graphics style
last_item: the previous path element.
initial_point: last position set by a "M" or "m" command
Returns:
a tuple of `(str, new_last_item)`, where `new_last_item` is the resolved
`QuadraticBezierCurve`.
"""
last_point = last_item.end_point
ctrl = last_point + self.ctrl
end = last_point + self.end
absolute = QuadraticBezierCurve(ctrl=ctrl, end=end)
return absolute.render(resource_registry, style, last_item, initial_point)
class Arc(NamedTuple):
"""
An elliptical arc path element.
The arc is drawn from the end of the current path element to its specified end point
using a number of parameters to determine how it is constructed.
See: `PaintedPath.arc_to`
"""
radii: Point
"""
The x- and y-radii of the arc. If `radii.x == radii.y` the arc will be circular.
"""
rotation: Number
"""The rotation of the arc's major/minor axes relative to the coordinate frame."""
large: bool
"""If True, sweep the arc over an angle greater than or equal to 180 degrees."""
sweep: bool
"""If True, the arc is swept in the positive angular direction."""
end: Point
"""The end point of the arc."""
@property
def end_point(self) -> Point:
"""The end point of this path element."""
return self.end
@staticmethod
@force_nodocument
def subdivide_sweep(
sweep_angle: float,
) -> Generator[tuple[Point, Point, Point], None, None]:
"""
A generator that subdivides a swept angle into segments no larger than a quarter
turn.
Any sweep that is larger than a quarter turn is subdivided into as many equally
sized segments as necessary to prevent any individual segment from being larger
than a quarter turn.
This is used for approximating a circular curve segment using cubic Bézier
curves. This computes the parameters used for the Bézier approximation up
front, as well as the transform necessary to place the segment in the correct
position.
Args:
sweep_angle (float): the angle to subdivide.
Yields:
A tuple of (ctrl1, ctrl2, end) representing the control and end points of
the cubic Bézier curve approximating the segment as a unit circle centered
at the origin.
"""
sweep_angle = abs(sweep_angle)
sweep_left = sweep_angle
quarterturn = math.pi / 2
chunks = math.ceil(sweep_angle / quarterturn)
sweep_segment = sweep_angle / chunks
cos_t = math.cos(sweep_segment)
sin_t = math.sin(sweep_segment)
kappa = 4 / 3 * math.tan(sweep_segment / 4)
ctrl1 = Point(1, kappa)
ctrl2 = Point(cos_t + kappa * sin_t, sin_t - kappa * cos_t)
end = Point(cos_t, sin_t)
for _ in range(chunks):
offset = sweep_angle - sweep_left
transform = Transform.rotation(offset)
yield ctrl1 @ transform, ctrl2 @ transform, end @ transform
sweep_left -= sweep_segment
def _approximate_arc(self, last_item: Renderable) -> list[BezierCurve]:
"""
Approximate this arc with a sequence of `BezierCurve`.
Args:
last_item: the previous path element (used for its end point)
Returns:
a list of `BezierCurve`.
"""
radii = self.radii
reverse = Transform.rotation(-self.rotation)
forward = Transform.rotation(self.rotation)
prime = ((last_item.end_point - self.end) * 0.5) @ reverse
lam_da = (prime.x / radii.x) ** 2 + (prime.y / radii.y) ** 2
if lam_da > 1:
radii = Point(x=(lam_da**0.5) * radii.x, y=(lam_da**0.5) * radii.y)
sign = (self.large != self.sweep) - (self.large == self.sweep)
rxry2 = (radii.x * radii.y) ** 2
rxpy2 = (radii.x * prime.y) ** 2
rypx2 = (radii.y * prime.x) ** 2
centerprime = (
sign
* math.sqrt(round(rxry2 - rxpy2 - rypx2, 8) / (rxpy2 + rypx2))
* Point(
x=radii.x * prime.y / radii.y,
y=-radii.y * prime.x / radii.x,
)
)
center = (centerprime @ forward) + ((last_item.end_point + self.end) * 0.5)
arcstart = Point(
x=(prime.x - centerprime.x) / radii.x,
y=(prime.y - centerprime.y) / radii.y,
)
arcend = Point(
x=(-prime.x - centerprime.x) / radii.x,
y=(-prime.y - centerprime.y) / radii.y,
)
theta = Point(1, 0).angle(arcstart)
deltatheta = arcstart.angle(arcend)
if (self.sweep is False) and (deltatheta > 0):
deltatheta -= math.tau
elif (self.sweep is True) and (deltatheta < 0):
deltatheta += math.tau
sweep_sign = (deltatheta >= 0) - (deltatheta < 0)
final_tf = (
Transform.scaling(x=1, y=sweep_sign) # flip negative sweeps
.rotate(theta) # rotate start of arc to correct position
.scale(radii.x, radii.y) # scale unit circle into the final ellipse shape
.rotate(self.rotation) # rotate the ellipse the specified angle
.translate(center.x, center.y) # translate to the final coordinates
)
curves: list[BezierCurve] = []
for ctrl1, ctrl2, end in self.subdivide_sweep(deltatheta):
curves.append(
BezierCurve(ctrl1 @ final_tf, ctrl2 @ final_tf, end @ final_tf)
)
return curves
def bounding_box(self, start: Point) -> tuple[BoundingBox, Point]:
"""
Compute the bounding box of this arc by approximating it with a series of
Bezier curves and aggregating their bounding boxes.
"""
bbox = BoundingBox.empty()
prev: Renderable = Move(start)
for curve in self._approximate_arc(prev):
segment_bbox, _ = curve.bounding_box(prev.end_point)
bbox = bbox.merge(segment_bbox)
prev = curve
return bbox, self.end
@force_nodocument
def render(
self,
resource_registry: "ResourceCatalog",
style: GraphicsStyle,
last_item: Renderable,
initial_point: Point,
) -> tuple[str, Renderable, Point]:
"""
Render this path element to its PDF representation.
Args:
resource_registry (ResourceCatalog): the owner's graphics state
dictionary registry.
style (GraphicsStyle): the current resolved graphics style
last_item: the previous path element.
initial_point: last position set by a "M" or "m" command
Returns:
a tuple of `(str, new_last_item)`, where `new_last_item` is a resolved
`BezierCurve`.
"""
curves = self._approximate_arc(last_item)
if not curves:
return "", last_item, initial_point
return (
" ".join(
curve.render(resource_registry, style, prev, initial_point)[0]
for prev, curve in zip([last_item, *curves[:-1]], curves)
),
curves[-1],
initial_point,
)
class RelativeArc(NamedTuple):
"""
An elliptical arc path element.
The arc is drawn from the end of the current path element to its specified end point
using a number of parameters to determine how it is constructed.
See: `PaintedPath.arc_relative`
"""
radii: Point
"""
The x- and y-radii of the arc. If `radii.x == radii.y` the arc will be circular.
"""
rotation: Number
"""The rotation of the arc's major/minor axes relative to the coordinate frame."""
large: bool
"""If True, sweep the arc over an angle greater than or equal to 180 degrees."""
sweep: bool
"""If True, the arc is swept in the positive angular direction."""
end: Point
"""The end point of the arc relative to the end of the previous path element."""
@property
def end_point(self) -> Point:
raise NotImplementedError
def bounding_box(self, start: Point) -> tuple[BoundingBox, Point]:
"""Compute the bounding box of the resolved arc from the given start point."""
end_point = start + self.end
arc = Arc(
radii=self.radii,
rotation=self.rotation,
large=self.large,
sweep=self.sweep,
end=end_point,
)
return arc.bounding_box(start)
@force_nodocument
def render(
self,
resource_registry: "ResourceCatalog",
style: GraphicsStyle,
last_item: Renderable,
initial_point: Point,
) -> tuple[str, Renderable, Point]:
"""
Render this path element to its PDF representation.
Args:
resource_registry (ResourceCatalog): the owner's graphics state
dictionary registry.
style (GraphicsStyle): the current resolved graphics style
last_item: the previous path element.
initial_point: last position set by a "M" or "m" command
Returns:
a tuple of `(str, new_last_item)`, where `new_last_item` is a resolved
`BezierCurve`.
"""
return Arc(
self.radii,
self.rotation,
self.large,
self.sweep,
last_item.end_point + self.end,
).render(resource_registry, style, last_item, initial_point)
class Rectangle(NamedTuple):
"""A pdf primitive rectangle."""
org: Point
"""The top-left corner of the rectangle."""
size: Point
"""The width and height of the rectangle."""
@property
def end_point(self) -> Point:
"""The end point of a rectangle is the origin."""
return self.org
# pylint: disable=unused-argument
def bounding_box(self, start: Point) -> tuple[BoundingBox, Point]:
"""Compute the bounding box of this rectangle."""
x0, y0 = self.org.x, self.org.y
x1 = float(x0) + float(self.size.x)
y1 = float(y0) + float(self.size.y)
bbox = BoundingBox.from_points(
[
Point(x0, y0),
Point(x1, y0),
Point(x0, y1),
Point(x1, y1),
]
)
return bbox, self.org
@force_nodocument
def render(
self,
resource_registry: "ResourceCatalog",
style: GraphicsStyle,
last_item: Renderable,
initial_point: Point,
) -> tuple[str, Renderable, Point]:
"""
Render this path element to its PDF representation.
Args:
resource_registry (ResourceCatalog): the owner's graphics state
dictionary registry.
style (GraphicsStyle): the current resolved graphics style
last_item: the previous path element.
initial_point: last position set by a "M" or "m" command
Returns:
a tuple of `(str, new_last_item)`, where `new_last_item` is a `Line` back to
the rectangle's origin.
"""
return (
f"{self.org.render()} {self.size.render()} re",
Line(self.org),
initial_point,
)
class RoundedRectangle(NamedTuple):
"""
A rectangle with rounded corners.
See: `PaintedPath.rectangle`
"""
org: Point
"""The top-left corner of the rectangle."""
size: Point
"""The width and height of the rectangle."""
corner_radii: Point
"""The x- and y-radius of the corners."""
@property
def end_point(self) -> Point:
return self.org
def _decompose(self) -> list[Renderable]:
items: list[Renderable] = []
if (self.size.x == 0) and (self.size.y == 0):
pass
elif (self.size.x == 0) or (self.size.y == 0):
items.append(Move(self.org))
items.append(Line(self.org + self.size))
items.append(Close())
elif (self.corner_radii.x == 0) or (self.corner_radii.y == 0):
items.append(Rectangle(self.org, self.size))
else:
x, y = self.org
w, h = self.size
rx, ry = self.corner_radii
sign_width = (self.size.x >= 0) - (self.size.x < 0)
sign_height = (self.size.y >= 0) - (self.size.y < 0)
if abs(rx) > abs(w):
rx = self.size.x
if abs(ry) > abs(h):
ry = self.size.y
rx = sign_width * abs(rx)
ry = sign_height * abs(ry)
arc_rad = Point(rx, ry)
items.append(Move(Point(x + rx, y)))
items.append(Line(Point(x + w - rx, y)))
items.append(Arc(arc_rad, 0, False, True, Point(x + w, y + ry)))
items.append(Line(Point(x + w, y + h - ry)))
items.append(Arc(arc_rad, 0, False, True, Point(x + w - rx, y + h)))
items.append(Line(Point(x + rx, y + h)))
items.append(Arc(arc_rad, 0, False, True, Point(x, y + h - ry)))
items.append(Line(Point(x, y + ry)))
items.append(Arc(arc_rad, 0, False, True, Point(x + rx, y)))
items.append(Close())
return items
def bounding_box(self, start: Point) -> tuple[BoundingBox, Point]:
"""
Compute the bounding box of this rounded rectangle by decomposing into primitives
and merging their individual bounding boxes.
"""
bbox = BoundingBox.empty()
current_point = start
for item in self._decompose():
b, current_point = item.bounding_box(current_point)
bbox = bbox.merge(b)
return bbox, self.org
@force_nodocument
def render(
self,
resource_registry: "ResourceCatalog",
style: GraphicsStyle,
last_item: Renderable,
initial_point: Point,
) -> tuple[str, Renderable, Point]:
"""
Render this path element to its PDF representation.
Args:
resource_registry (ResourceCatalog): the owner's graphics state
dictionary registry.
style (GraphicsStyle): the current resolved graphics style
last_item: the previous path element.
initial_point: last position set by a "M" or "m" command
Returns:
a tuple of `(str, new_last_item)`, where `new_last_item` is a resolved
`Line`.
"""
components = self._decompose()
if not components:
return "", last_item, initial_point
render_list: list[str] = []
for item in components:
rendered, last_item, initial_point = item.render(
resource_registry, style, last_item, initial_point
)
render_list.append(rendered)
return " ".join(render_list), Line(self.org), initial_point
class Ellipse(NamedTuple):
"""
An ellipse.
See: `PaintedPath.ellipse`
"""
radii: Point
"""The x- and y-radii of the ellipse"""
center: Point
"""The abscissa and ordinate of the center of the ellipse"""
@property
def end_point(self) -> Point:
raise NotImplementedError
def _decompose(self) -> list[Renderable]:
items: list[Renderable] = []
rx = abs(self.radii.x)
ry = abs(self.radii.y)
cx, cy = self.center
arc_rad = Point(rx, ry)
# this isn't the most efficient way to do this, computationally, but it's
# internally consistent.
if (rx != 0) and (ry != 0):
items.append(Move(Point(cx + rx, cy)))
items.append(Arc(arc_rad, 0, False, True, Point(cx, cy + ry)))
items.append(Arc(arc_rad, 0, False, True, Point(cx - rx, cy)))
items.append(Arc(arc_rad, 0, False, True, Point(cx, cy - ry)))
items.append(Arc(arc_rad, 0, False, True, Point(cx + rx, cy)))
items.append(Close())
return items
def bounding_box(self, start: Point) -> tuple[BoundingBox, Point]:
"""
Compute the bounding box of this ellipse by decomposing it and merging the bounding boxes
of its components.
"""
bbox = BoundingBox.empty()
current_point = start
for item in self._decompose():
b, current_point = item.bounding_box(current_point)
bbox = bbox.merge(b)
return bbox, self.center
@force_nodocument
def render(
self,
resource_registry: "ResourceCatalog",
style: GraphicsStyle,
last_item: Renderable,
initial_point: Point,
) -> tuple[str, Renderable, Point]:
"""
Render this path element to its PDF representation.
Args:
resource_registry (ResourceCatalog): the owner's graphics state
dictionary registry.
style (GraphicsStyle): the current resolved graphics style
last_item: the previous path element.
initial_point: last position set by a "M" or "m" command
Returns:
a tuple of `(str, new_last_item)`, where `new_last_item` is a resolved
`Move` to the center of the ellipse.
"""
components = self._decompose()
if not components:
return "", last_item, initial_point
render_list: list[str] = []
for item in components:
rendered, last_item, initial_point = item.render(
resource_registry, style, last_item, initial_point
)
render_list.append(rendered)
return " ".join(render_list), Move(self.center), initial_point
class TextRun(NamedTuple):
text: str
family: str
emphasis: str
size: float
dx: float = 0.0
dy: float = 0.0
abs_x: Optional[float] = None
abs_y: Optional[float] = None
transform: Optional[Transform] = None
run_style: Optional[GraphicsStyle] = None
class Text(NamedTuple):
"""
SVG-like text renderable.
Stores the anchor position (x, y) and one or more TextRuns that include
relative positioning offsets. Accurate glyph positioning is resolved
during rendering once font metrics are available.
"""
x: float
y: float
text_runs: tuple[TextRun, ...]
text_anchor: str = "start" # "start" | "middle" | "end"
@property
def end_point(self) -> Point:
raise NotImplementedError
def _approximate_layout(self) -> tuple[list[tuple[float, float, float]], float]:
"""
Produce an approximate layout for bounding-box estimation.
Returns:
A tuple of (per-run layout list, total width estimate). Each layout
entry is (x, y, width) in user space.
"""
positions: list[tuple[float, float, float]] = []
pen_x = self.x
pen_y = self.y
max_right = pen_x
min_left = pen_x
for run in self.text_runs:
if run.abs_x is not None:
pen_x = run.abs_x
if run.abs_y is not None:
pen_y = run.abs_y
pen_x += run.dx
pen_y += run.dy
# Fallback width estimation: ~0.5em per glyph
approx_width = 0.5 * run.size * max(0, len(run.text))
positions.append((pen_x, pen_y, approx_width))
min_left = min(min_left, pen_x)
max_right = max(max_right, pen_x + approx_width)
pen_x += approx_width
total_width = max_right - min_left
return positions, total_width
def _anchor_offset(self, positions: list[tuple[float, float, float]]) -> float:
"""Compute anchor offset for the provided approximate layout."""
if not positions:
return 0.0
if any(run.abs_x is not None for run in self.text_runs):
return 0.0
min_x = min(pos[0] for pos in positions)
max_x = max(pos[0] + pos[2] for pos in positions)
if self.text_anchor == "middle":
return self.x - (min_x + max_x) / 2.0
if self.text_anchor == "end":
return self.x - max_x
return self.x - min_x
def bounding_box(self, start: Point) -> tuple["BoundingBox", Point]:
"""
Compute a conservative bbox for the text.
Font metrics are not available at this stage so the layout relies on
approximate glyph widths proportional to the run font size. The actual
layout is computed precisely in render().
"""
if not self.text_runs:
return BoundingBox.empty(), start
positions, _ = self._approximate_layout()
anchor_offset = self._anchor_offset(positions)
min_x = float("inf")
max_x = float("-inf")
min_y = float("inf")
max_y = float("-inf")
for (run_x, run_y, run_width), run in zip(positions, self.text_runs):
adj_x = run_x + anchor_offset
asc = 0.8 * run.size
desc = 0.2 * run.size
min_x = min(min_x, adj_x)
max_x = max(max_x, adj_x + run_width)
min_y = min(min_y, run_y - asc)
max_y = max(max_y, run_y + desc)
if min_x == float("inf"):
return BoundingBox.empty(), start
x0 = min_x
x1 = max_x
y0 = min_y
y1 = max_y
return BoundingBox.from_points([Point(x0, y0), Point(x1, y1)]), start
@force_nodocument
def render(
self,
resource_registry: "ResourceCatalog",
style: "GraphicsStyle",
last_item: "Renderable",
initial_point: Point,
) -> tuple[str, "Renderable", Point]:
"""
Emit PDF text operators:
BT
<font_id> <font_size> Tf
Tr <mode> (map from GraphicsStyle->PathPaintRule)
1 0 0 1 x y Tm
(escaped-text) Tj
ET
"""
if not self.text_runs:
return "", last_item, initial_point
# Precise layout resolution with actual font metrics
layout: list[
tuple[float, float, float, TextRun, Union["CoreFont", "TTFFont"]]
] = []
pen_x = self.x
pen_y = self.y
min_x = pen_x
max_x = pen_x
for run in self.text_runs:
font = resource_registry.get_font_from_family(run.family, run.emphasis)
_, width = font.get_text_width(run.text, run.size, None)
if run.abs_x is not None:
pen_x = run.abs_x
if run.abs_y is not None:
pen_y = run.abs_y
pen_x += run.dx
pen_y += run.dy
min_x = min(min_x, pen_x)
max_x = max(max_x, pen_x + width)
layout.append((pen_x, pen_y, width, run, font))
pen_x += width
has_absolute = any(run.abs_x is not None for _, _, _, run, _ in layout)
if layout and not has_absolute:
if self.text_anchor == "middle":
anchor_offset = self.x - (min_x + max_x) / 2.0
elif self.text_anchor == "end":
anchor_offset = self.x - max_x
else:
anchor_offset = self.x - min_x
else:
anchor_offset = 0.0
ops: list[str] = []
NO_EMIT_SET = (None, GraphicsStyle.INHERIT)
for run_x, run_y, width, run, font in layout:
effective_style = (
GraphicsStyle.merge(style, run.run_style)
if run.run_style is not None
else style
)
# Determine text rendering mode
rule = effective_style.resolve_paint_rule()
if rule in (PathPaintRule.FILL_NONZERO, PathPaintRule.FILL_EVENODD):
tr = 0
elif rule is PathPaintRule.STROKE:
tr = 1
elif rule in (
PathPaintRule.STROKE_FILL_NONZERO,
PathPaintRule.STROKE_FILL_EVENODD,
):
tr = 2
else: # PathPaintRule.DONT_PAINT:
tr = 3
run_ops: list[str] = []
if run.run_style is not None:
merged_style = effective_style
style_dict_name = resource_registry.register_graphics_style(
merged_style
)
if style_dict_name is not None:
run_ops.append(f"{render_pdf_primitive(style_dict_name)} gs")
fill_color = merged_style.fill_color
stroke_color = merged_style.stroke_color
run_bbox = BoundingBox.from_points(
[
Point(run_x + anchor_offset, run_y - 0.8 * run.size),
Point(run_x + anchor_offset + width, run_y + 0.2 * run.size),
]
)
if fill_color not in NO_EMIT_SET:
if isinstance(fill_color, GradientPaint):
run_ops.append(
fill_color.emit_fill(resource_registry, run_bbox)
)
else:
assert isinstance(
fill_color, (DeviceCMYK, DeviceRGB, DeviceRGB)
)
run_ops.append(fill_color.serialize().lower())
if stroke_color not in NO_EMIT_SET:
if isinstance(stroke_color, GradientPaint):
run_ops.append(
stroke_color.emit_stroke(resource_registry, run_bbox)
)
else:
assert isinstance(
stroke_color, (DeviceCMYK, DeviceRGB, DeviceRGB)
)
run_ops.append(stroke_color.serialize().upper())
dash_pattern = merged_style.stroke_dash_pattern
dash_phase = merged_style.stroke_dash_phase
assert isinstance(dash_phase, NumberClass)
if dash_pattern not in NO_EMIT_SET:
run_ops.append(
render_pdf_primitive(dash_pattern)
+ f" {number_to_str(dash_phase)} d"
)
run_ops.extend(
[
"BT",
f"/F{font.i} {number_to_str(run.size)} Tf",
f"{number_to_str(tr)} Tr",
f"1 0 0 -1 {number_to_str(run_x + anchor_offset)} {number_to_str(run_y)} Tm",
font.encode_text(run.text),
"ET",
]
)
if run.run_style is not None:
run_ops = ["q"] + run_ops + ["Q"]
ops.extend(run_ops)
return " ".join(ops), last_item, initial_point
class ImplicitClose(NamedTuple):
"""
A path close element that is conditionally rendered depending on the value of
`GraphicsStyle.auto_close`.
"""
@property
def end_point(self) -> Point:
raise NotImplementedError
# pylint: disable=no-self-use
def bounding_box(self, start: Point) -> tuple[BoundingBox, Point]:
"""Return an empty bounding box; Close does not affect the geometry."""
return BoundingBox.empty(), start
# pylint: disable=no-self-use
@force_nodocument
def render(
self,
resource_registry: "ResourceCatalog",
style: GraphicsStyle,
last_item: Renderable,
initial_point: Point,
) -> tuple[str, Renderable, Point]:
"""
Render this path element to its PDF representation.
Args:
resource_registry (ResourceCatalog): the owner's graphics state
dictionary registry.
style (GraphicsStyle): the current resolved graphics style
last_item: the previous path element.
initial_point: last position set by a "M" or "m" command
Returns:
a tuple of `(str, new_last_item)`, where `new_last_item` is whatever the old
last_item was.
"""
# pylint: disable=unused-argument
if style.auto_close:
return "h", last_item, initial_point
return "", last_item, initial_point
class Close(NamedTuple):
"""
A path close element.
Instructs the renderer to draw a straight line from the end of the last path element
to the start of the current path.
See: `PaintedPath.close`
"""
@property
def end_point(self) -> Point:
"""The end point of a Close is undefined; return (0, 0)."""
return Point(0, 0)
# pylint: disable=no-self-use
def bounding_box(self, start: Point) -> tuple[BoundingBox, Point]:
"""Return an empty bounding box; Close does not affect the geometry."""
return BoundingBox.empty(), start
# pylint: disable=no-self-use
@force_nodocument
def render(
self,
resource_registry: "ResourceCatalog",
style: GraphicsStyle,
last_item: Renderable,
initial_point: Point,
) -> tuple[str, Renderable, Point]:
"""
Render this path element to its PDF representation.
Args:
resource_registry (ResourceCatalog): the owner's graphics state
dictionary registry.
style (GraphicsStyle): the current resolved graphics style
last_item: the previous path element.
initial_point: last position set by a "M" or "m" command
Returns:
a tuple of `(str, new_last_item)`, where `new_last_item` is whatever the old
last_item was.
"""
# pylint: disable=unused-argument
return "h", Move(initial_point), initial_point
if TYPE_CHECKING:
# Validate all path items conform to the Renderable protocol
move: Renderable = Move(pt=Point(0, 0))
relative_move: Renderable = RelativeMove(pt=Point(0, 0))
line: Renderable = Line(pt=Point(0, 0))
relative_line: Renderable = RelativeLine(pt=Point(0, 0))
horizontal_line: Renderable = HorizontalLine(x=0)
relative_horizontal_line: Renderable = RelativeHorizontalLine(x=0)
vertical_line: Renderable = VerticalLine(y=0)
relative_vertical_line: Renderable = RelativeVerticalLine(y=0)
bezier_curve: Renderable = BezierCurve(
c1=Point(0, 0), c2=Point(0, 0), end=Point(0, 0)
)
relative_bezier_curve: Renderable = RelativeBezierCurve(
c1=Point(0, 0), c2=Point(0, 0), end=Point(0, 0)
)
quadratic_bezier_curve: Renderable = QuadraticBezierCurve(
ctrl=Point(0, 0), end=Point(0, 0)
)
relative_quadratic_bezier_curve: Renderable = RelativeQuadraticBezierCurve(
ctrl=Point(0, 0), end=Point(0, 0)
)
arc: Renderable = Arc(
radii=Point(0, 0), rotation=0, large=False, sweep=False, end=Point(0, 0)
)
relative_arc: Renderable = RelativeArc(
radii=Point(0, 0), rotation=0, large=False, sweep=False, end=Point(0, 0)
)
rectangle: Renderable = Rectangle(org=Point(0, 0), size=Point(0, 0))
rounded_rectangle: Renderable = RoundedRectangle(
org=Point(0, 0), size=Point(0, 0), corner_radii=Point(0, 0)
)
ellipse: Renderable = Ellipse(radii=Point(0, 0), center=Point(0, 0))
text: Renderable = Text(
x=0,
y=0,
text_runs=(TextRun(text="", family="Sans serif", emphasis="", size=12.0),),
)
implicit_close: Renderable = ImplicitClose()
close: Renderable = Close()
class DrawingContext:
"""
Base context for a drawing in a PDF
This context is not stylable and is mainly responsible for transforming path
drawing coordinates into user coordinates (i.e. it ensures that the output drawing
is correctly scaled).
"""
__slots__ = ("_subitems",)
def __init__(self) -> None:
self._subitems: list[Union[GraphicsContext, PaintedPath, PaintComposite]] = []
def add_item(
self,
item: Union["GraphicsContext", "PaintedPath", "PaintComposite"],
clone: bool = True,
) -> None:
"""
Append an item to this drawing context
Args:
item (GraphicsContext, PaintedPath): the item to be appended.
clone (bool): if true (the default), the item will be copied before being
appended. This prevents modifications to a referenced object from
"retroactively" altering its style/shape and should be disabled with
caution.
"""
if not isinstance(item, (GraphicsContext, PaintedPath, PaintComposite)):
raise TypeError(f"{item} doesn't belong in a DrawingContext")
if clone:
item = deepcopy(item)
self._subitems.append(item)
@staticmethod
def _setup_render_prereqs(
style: GraphicsStyle, first_point: Point, scale: float, height: float
) -> tuple[list[str], GraphicsStyle, Renderable]:
style.auto_close = True
style.paint_rule = PathPaintRule.AUTO
style.intersection_rule = IntersectionRule.NONZERO
last_item: Renderable = Move(first_point)
scale_rendered, last_item = (
Transform.scaling(x=1, y=-1)
.about(x=0, y=height / 2)
.scale(scale)
.render(last_item)
)
render_list = ["q", scale_rendered]
return render_list, style, last_item
def render(
self,
resource_registry: "ResourceCatalog",
first_point: Point,
scale: float,
height: float,
starting_style: GraphicsStyle,
) -> str:
"""
Render the drawing context to PDF format.
Args:
resource_registry (ResourceCatalog): the parent document's graphics
state registry.
first_point (Point): the starting point to use if the first path element is
a relative element.
scale (Number): the scale factor to convert from PDF pt units into the
document's semantic units (e.g. mm or in).
height (Number): the page height. This is used to remap the coordinates to
be from the top-left corner of the page (matching fpdf's behavior)
instead of the PDF native behavior of bottom-left.
starting_style (GraphicsStyle): the base style for this drawing context,
derived from the document's current style defaults.
Returns:
A string composed of the PDF representation of all the paths and groups in
this context (an empty string is returned if there are no paths or groups)
"""
if not self._subitems:
return ""
render_list, style, last_item = self._setup_render_prereqs(
starting_style, first_point, scale, height
)
for item in self._subitems:
rendered, last_item, first_point = item.render(
resource_registry, style, last_item, first_point
)
if rendered:
render_list.append(rendered)
# there was nothing to render: the only items are the start group and scale
# transform.
if len(render_list) == 2:
return ""
if (
not isinstance(style.soft_mask, InheritType)
and style.soft_mask.object_id == 0
):
style.soft_mask.object_id = resource_registry.register_soft_mask(
style.soft_mask
)
style_dict_name = resource_registry.register_graphics_style(style)
if style_dict_name is not None:
assert not isinstance(style.stroke_dash_pattern, InheritType)
assert not isinstance(style.stroke_dash_phase, InheritType)
render_list.insert(2, f"{render_pdf_primitive(style_dict_name)} gs")
render_list.insert(
3,
render_pdf_primitive(style.stroke_dash_pattern)
+ f" {number_to_str(style.stroke_dash_phase)} d",
)
render_list.append("Q")
return " ".join(render_list)
PP = TypeVar("PP", bound="PaintedPath")
class PaintedPath:
"""
A path to be drawn by the PDF renderer.
A painted path is defined by a style and an arbitrary sequence of path elements,
which include the primitive path elements (`Move`, `Line`, `BezierCurve`, ...) as
well as arbitrarily nested `GraphicsContext` containing their own sequence of
primitive path elements and `GraphicsContext`.
"""
__slots__ = (
"_root_graphics_context",
"_graphics_context",
"_closed",
"_close_context",
"_starter_move",
)
def __init__(self, x: float = 0, y: float = 0) -> None:
self._root_graphics_context: GraphicsContext = GraphicsContext()
self._graphics_context: GraphicsContext = self._root_graphics_context
self._closed: bool = True
self._close_context: GraphicsContext = self._graphics_context
self._starter_move: Optional[Renderable] = Move(Point(x, y))
def __deepcopy__(self: PP, memo: dict[int, Any]) -> PP:
# there's no real way to recover the matching current _graphics_context after
# copying the root context, but that's ok because we can just disallow copying
# of paths under modification as that is almost certainly wrong usage.
if self._graphics_context is not self._root_graphics_context:
raise RuntimeError(f"cannot copy path {self} while it is being modified")
copied = self.__class__()
copied._root_graphics_context = deepcopy(self._root_graphics_context, memo)
copied._graphics_context = copied._root_graphics_context
copied._closed = self._closed
copied._close_context = copied._graphics_context
return copied
@property
def style(self) -> GraphicsStyle:
"""The `GraphicsStyle` applied to all elements of this path."""
return self._root_graphics_context.style
@property
def transform(self) -> Optional[Transform]:
"""The `Transform` that applies to all of the elements of this path."""
return self._root_graphics_context.transform
@transform.setter
def transform(self, tf: Transform) -> None:
self._root_graphics_context.transform = tf
@property
def auto_close(self) -> bool | InheritType:
"""If true, the path should automatically close itself before painting."""
return self.style.auto_close
@auto_close.setter
def auto_close(self, should: bool) -> None:
self.style.auto_close = should
@property
def paint_rule(self) -> PathPaintRule | InheritType | None:
"""Manually specify the `PathPaintRule` to use for rendering the path."""
return self.style.paint_rule
@paint_rule.setter
def paint_rule(self, style: PathPaintRule) -> None:
self.style.paint_rule = style
@property
def clipping_path(self) -> Optional["ClippingPath"]:
"""Set the clipping path for this path."""
return self._root_graphics_context.clipping_path
@clipping_path.setter
def clipping_path(self, new_clipath: Optional["ClippingPath"]) -> None:
self._root_graphics_context.clipping_path = new_clipath
def get_graphics_context(self) -> "GraphicsContext":
return self._graphics_context
@contextmanager
def _new_graphics_context(
self, _attach: bool = True
) -> Iterator["GraphicsContext"]:
old_graphics_context = self._graphics_context
new_graphics_context = GraphicsContext()
self._graphics_context = new_graphics_context
try:
yield new_graphics_context
if _attach:
old_graphics_context.add_item(new_graphics_context)
finally:
self._graphics_context = old_graphics_context
@contextmanager
def transform_group(self, transform: Transform) -> Iterator["PaintedPath"]:
"""
Apply the provided `Transform` to all points added within this context.
"""
with self._new_graphics_context() as ctxt:
ctxt.transform = transform
yield self
def add_path_element(self, item: Renderable, clone: bool = True) -> None:
"""
Add the given element as a path item of this path.
Args:
item: the item to add to this path.
clone (bool): if true (the default), the item will be copied before being
appended. This prevents modifications to a referenced object from
"retroactively" altering its style/shape and should be disabled with
caution.
"""
if self._starter_move is not None:
self._closed = False
self._graphics_context.add_item(self._starter_move, clone=False)
self._close_context = self._graphics_context
self._starter_move = None
self._graphics_context.add_item(item, clone=clone)
def remove_last_path_element(self) -> None:
self._graphics_context.remove_last_item()
def rectangle(
self, x: Number, y: Number, w: Number, h: Number, rx: Number = 0, ry: Number = 0
) -> "PaintedPath":
"""
Append a rectangle as a closed subpath to the current path.
If the width or the height are 0, the rectangle will be collapsed to a line
(unless they're both 0, in which case it's collapsed to nothing).
Args:
x (Number): the abscissa of the starting corner of the rectangle.
y (Number): the ordinate of the starting corner of the rectangle.
w (Number): the width of the rectangle (if 0, the rectangle will be
rendered as a vertical line).
h (Number): the height of the rectangle (if 0, the rectangle will be
rendered as a horizontal line).
rx (Number): the x-radius of the rectangle rounded corner (if 0 the corners
will not be rounded).
ry (Number): the y-radius of the rectangle rounded corner (if 0 the corners
will not be rounded).
Returns:
The path, to allow chaining method calls.
"""
self._insert_implicit_close_if_open()
self.add_path_element(
RoundedRectangle(
Point(float(x), float(y)),
Point(float(w), float(h)),
Point(float(rx), float(ry)),
),
clone=False,
)
self._closed = True
self.move_to(x, y)
return self
def circle(self, cx: Number, cy: Number, r: Number) -> "PaintedPath":
"""
Append a circle as a closed subpath to the current path.
Args:
cx (Number): the abscissa of the circle's center point.
cy (Number): the ordinate of the circle's center point.
r (Number): the radius of the circle.
Returns:
The path, to allow chaining method calls.
"""
return self.ellipse(cx, cy, r, r)
def ellipse(self, cx: Number, cy: Number, rx: Number, ry: Number) -> "PaintedPath":
"""
Append an ellipse as a closed subpath to the current path.
Args:
cx (Number): the abscissa of the ellipse's center point.
cy (Number): the ordinate of the ellipse's center point.
rx (Number): the x-radius of the ellipse.
ry (Number): the y-radius of the ellipse.
Returns:
The path, to allow chaining method calls.
"""
self._insert_implicit_close_if_open()
self.add_path_element(
Ellipse(Point(float(rx), float(ry)), Point(float(cx), float(cy))),
clone=False,
)
self._closed = True
self.move_to(cx, cy)
return self
def move_to(self, x: Number, y: Number) -> "PaintedPath":
"""
Start a new subpath or move the path starting point.
If no path elements have been added yet, this will change the path starting
point. If path elements have been added, this will insert an implicit close in
order to start a new subpath.
Args:
x (Number): abscissa of the (sub)path starting point.
y (Number): ordinate of the (sub)path starting point.
Returns:
The path, to allow chaining method calls.
"""
self._insert_implicit_close_if_open()
self._starter_move = Move(Point(float(x), float(y)))
return self
def move_relative(self, x: Number, y: Number) -> "PaintedPath":
"""
Start a new subpath or move the path start point relative to the previous point.
If no path elements have been added yet, this will change the path starting
point. If path elements have been added, this will insert an implicit close in
order to start a new subpath.
This will overwrite an absolute move_to as long as no non-move path items have
been appended. The relative position is resolved from the previous item when
the path is being rendered, or from 0, 0 if it is the first item.
Args:
x (Number): abscissa of the (sub)path starting point relative to the previous point.
y (Number): ordinate of the (sub)path starting point relative to the previous point.
"""
self._insert_implicit_close_if_open()
if self._starter_move is not None:
self._closed = False
self._graphics_context.add_item(self._starter_move, clone=False)
self._close_context = self._graphics_context
self._starter_move = RelativeMove(Point(float(x), float(y)))
return self
def line_to(self, x: Number, y: Number) -> "PaintedPath":
"""
Append a straight line to this path.
Args:
x (Number): abscissa the line's end point.
y (Number): ordinate of the line's end point.
Returns:
The path, to allow chaining method calls.
"""
self.add_path_element(Line(Point(float(x), float(y))), clone=False)
return self
def line_relative(self, dx: Number, dy: Number) -> "PaintedPath":
"""
Append a straight line whose end is computed as an offset from the end of the
previous path element.
Args:
x (Number): abscissa the line's end point relative to the end point of the
previous path element.
y (Number): ordinate of the line's end point relative to the end point of
the previous path element.
Returns:
The path, to allow chaining method calls.
"""
self.add_path_element(RelativeLine(Point(float(dx), float(dy))), clone=False)
return self
def horizontal_line_to(self, x: Number) -> "PaintedPath":
"""
Append a straight horizontal line to the given abscissa. The ordinate is
retrieved from the end point of the previous path element.
Args:
x (Number): abscissa of the line's end point.
Returns:
The path, to allow chaining method calls.
"""
self.add_path_element(HorizontalLine(float(x)), clone=False)
return self
def horizontal_line_relative(self, dx: Number) -> "PaintedPath":
"""
Append a straight horizontal line to the given offset from the previous path
element. The ordinate is retrieved from the end point of the previous path
element.
Args:
x (Number): abscissa of the line's end point relative to the end point of
the previous path element.
Returns:
The path, to allow chaining method calls.
"""
self.add_path_element(RelativeHorizontalLine(float(dx)), clone=False)
return self
def vertical_line_to(self, y: Number) -> "PaintedPath":
"""
Append a straight vertical line to the given ordinate. The abscissa is
retrieved from the end point of the previous path element.
Args:
y (Number): ordinate of the line's end point.
Returns:
The path, to allow chaining method calls.
"""
self.add_path_element(VerticalLine(float(y)), clone=False)
return self
def vertical_line_relative(self, dy: Number) -> "PaintedPath":
"""
Append a straight vertical line to the given offset from the previous path
element. The abscissa is retrieved from the end point of the previous path
element.
Args:
y (Number): ordinate of the line's end point relative to the end point of
the previous path element.
Returns:
The path, to allow chaining method calls.
"""
self.add_path_element(RelativeVerticalLine(float(dy)), clone=False)
return self
def curve_to(
self, x1: Number, y1: Number, x2: Number, y2: Number, x3: Number, y3: Number
) -> "PaintedPath":
"""
Append a cubic Bézier curve to this path.
Args:
x1 (Number): abscissa of the first control point
y1 (Number): ordinate of the first control point
x2 (Number): abscissa of the second control point
y2 (Number): ordinate of the second control point
x3 (Number): abscissa of the end point
y3 (Number): ordinate of the end point
Returns:
The path, to allow chaining method calls.
"""
ctrl1 = Point(float(x1), float(y1))
ctrl2 = Point(float(x2), float(y2))
end = Point(float(x3), float(y3))
self.add_path_element(BezierCurve(ctrl1, ctrl2, end), clone=False)
return self
def curve_relative(
self,
dx1: Number,
dy1: Number,
dx2: Number,
dy2: Number,
dx3: Number,
dy3: Number,
) -> "PaintedPath":
"""
Append a cubic Bézier curve whose points are expressed relative to the
end point of the previous path element.
E.g. with a start point of (0, 0), given (1, 1), (2, 2), (3, 3), the output
curve would have the points:
(0, 0) c1 (1, 1) c2 (3, 3) e (6, 6)
Args:
dx1 (Number): abscissa of the first control point relative to the end point
of the previous path element
dy1 (Number): ordinate of the first control point relative to the end point
of the previous path element
dx2 (Number): abscissa offset of the second control point relative to the
end point of the previous path element
dy2 (Number): ordinate offset of the second control point relative to the
end point of the previous path element
dx3 (Number): abscissa offset of the end point relative to the end point of
the previous path element
dy3 (Number): ordinate offset of the end point relative to the end point of
the previous path element
Returns:
The path, to allow chaining method calls.
"""
c1d = Point(float(dx1), float(dy1))
c2d = Point(float(dx2), float(dy2))
end = Point(float(dx3), float(dy3))
self.add_path_element(RelativeBezierCurve(c1d, c2d, end), clone=False)
return self
def quadratic_curve_to(
self, x1: Number, y1: Number, x2: Number, y2: Number
) -> "PaintedPath":
"""
Append a cubic Bézier curve mimicking the specified quadratic Bézier curve.
Args:
x1 (Number): abscissa of the control point
y1 (Number): ordinate of the control point
x2 (Number): abscissa of the end point
y2 (Number): ordinate of the end point
Returns:
The path, to allow chaining method calls.
"""
ctrl = Point(float(x1), float(y1))
end = Point(float(x2), float(y2))
self.add_path_element(QuadraticBezierCurve(ctrl, end), clone=False)
return self
def quadratic_curve_relative(
self, dx1: Number, dy1: Number, dx2: Number, dy2: Number
) -> "PaintedPath":
"""
Append a cubic Bézier curve mimicking the specified quadratic Bézier curve.
Args:
dx1 (Number): abscissa of the control point relative to the end point of
the previous path element
dy1 (Number): ordinate of the control point relative to the end point of
the previous path element
dx2 (Number): abscissa offset of the end point relative to the end point of
the previous path element
dy2 (Number): ordinate offset of the end point relative to the end point of
the previous path element
Returns:
The path, to allow chaining method calls.
"""
ctrl = Point(float(dx1), float(dy1))
end = Point(float(dx2), float(dy2))
self.add_path_element(RelativeQuadraticBezierCurve(ctrl, end), clone=False)
return self
def arc_to(
self,
rx: Number,
ry: Number,
rotation: Number,
large_arc: bool,
positive_sweep: bool,
x: Number,
y: Number,
) -> "PaintedPath":
"""
Append an elliptical arc from the end of the previous path point to the
specified end point.
The arc is approximated using Bézier curves, so it is not perfectly accurate.
However, the error is small enough to not be noticeable at any reasonable
(and even most unreasonable) scales, with a worst-case deviation of around 3‱.
Notes:
- The signs of the radii arguments (`rx` and `ry`) are ignored (i.e. their
absolute values are used instead).
- If either radius is 0, then a straight line will be emitted instead of an
arc.
- If the radii are too small for the arc to reach from the current point to
the specified end point (`x` and `y`), then they will be proportionally
scaled up until they are big enough, which will always result in a
half-ellipse arc (i.e. an 180 degree sweep)
Args:
rx (Number): radius in the x-direction.
ry (Number): radius in the y-direction.
rotation (Number): angle (in degrees) that the arc should be rotated
clockwise from the principle axes. This parameter does not have
a visual effect in the case that `rx == ry`.
large_arc (bool): if True, the arc will cover a sweep angle of at least 180
degrees. Otherwise, the sweep angle will be at most 180 degrees.
positive_sweep (bool): if True, the arc will be swept over a positive angle,
i.e. clockwise. Otherwise, the arc will be swept over a negative
angle.
x (Number): abscissa of the arc's end point.
y (Number): ordinate of the arc's end point.
"""
if rx == 0 or ry == 0:
return self.line_to(x, y)
rx_float = float(rx)
ry_float = float(ry)
radii = Point(abs(rx_float), abs(ry_float))
large_arc = bool(large_arc)
rotation = math.radians(rotation)
positive_sweep = bool(positive_sweep)
end = Point(float(x), float(y))
self.add_path_element(
Arc(radii, rotation, large_arc, positive_sweep, end), clone=False
)
return self
def arc_relative(
self,
rx: Number,
ry: Number,
rotation: Number,
large_arc: bool,
positive_sweep: bool,
dx: Number,
dy: Number,
) -> "PaintedPath":
"""
Append an elliptical arc from the end of the previous path point to an offset
point.
The arc is approximated using Bézier curves, so it is not perfectly accurate.
However, the error is small enough to not be noticeable at any reasonable
(and even most unreasonable) scales, with a worst-case deviation of around 3‱.
Notes:
- The signs of the radii arguments (`rx` and `ry`) are ignored (i.e. their
absolute values are used instead).
- If either radius is 0, then a straight line will be emitted instead of an
arc.
- If the radii are too small for the arc to reach from the current point to
the specified end point (`x` and `y`), then they will be proportionally
scaled up until they are big enough, which will always result in a
half-ellipse arc (i.e. an 180 degree sweep)
Args:
rx (Number): radius in the x-direction.
ry (Number): radius in the y-direction.
rotation (Number): angle (in degrees) that the arc should be rotated
clockwise from the principle axes. This parameter does not have
a visual effect in the case that `rx == ry`.
large_arc (bool): if True, the arc will cover a sweep angle of at least 180
degrees. Otherwise, the sweep angle will be at most 180 degrees.
positive_sweep (bool): if True, the arc will be swept over a positive angle,
i.e. clockwise. Otherwise, the arc will be swept over a negative
angle.
dx (Number): abscissa of the arc's end point relative to the end point of
the previous path element.
dy (Number): ordinate of the arc's end point relative to the end point of
the previous path element.
"""
if rx == 0 or ry == 0:
return self.line_relative(dx, dy)
rx_float = float(rx)
ry_float = float(ry)
radii = Point(abs(rx_float), abs(ry_float))
large_arc = bool(large_arc)
rotation = math.radians(rotation)
positive_sweep = bool(positive_sweep)
end = Point(float(dx), float(dy))
self.add_path_element(
RelativeArc(radii, rotation, large_arc, positive_sweep, end), clone=False
)
return self
def text(
self,
x: float,
y: float,
content: str,
font_family: str = "helvetica",
font_style: str = "", # "", "B", "I", "BI"
font_size: float = 12.0,
text_anchor: str = "start", # "start" | "middle" | "end"
) -> "PaintedPath":
"""
Append a text run at (x, y) to this path.
The baseline is at (x, y). `text_anchor` controls alignment about x.
`font_style` accepts "", "B", "I", or "BI". `font_family` can be a single
name or a comma-separated fallback list (handled at render-time).
Returns:
self (to allow chaining)
"""
# Normalize style just in case e.g. "ib" -> "BI"
s = "".join(sorted(font_style.upper()))
self.add_path_element(
Text(
x=x,
y=y,
text_runs=(
TextRun(
text=content,
family=font_family,
emphasis=s,
size=font_size,
),
),
text_anchor=text_anchor,
),
clone=False,
)
return self
def close(self) -> None:
"""
Explicitly close the current (sub)path.
"""
self.add_path_element(Close(), clone=False)
self._closed = True
self.move_relative(0, 0)
def _insert_implicit_close_if_open(self) -> None:
if not self._closed:
self._close_context.add_item(ImplicitClose(), clone=False)
self._close_context = self._graphics_context
self._closed = True
def bounding_box(
self, start: Point, expand_for_stroke: bool = True
) -> tuple[BoundingBox, Point]:
"""Compute the bounding box of this painted path, including nested contexts and transformations."""
return self._root_graphics_context.bounding_box(
start, self.style, expand_for_stroke=expand_for_stroke
)
def render(
self,
resource_registry: "ResourceCatalog",
style: GraphicsStyle,
last_item: Renderable,
initial_point: Point,
) -> tuple[str, Renderable, Point]:
self._insert_implicit_close_if_open()
(
render_list,
last_item,
initial_point,
) = self._root_graphics_context.build_render_list(
resource_registry, style, last_item, initial_point
)
paint_rule = GraphicsStyle.merge(style, self.style).resolve_paint_rule()
render_list.insert(-1, paint_rule.value)
return " ".join(render_list), last_item, initial_point
class ClippingPath(PaintedPath):
"""
The PaintedPath API but to be used to create clipping paths.
.. warning::
Unless you really know what you're doing, changing attributes of the clipping
path style is likely to produce unexpected results. This is because the
clipping path styles override implicit style inheritance of the `PaintedPath`
it applies to.
For example, `clippath.style.stroke_width = 2` can unexpectedly override
`paintpath.style.stroke_width = GraphicsStyle.INHERIT` and cause the painted
path to be rendered with a stroke of 2 instead of what it would have normally
inherited. Because a `ClippingPath` can be painted like a normal `PaintedPath`,
it would be overly restrictive to remove the ability to style it, so instead
this warning is here.
"""
__slots__ = () # no new attributes; preserve slotted layout from PaintedPath
# because clipping paths can be painted, we inherit from PaintedPath. However, when
# setting the styling on the clipping path, those values will also be applied to
# the PaintedPath the ClippingPath is applied to unless they are explicitly set for
# that painted path. This is not ideal, but there's no way to really fix it from
# the PDF rendering model, and trying to track the appropriate state/defaults seems
# similarly error prone.
# In general, the expectation is that painted clipping paths are likely to be very
# uncommon, so it's an edge case that isn't worth worrying too much about.
def __init__(self, x: Number = 0, y: Number = 0) -> None:
super().__init__(x=float(x), y=float(y))
self.paint_rule = PathPaintRule.DONT_PAINT
def render(
self,
resource_registry: "ResourceCatalog",
style: GraphicsStyle,
last_item: Renderable,
initial_point: Point,
) -> tuple[str, Renderable, Point]:
# painting the clipping path outside of its root graphics context allows it to
# be transformed without affecting the transform of the graphics context of the
# path it is being used to clip. This is because, unlike all of the other style
# settings, transformations immediately affect the points following them,
# rather than only affecting them at painting time. stroke settings and color
# settings are applied only at paint time.
(
render_list,
last_item,
initial_point,
) = self._root_graphics_context.build_render_list(
resource_registry,
style,
last_item,
initial_point,
_push_stack=False,
)
merged_style = GraphicsStyle.merge(style, self.style)
# we should never get a collision error here
intersection_rule: ClippingPathIntersectionRule = (
ClippingPathIntersectionRule.NONZERO
)
if not isinstance(merged_style.intersection_rule, InheritType):
intersection_rule = ClippingPathIntersectionRule[
merged_style.intersection_rule.name
]
paint_rule = merged_style.resolve_paint_rule()
render_list.append(intersection_rule.value)
render_list.append(paint_rule.value)
return " ".join(render_list), last_item, initial_point
GC = TypeVar("GC", bound="GraphicsContext")
class GraphicsContext:
"""
Page-level container that collects drawable items and renders them into a PDF
content stream.
Converts model coordinates to PDF user space by applying the provided
`scale` and a vertical flip so (0, 0) is the top-left of the page.
Wraps output in a saved graphics state (`q … Q`) and registers any
required resources (graphics state dictionaries, soft masks, dash pattern).
Child items are typically `GraphicsContext`, `PaintedPath`, or `PaintComposite`
objects added via `add_item()`. By default, items are deep-copied on insert to
avoid later mutations affecting the emitted stream.
"""
__slots__ = ("style", "path_items", "_transform", "_clipping_path")
def __init__(self) -> None:
self.style: GraphicsStyle = GraphicsStyle()
self.path_items: list[
Renderable
| GraphicsContext
| PaintedPath
| PaintComposite
| PaintBlendComposite
] = []
self._transform: Optional[Transform] = None
self._clipping_path: Optional[ClippingPath] = None
def __deepcopy__(self: GC, memo: dict[int, Any]) -> GC:
copied = self.__class__()
copied.style = deepcopy(self.style, memo)
copied.path_items = deepcopy(self.path_items, memo)
copied._transform = deepcopy(self.transform, memo)
copied._clipping_path = deepcopy(self.clipping_path, memo)
return copied
@property
def transform(self) -> Optional[Transform]:
return self._transform
@transform.setter
def transform(self, tf: Optional[Transform]) -> None:
self._transform = tf
@property
def clipping_path(self) -> Optional[ClippingPath]:
"""The `ClippingPath` for this graphics context."""
return self._clipping_path
@clipping_path.setter
def clipping_path(self, new_clipath: Optional[ClippingPath]) -> None:
self._clipping_path = new_clipath
def add_item(
self,
item: Union[
Renderable,
"GraphicsContext",
PaintedPath,
"PaintComposite",
"PaintBlendComposite",
],
clone: bool = True,
) -> None:
"""
Add a path element to this graphics context.
Args:
item: the path element to add. May be a primitive element or another
`GraphicsContext` or a `PaintedPath`.
clone (bool): if true (the default), the item will be copied before being
appended. This prevents modifications to a referenced object from
"retroactively" altering its style/shape and should be disabled with
caution.
"""
if clone:
item = deepcopy(item)
self.path_items.append(item)
def remove_last_item(self) -> None:
del self.path_items[-1]
def merge(self, other_context: "GraphicsContext") -> None:
"""Copy another `GraphicsContext`'s path items into this one."""
self.path_items.extend(other_context.path_items)
@force_nodocument
def build_render_list(
self,
resource_registry: "ResourceCatalog",
style: GraphicsStyle,
last_item: Renderable,
initial_point: Point,
_push_stack: bool = True,
) -> tuple[list[str], Renderable, Point]:
"""
Build a list composed of all all the individual elements rendered.
This is used by `PaintedPath` and `ClippingPath` to reuse the `GraphicsContext`
rendering process while still being able to inject some path specific items
(e.g. the painting directive) before the render is collapsed into a single
string.
Args:
resource_registry (ResourceCatalog): the owner's graphics state
dictionary registry.
style (GraphicsStyle): the current resolved graphics style
last_item: the previous path element.
initial_point: last position set by a "M" or "m" command
_push_stack (bool): if True, wrap the resulting render list in a push/pop
graphics stack directive pair.
Returns:
`tuple[list[str], last_item]` where `last_item` is the past path element in
this `GraphicsContext`
"""
render_list: list[str] = []
if self.path_items:
merged_style = style.__class__.merge(style, self.style)
NO_EMIT_SET = (None, merged_style.INHERIT)
emit_style = self.style
if merged_style.allow_transparency != self.style.allow_transparency:
emit_style = deepcopy(self.style)
emit_style.allow_transparency = merged_style.allow_transparency
# in order to decouple the dash pattern and the dash phase at the API layer,
# we have to perform additional logic here to recombine them. We can rely
# on these being serializable because we always get a sane style on the
# drawing context.
dash_pattern = merged_style.stroke_dash_pattern
dash_phase = merged_style.stroke_dash_phase
emit_dash = None
if (
dash_pattern != style.stroke_dash_pattern
or dash_phase != style.stroke_dash_phase
):
if emit_style is self.style:
emit_style = deepcopy(emit_style)
emit_style.stroke_dash_pattern = dash_pattern
emit_style.stroke_dash_phase = dash_phase
emit_dash = (dash_pattern, dash_phase)
if (
not isinstance(emit_style.soft_mask, InheritType)
and emit_style.soft_mask.object_id == 0
):
emit_style.soft_mask.object_id = resource_registry.register_soft_mask(
emit_style.soft_mask
)
# ---- If fill/stroke use a GradientPaint with alpha, synthesize a soft mask now
def _attach_alpha_mask_if_needed(
paint_obj: GradientPaint | Color | InheritType | str | None,
) -> None:
if not isinstance(paint_obj, GradientPaint):
return
if not paint_obj.has_alpha():
return
# bbox in content space (shared by color & mask)
bbox_for_units = self.bounding_box(
initial_point,
style=self.style,
expand_for_stroke=False,
transformed=False,
)[0]
# rectangular mask covering the painted area
mask_rect = PaintedPath()
mask_rect.rectangle(
bbox_for_units.x0,
bbox_for_units.y0,
bbox_for_units.width,
bbox_for_units.height,
)
# paint that rectangle with the grayscale alpha gradient
alpha_paint = _AlphaGradientPaint(
paint_obj.gradient,
paint_obj.units,
gradient_transform=paint_obj.gradient_transform,
)
alpha_paint.apply_page_ctm = paint_obj.apply_page_ctm
mask_rect.style.fill_color = alpha_paint
mask_rect.style.stroke_color = None
mask_rect.style.stroke_width = 0
mask_rect.style.paint_rule = PathPaintRule.FILL_NONZERO
mask_gc = GraphicsContext()
mask_gc.add_item(mask_rect, clone=False)
# use luminosity so gray intensity drives coverage
sm = PaintSoftMask(
mask_gc,
invert=False,
use_luminosity=True,
matrix=paint_obj.gradient_transform,
)
nonlocal emit_style
if emit_style.allow_transparency is False:
return
if emit_style is self.style:
emit_style = deepcopy(self.style)
emit_style.soft_mask = sm
emit_style.soft_mask.object_id = resource_registry.register_soft_mask(
emit_style.soft_mask
)
# Decide whether to attach a soft mask from fill or stroke gradient alpha.
# Priority: fill first (most common), otherwise stroke.
if isinstance(emit_style.fill_color, GradientPaint) and (
emit_style.soft_mask in (None, GraphicsStyle.INHERIT)
):
_attach_alpha_mask_if_needed(self.style.fill_color)
elif isinstance(emit_style.stroke_color, GradientPaint) and (
emit_style.soft_mask in (None, GraphicsStyle.INHERIT)
):
_attach_alpha_mask_if_needed(self.style.stroke_color)
style_dict_name = resource_registry.register_graphics_style(emit_style)
if style_dict_name is not None:
render_list.append(f"{render_pdf_primitive(style_dict_name)} gs")
# we can't set color in the graphics state context dictionary, so we have to
# manually inherit it and emit it here.
fill_color = self.style.fill_color
stroke_color = self.style.stroke_color
bbox_for_units = None
if isinstance(fill_color, GradientPaint) or isinstance(
stroke_color, GradientPaint
):
# Compute bbox once so mask and color share the same mapping
bbox_for_units = self.bounding_box(
initial_point, style=self.style, expand_for_stroke=False
)[0]
if fill_color not in NO_EMIT_SET:
if isinstance(fill_color, GradientPaint):
render_list.append(
fill_color.emit_fill(resource_registry, bbox_for_units)
)
else:
assert isinstance(fill_color, (DeviceCMYK | DeviceGray | DeviceRGB))
render_list.append(fill_color.serialize().lower())
if stroke_color not in NO_EMIT_SET:
if isinstance(stroke_color, GradientPaint):
render_list.append(
stroke_color.emit_stroke(resource_registry, bbox_for_units)
)
else:
assert isinstance(stroke_color, (DeviceCMYK, DeviceGray, DeviceRGB))
render_list.append(stroke_color.serialize().upper())
if emit_dash is not None:
assert isinstance(emit_dash[1], NumberClass)
render_list.append(
render_pdf_primitive(emit_dash[0])
+ f" {number_to_str(emit_dash[1])} d"
)
if self.clipping_path is not None:
rendered_cpath, _, __ = self.clipping_path.render(
resource_registry, merged_style, last_item, initial_point
)
if rendered_cpath:
render_list.append(rendered_cpath)
for item in self.path_items:
rendered, last_item, initial_point = item.render(
resource_registry, merged_style, last_item, initial_point
)
if rendered:
render_list.append(rendered)
# insert transform before points
if self.transform is not None:
render_list.insert(0, self.transform.render(last_item)[0])
if _push_stack:
render_list.insert(0, "q")
render_list.append("Q")
return render_list, last_item, initial_point
def bounding_box(
self,
start: Point,
style: Optional[GraphicsStyle] = None,
expand_for_stroke: bool = True,
transformed: bool = True,
) -> tuple[BoundingBox, Point]:
"""
Compute bbox of all path items. We:
1) recurse with accumulated CTM,
2) merge child bboxes already transformed to this level,
3) at the end, expand once for stroke using the worst-case CTM row norms.
"""
identity = Transform.identity()
def walk(
ctx: "GraphicsContext",
current_point: Point,
ambient_style: Optional[GraphicsStyle],
accum_tf: Transform,
) -> tuple[BoundingBox, Point, float, float]:
bbox = BoundingBox.empty()
tf = accum_tf @ (ctx.transform or identity)
if not transformed:
tf = identity
merged_style = (
ambient_style.__class__.merge(ambient_style, ctx.style)
if ambient_style
else ctx.style
)
max_nx, max_ny = tf.row_norms()
for item in ctx.path_items:
if isinstance(item, (PaintComposite, PaintBlendComposite)):
continue
if isinstance(item, GraphicsContext):
child_bbox, end_point, cnx, cny = walk(
item, current_point, merged_style, tf
)
bbox = bbox.merge(child_bbox) # child bbox already in this space
current_point = end_point
max_nx = max(max_nx, cnx)
max_ny = max(max_ny, cny)
elif hasattr(item, "bounding_box"):
item_bbox, end_point = item.bounding_box(current_point)
bbox = bbox.merge(item_bbox.transformed(tf))
current_point = end_point
return bbox, current_point, max_nx, max_ny
# 1) geometric + collect CTM scales
geom_bbox, end_pt, nx, ny = walk(self, start, style, identity)
final_bbox = geom_bbox
if expand_for_stroke:
# 2) expand once for stroke with the effective style at *this* level
effective_style = (
style.__class__.merge(style, self.style) if style else self.style
)
final_bbox = geom_bbox.expanded_to_stroke(
effective_style, row_norms=(nx, ny)
)
return final_bbox, end_pt
def render(
self,
resource_registry: "ResourceCatalog",
style: GraphicsStyle,
last_item: Renderable,
initial_point: Point,
_push_stack: bool = True,
) -> tuple[str, Renderable, Point]:
render_list, last_item, initial_point = self.build_render_list(
resource_registry,
style,
last_item,
initial_point,
_push_stack=_push_stack,
)
return " ".join(render_list), last_item, initial_point
class PaintSoftMask:
"""
Wraps a vector path as a PDF soft mask (SMask) that can be attached to a
graphics state.
The provided `mask_path` is deep-copied and forced to render as an opaque
grayscale fill (white, alpha=1, nonzero rule, transparency disabled). During
rendering, the mask’s content stream is generated and its resource
dictionary is collected so it can be embedded as a Form XObject and
referenced from an ExtGState.
"""
__slots__ = (
"mask_path",
"invert",
"resources",
"use_luminosity",
"object_id",
"matrix",
)
def __init__(
self,
mask_path: Union[PaintedPath, GraphicsContext],
invert: bool = False,
use_luminosity: bool = False,
matrix: Transform = Transform.identity(),
):
self.mask_path = deepcopy(mask_path)
self.invert: bool = invert
self.use_luminosity: bool = use_luminosity
self.resources: set[tuple[PDFResourceType, str]] = set()
self.object_id: int = 0
self.matrix: Transform = matrix
if not self.use_luminosity:
# Pure alpha mask -> force opaque white so shape defines coverage
self.mask_path.style.paint_rule = PathPaintRule.FILL_NONZERO
self.mask_path.style.fill_opacity = 1
self.mask_path.style.fill_color = "#ffffff"
def serialize(self) -> str:
tr = (
" /TR <</FunctionType 2 /Domain [0 1] /Range [0 1] /C0 [1] /C1 [0] /N 1>>"
if self.invert
else ""
)
mask_type = "/Luminosity" if self.use_luminosity else "/Alpha"
return f"<</S {mask_type} /G {self.object_id} 0 R{tr}>>"
def get_bounding_box(self) -> tuple[float, float, float, float]:
bounding_box, _ = self.mask_path.bounding_box(Point(0, 0))
return bounding_box.to_tuple()
def get_resource_dictionary(
self,
gfxstate_objs_per_name: dict[str, PDFObject],
pattern_objs_per_name: dict[str, PDFObject],
_img_objs_per_index: Optional[dict[int, PDFObject]] = None,
) -> str:
"""Build the resource dictionary for this soft mask, resolving GS & Pattern ids."""
resources_registered: dict[str, set[str]] = {}
for resource_type, resource_id in self.resources:
resources_registered.setdefault(resource_type.value, set()).add(resource_id)
parts: list[str] = []
# ExtGState
if "ExtGState" in resources_registered and resources_registered["ExtGState"]:
parts.append(
Name("ExtGState").serialize()
+ "<<"
+ "".join(
f"{Name(gs_name).serialize()} {gfxstate_objs_per_name[gs_name].id} 0 R"
for gs_name in sorted(resources_registered["ExtGState"])
)
+ ">>"
)
# Pattern
if "Pattern" in resources_registered and resources_registered["Pattern"]:
parts.append(
Name("Pattern").serialize()
+ "<<"
+ "".join(
f"{Name(pat_name).serialize()} {pattern_objs_per_name[pat_name].id} 0 R"
for pat_name in sorted(resources_registered["Pattern"])
)
+ ">>"
)
return "<<" + "".join(parts) + ">>"
def render(self, resource_registry: "ResourceCatalog") -> str:
stream, _, _ = self.mask_path.render(
resource_registry,
style=GraphicsStyle(),
last_item=Move(Point(0, 0)),
initial_point=Point(0, 0),
)
self.resources = resource_registry.scan_stream(stream)
return stream
@staticmethod
def coverage_white(
node: Union[PaintedPath, GraphicsContext],
) -> Union[PaintedPath, GraphicsContext]:
"""
Return a deep-copied version of *node* whose appearance encodes only its
geometric coverage: every shape is converted to an **opaque white fill**
(nonzero rule), with **no stroke**, no soft mask, and inherited blend mode.
The transform/clipping/structure of the original node is preserved; only
paint-related attributes are normalized. This is intended for building the
“B” term of soft-mask expressions (coverage), where inside = 1 and
outside = 0.
"""
def _force_white(gc: GraphicsContext) -> None:
# normalize the GC's own style
gc.style.paint_rule = PathPaintRule.FILL_NONZERO
gc.style.fill_color = "#ffffff"
gc.style.fill_opacity = 1
gc.style.stroke_color = None
gc.style.blend_mode = GraphicsStyle.INHERIT
gc.style.soft_mask = GraphicsStyle.INHERIT
# recurse into children
for child in gc.path_items:
if isinstance(child, GraphicsContext):
_force_white(child)
elif isinstance(child, PaintedPath):
child.style.paint_rule = PathPaintRule.FILL_NONZERO
child.style.fill_color = "#ffffff"
child.style.fill_opacity = 1
child.style.stroke_color = None
child.style.blend_mode = GraphicsStyle.INHERIT
child.style.soft_mask = GraphicsStyle.INHERIT
new_node = clone_structure(node)
gc = (
new_node
if isinstance(new_node, GraphicsContext)
else new_node.get_graphics_context()
)
_force_white(gc)
return new_node
@staticmethod
def alpha_layers_from(
node: GraphicsContext | PaintedPath,
) -> Optional[GraphicsContext]:
"""
Build a GraphicsContext that encodes the *alpha ramps* contributed by any
`GradientPaint` used by *node*. Each contributing PaintedPath yields one
rectangle covering its content-space bounding box; that rectangle is filled
with an `_AlphaGradientPaint` (the gradient’s *alpha channel only*).
Rectangles are stacked with `BM=Multiply` so multiple alpha sources
combine multiplicatively.
"""
layers: list[GraphicsContext] = []
for n in _iter_nodes(node):
if isinstance(n, PaintedPath):
for paint in (n.style.fill_color, n.style.stroke_color):
if (
isinstance(paint, GradientPaint)
and paint.gradient
and paint.gradient.has_alpha()
):
bb = n.bounding_box(Point(0, 0), expand_for_stroke=False)[0]
if bb.width <= 0 or bb.height <= 0:
continue
rect = PaintedPath()
rect.rectangle(bb.x0, bb.y0, bb.width, bb.height)
alpha_paint = _AlphaGradientPaint(
gradient=paint.gradient,
units=paint.units,
gradient_transform=paint.gradient_transform,
apply_page_ctm=paint.apply_page_ctm,
)
rect.style.fill_color = alpha_paint
rect.style.stroke_color = None
rect.style.stroke_width = 0
rect.style.paint_rule = PathPaintRule.FILL_NONZERO
layer_gc = GraphicsContext()
layer_gc.add_item(rect, clone=False)
# multiply multiple alpha contributors together
layer_gc.style.blend_mode = BlendMode.MULTIPLY
layers.append(layer_gc)
if not layers:
return None
A = GraphicsContext()
for layer in layers:
A.add_item(layer)
return A
@classmethod
def from_AB(
cls,
A: Optional[GraphicsContext],
B: Union[PaintedPath, GraphicsContext],
invert: bool,
registry: "ResourceCatalog",
region_bbox: Optional["BoundingBox"] = None,
) -> "PaintSoftMask":
"""
Construct a **luminosity soft mask** from two ingredients:
- **A**: Optional GraphicsContext encoding alpha ramps (e.g., the result of
:meth:`alpha_layers_from`). If ``None``, the effective alpha is 1.
- **B**: Coverage term (e.g., the result of :meth:`coverage_white`).
The mask luminance is:
- ``A × B`` when ``invert = False``
- ``A × (1 − B)`` when ``invert = True``
Implementation outline:
1. Compute the union bbox of A and B (no stroke expansion).
2. Paint a background rectangle: **black** for ``A×B`` or **white** for
``A×(1−B)``.
3. Paint **B**; when ``invert=True``, set ``BM=Difference`` to obtain
``1−B`` from the white background.
4. If A is present, paint it with ``BM=Multiply`` to apply the alpha ramp.
5. Wrap the result as a Form XObject and attach it as ``/SMask`` with
``/S /Luminosity``.
"""
# Decide the canvas/BBox for the soft mask
if region_bbox is not None:
union = region_bbox
else:
bb_A = (
A.bounding_box(Point(0, 0), expand_for_stroke=False)[0] if A else None
)
bb_B = B.bounding_box(Point(0, 0), expand_for_stroke=False)[0]
union = bb_B if bb_A is None else bb_A.merge(bb_B)
canvas = GraphicsContext()
# Background: black for A×B, white for A×(1−B)
bg = PaintedPath()
bg.rectangle(union.x0, union.y0, union.width, union.height)
bg.style.fill_color = "#000000" if not invert else "#ffffff"
bg.style.fill_opacity = 1
bg.style.stroke_color = None
canvas.add_item(bg)
# Paint B (optionally build 1−B using Difference on white bg)
if invert:
B.style.blend_mode = BlendMode.DIFFERENCE
canvas.add_item(B)
# Multiply by A if present
if A is not None:
A.style.blend_mode = BlendMode.MULTIPLY
canvas.add_item(A)
sm = cls(canvas, invert=False, use_luminosity=True)
_ = sm.render(registry)
sm.object_id = registry.register_soft_mask(sm)
return sm
class ImageSoftMask:
"""
Soft mask backed by a grayscale image XObject.
The grayscale image is drawn into a transparency group; the group's luminance
is used as the mask values.
"""
__slots__ = ("image_index", "bbox", "matrix", "object_id")
def __init__(
self,
image_index: int,
bbox: tuple[float, float, float, float],
matrix: Transform,
) -> None:
self.image_index = image_index
self.bbox = bbox
self.matrix = matrix
self.object_id = 0
def serialize(self) -> str:
return f"<</S /Luminosity /G {self.object_id} 0 R>>"
def get_bounding_box(self) -> tuple[float, float, float, float]:
return self.bbox
def render(self, _resource_registry: "ResourceCatalog") -> str:
m = self.matrix
return (
"q "
f"{number_to_str(m.a)} {number_to_str(m.b)} "
f"{number_to_str(m.c)} {number_to_str(m.d)} "
f"{number_to_str(m.e)} {number_to_str(m.f)} cm "
f"/I{self.image_index} Do Q"
)
def get_resource_dictionary(
self,
_gfxstate_objs_per_name: dict[str, PDFObject],
_pattern_objs_per_name: dict[str, PDFObject],
img_objs_per_index: Optional[dict[int, PDFObject]] = None,
) -> str:
if img_objs_per_index is None or self.image_index not in img_objs_per_index:
raise RuntimeError("Soft mask image XObject not registered.")
img_obj = img_objs_per_index[self.image_index]
xobject = (
Name("XObject").serialize()
+ "<<"
+ f"{Name(f'I{self.image_index}').serialize()} {img_obj.id} 0 R"
+ ">>"
)
return "<<" + xobject + ">>"
def _iter_nodes(
node: GraphicsContext | PaintedPath,
) -> Iterator[GraphicsContext | PaintedPath]:
# Yields all GraphicsContext/PaintedPath nodes recursively
if isinstance(node, PaintedPath):
yield node
root_gc = node.get_graphics_context()
for ch in root_gc.path_items:
if isinstance(ch, (GraphicsContext, PaintedPath)):
yield from _iter_nodes(ch)
else:
yield node
for ch in node.path_items:
if isinstance(ch, (GraphicsContext, PaintedPath)):
yield from _iter_nodes(ch)
def _disable_auto_alpha(node: Union[PaintedPath, GraphicsContext]) -> None:
for n in _iter_nodes(node):
if isinstance(n, PaintedPath):
for attr in ("fill_color", "stroke_color"):
col = getattr(n.style, attr)
if isinstance(col, GradientPaint):
# decide from the gradient, not col.has_alpha() (which checks skip_alpha)
if col.gradient and col.gradient.has_alpha():
col.skip_alpha = True
# pylint: disable=protected-access
def clone_structure(
node: GraphicsContext | PaintedPath,
) -> GraphicsContext | PaintedPath:
new: GraphicsContext | PaintedPath
if isinstance(node, GraphicsContext):
new = GraphicsContext()
new.style = deepcopy(node.style)
new.transform = node.transform
new.clipping_path = node.clipping_path
new.path_items = [
(
clone_structure(ch)
if isinstance(ch, (GraphicsContext, PaintedPath))
else ch
)
for ch in node.path_items
]
return new
new = PaintedPath.__new__(PaintedPath)
root = clone_structure(node.get_graphics_context())
object.__setattr__(new, "_root_graphics_context", root)
object.__setattr__(new, "_graphics_context", root)
object.__setattr__(
new, "_closed", node._closed # pyright: ignore[reportPrivateUsage]
)
object.__setattr__(new, "_close_context", root)
object.__setattr__(
new,
"_starter_move",
node._starter_move, # pyright: ignore[reportPrivateUsage]
)
return new
class PaintComposite:
@dataclass(frozen=True)
class _Step:
draw: str # "source" or "backdrop"
mask_from: Optional[str] # "source" | "backdrop" | None
invert: bool = False
_MODES = {
CompositingOperation.SOURCE: (_Step("source", None),),
CompositingOperation.DESTINATION: (_Step("backdrop", None),),
CompositingOperation.SOURCE_OVER: (
_Step("backdrop", None),
_Step("source", None),
),
CompositingOperation.DESTINATION_OVER: (
_Step("source", None),
_Step("backdrop", None),
),
CompositingOperation.SOURCE_IN: (_Step("source", "backdrop"),),
CompositingOperation.DESTINATION_IN: (_Step("backdrop", "source"),),
CompositingOperation.SOURCE_OUT: (_Step("source", "backdrop", True),),
CompositingOperation.DESTINATION_OUT: (_Step("backdrop", "source", True),),
CompositingOperation.SOURCE_ATOP: (
_Step("backdrop", "source", True),
_Step("source", "backdrop"),
),
CompositingOperation.DESTINATION_ATOP: (
_Step("source", "backdrop", True),
_Step("backdrop", "source"),
),
CompositingOperation.XOR: (
_Step("source", "backdrop", True),
_Step("backdrop", "source", True),
),
CompositingOperation.CLEAR: tuple(),
}
def __init__(
self,
backdrop: PaintedPath | GraphicsContext,
source: PaintedPath | GraphicsContext,
operation: CompositingOperation,
):
self.backdrop = backdrop
self.source = source
self.mode = operation
if self.mode not in self._MODES:
raise NotImplementedError(
f"Compositing mode '{self.mode.value}' is not yet supported."
)
@classmethod
def _with_mask(
cls,
path: Union[PaintedPath, GraphicsContext],
mask_from: Union[PaintedPath, GraphicsContext],
invert: bool,
resource_registry: "ResourceCatalog",
) -> PaintedPath | GraphicsContext:
p = deepcopy(path)
A = PaintSoftMask.alpha_layers_from(p)
B = PaintSoftMask.coverage_white(mask_from)
bb_p = p.bounding_box(Point(0, 0), expand_for_stroke=False)[0]
bb_B = B.bounding_box(Point(0, 0), expand_for_stroke=False)[0]
region_bbox = bb_p.merge(bb_B)
sm = PaintSoftMask.from_AB(
A, B, invert, resource_registry, region_bbox=region_bbox
)
p.style.soft_mask = sm
_disable_auto_alpha(p)
return p
def _pick(self, which: str) -> Union[PaintedPath, GraphicsContext]:
return self.source if which == "source" else self.backdrop
def render(
self,
resource_registry: "ResourceCatalog",
style: GraphicsStyle,
last_item: Renderable,
initial_point: Point,
) -> tuple[str, Renderable, Point]:
steps = self._MODES[self.mode]
if not steps: # CLEAR
return "", last_item, initial_point
parts: list[str] = []
for st in steps:
node = self._pick(st.draw)
if st.mask_from is not None:
node = self._with_mask(
node, self._pick(st.mask_from), st.invert, resource_registry
)
s, last_item, initial_point = node.render(
resource_registry, style, last_item, initial_point
)
parts.append(s)
return " ".join(parts), last_item, initial_point
class BlendGroup:
__slots__ = ("context", "base_style", "resources")
def __init__(self, context: GraphicsContext, base_style: GraphicsStyle) -> None:
self.context = context
self.base_style = deepcopy(base_style)
self.resources: set[tuple[PDFResourceType, str]] = set()
def render(self, resource_registry: "ResourceCatalog") -> str:
stream, _, _ = self.context.render(
resource_registry,
style=self.base_style,
last_item=Move(Point(0, 0)),
initial_point=Point(0, 0),
)
self.resources = resource_registry.scan_stream(stream)
return stream
def get_bounding_box(self) -> tuple[float, float, float, float]:
bbox, _ = self.context.bounding_box(
Point(0, 0), style=self.base_style, expand_for_stroke=True
)
if not bbox.is_valid():
return (0.0, 0.0, 0.0, 0.0)
return bbox.to_tuple()
def get_resource_dictionary(
self,
gfxstate_objs_per_name: dict[str, PDFObject],
pattern_objs_per_name: dict[str, PDFObject],
shading_objs_per_name: dict[str, PDFObject],
font_objs_per_index: dict[int, Union["PDFFont", "PDFType3Font"]],
img_objs_per_index: dict[int, PDFObject],
) -> "str":
resources_registered: dict[PDFResourceType, set[str]] = {}
for rtype, resource_id in self.resources:
resources_registered.setdefault(rtype, set()).add(str(resource_id))
parts: list[str] = []
ext_g_states = resources_registered.get(PDFResourceType.EXT_G_STATE)
if ext_g_states:
serialized = "".join(
f"{Name(name).serialize()} {gfxstate_objs_per_name[name].id} 0 R"
for name in sorted(ext_g_states)
if name in gfxstate_objs_per_name
)
if serialized:
parts.append(f"{Name('ExtGState').serialize()}<<{serialized}>>")
patterns = resources_registered.get(PDFResourceType.PATTERN)
if patterns:
serialized = "".join(
f"{Name(name).serialize()} {pattern_objs_per_name[name].id} 0 R"
for name in sorted(patterns)
if name in pattern_objs_per_name
)
if serialized:
parts.append(f"{Name('Pattern').serialize()}<<{serialized}>>")
shadings = resources_registered.get(PDFResourceType.SHADING)
if shadings:
serialized = "".join(
f"{Name(name).serialize()} {shading_objs_per_name[name].id} 0 R"
for name in sorted(shadings)
if name in shading_objs_per_name
)
if serialized:
parts.append(f"{Name('Shading').serialize()}<<{serialized}>>")
fonts = resources_registered.get(PDFResourceType.FONT)
if fonts:
serialized = "".join(
f"{Name(f'F{idx}').serialize()} {font_objs_per_index[int(idx)].id} 0 R"
for idx in sorted(fonts)
if int(idx) in font_objs_per_index
)
if serialized:
parts.append(f"{Name('Font').serialize()}<<{serialized}>>")
xobjects = resources_registered.get(PDFResourceType.X_OBJECT)
if xobjects:
serialized = "".join(
f"{Name(f'I{idx}').serialize()} {img_objs_per_index[int(idx)].id} 0 R"
for idx in sorted(xobjects)
if int(idx) in img_objs_per_index
)
if serialized:
parts.append(f"{Name('XObject').serialize()}<<{serialized}>>")
return "<<" + "".join(parts) + ">>" if parts else "<<>>"
class PaintBlendComposite:
__slots__ = ("backdrop", "source", "blend_mode", "_form_index")
def __init__(
self,
backdrop: GraphicsContext | PaintedPath,
source: GraphicsContext | PaintedPath,
blend_mode: BlendMode,
) -> None:
self.backdrop: Optional[GraphicsContext | PaintedPath] = backdrop
self.source: Optional[GraphicsContext | PaintedPath] = source
self.blend_mode: BlendMode = blend_mode
self._form_index: Optional[int] = None
def _ensure_form_index(
self, resource_registry: "ResourceCatalog", base_style: GraphicsStyle
) -> int:
if self._form_index is not None:
return self._form_index
group = GraphicsContext()
backdrop_node = self.backdrop
source_node = self.source
assert isinstance(backdrop_node, (GraphicsContext, PaintedPath))
assert isinstance(source_node, (GraphicsContext, PaintedPath))
source_node.style.blend_mode = self.blend_mode
if source_node.style.allow_transparency is False:
source_node.style.allow_transparency = GraphicsStyle.INHERIT
group.add_item(backdrop_node, clone=False)
group.add_item(source_node, clone=False)
effective_style = base_style
blend_group = BlendGroup(group, effective_style)
self._form_index = resource_registry.register_blend_form(blend_group)
self.backdrop = None
self.source = None
return self._form_index
def render(
self,
resource_registry: "ResourceCatalog",
style: GraphicsStyle,
last_item: Renderable,
initial_point: Point,
) -> tuple[str, Renderable, Point]:
form_index = self._ensure_form_index(resource_registry, style)
rendered = f"q /I{form_index} Do Q"
return rendered, last_item, initial_point
class PathPen(BasePen): # type: ignore[misc]
def __init__(
self,
pdf_path: ClippingPath | PaintedPath,
glyphSet: Optional[ # pyright: ignore[reportUnknownParameterType]
"ttGlyphSet" # pyright: ignore[reportInvalidTypeForm]
] = None,
) -> None:
self.pdf_path: ClippingPath | PaintedPath = pdf_path
self.last_was_line_to: bool = False
self.first_is_move: Optional[bool] = None
super().__init__(glyphSet=glyphSet) # pyright: ignore[reportUnknownMemberType]
def _moveTo(self, pt: tuple[float, float]) -> None:
self.pdf_path.move_to(*pt)
self.last_was_line_to = False
if self.first_is_move is None:
self.first_is_move = True
def _lineTo(self, pt: tuple[float, float]) -> None:
self.pdf_path.line_to(*pt)
self.last_was_line_to = True
if self.first_is_move is None:
self.first_is_move = False
def _curveToOne(
self,
pt1: tuple[float, float],
pt2: tuple[float, float],
pt3: tuple[float, float],
) -> None:
self.pdf_path.curve_to(
x1=pt1[0], y1=pt1[1], x2=pt2[0], y2=pt2[1], x3=pt3[0], y3=pt3[1]
)
self.last_was_line_to = False
if self.first_is_move is None:
self.first_is_move = False
def _qCurveToOne(self, pt1: tuple[float, float], pt2: tuple[float, float]) -> None:
self.pdf_path.quadratic_curve_to(x1=pt1[0], y1=pt1[1], x2=pt2[0], y2=pt2[1])
self.last_was_line_to = False
if self.first_is_move is None:
self.first_is_move = False
def arcTo(
self,
rx: float,
ry: float,
rotation: float,
arc: bool,
sweep: bool,
end: tuple[float, float],
) -> None:
self.pdf_path.arc_to(
rx=rx,
ry=ry,
rotation=rotation,
large_arc=arc,
positive_sweep=sweep,
x=end[0],
y=end[1],
)
self.last_was_line_to = False
if self.first_is_move is None:
self.first_is_move = False
def _closePath(self) -> None:
# The fonttools parser inserts an unnecessary explicit line back to the start
# point of the path before actually closing it. Let's get rid of that again.
if self.last_was_line_to:
self.pdf_path.remove_last_path_element()
self.pdf_path.close()
class GlyphPathPen(PathPen):
"""A pen that can be used to draw glyphs into a `PaintedPath`."""
def _closePath(self) -> None:
"""
The difference between GlyphPathPen and PathPen is that GlyphPathPen does not
remove the last path element before closing the path.
This last line back to start point is necessary for correctly rendering glyphs.
"""
self.pdf_path.close()
|