1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463
|
package PDF::Builder::Content::Text;
use base 'PDF::Builder::Content';
use strict;
use warnings;
use Carp;
use List::Util qw(min max);
use version;
#use Data::Dumper; # for debugging
# $Data::Dumper::Sortkeys = 1; # hash keys in sorted order
# print Dumper(var); usage of Dumper
# >>>>>>>>>>>>>>>>>> CRITICAL !!!! <<<<<<<<<<<<<<<<<<<<<<
# when update column() tags and CSS with new/changed support, also update
# Column_docs.pm (immediately) and perhaps #195 list (AT release).
# any examples/ changes update Examples on website (AT release)
our $VERSION = '3.028'; # VERSION
our $LAST_UPDATE = '3.028'; # manually update whenever code is changed
my $TextMarkdown = '1.000031'; # minimum version of Text::Markdown;
#my $TextMultiMarkdown = '1.005'; # TBD minimum version of Text::MultiMarkdown;
my $HTMLTreeBldr = '5.07'; # minimum version of HTML::TreeBuilder
=head1 NAME
PDF::Builder::Content::Text - Additional specialized text-related formatting methods
Inherits from L<PDF::Builder::Content>
B<Note:> If you have used some of these methods in PDF::Builder with a
I<graphics>
type object (e.g., $page->gfx()->method()), you may have to change to a I<text>
type object (e.g., $page->text()->method()).
=head1 METHODS
=cut
sub new {
my ($class) = @_;
my $self = $class->SUPER::new(@_);
$self->textstart();
return $self;
}
=head2 Single Lines from a String
=head3 text_left
$width = $content->text_left($text, %opts)
=over
Alias for C<text>. Implemented for symmetry, for those who use a lot of
C<text_center> and C<text_right>, and desire a matching C<text_left>.
Adds text to the page (left justified), at the current position.
Note that there is no maximum width, and nothing to keep you from overflowing
the physical page on the right!
The width used (in points) is B<returned>.
=back
=cut
sub text_left {
my ($self, $text, @opts) = @_;
# override any stray 'align' that got through to here
return $self->text($text, @opts, 'align'=>'l');
}
=head3 text_center
$width = $content->text_center($text, %opts)
=over
As C<text>, but I<centered> on the current point.
Adds text to the page (centered).
The width used (in points) is B<returned>.
=back
=cut
sub text_center {
my ($self, $text, @opts) = @_;
# override any stray 'align' that got through to here
return $self->text($text, @opts, 'align'=>'c');
}
=head3 text_right
$width = $content->text_right($text, %opts)
=over
As C<text>, but right-aligned to the current point.
Adds text to the page (right justified).
Note that there is no maximum width, and nothing to keep you from overflowing
the physical page on the left!
The width used (in points) is B<returned>.
=back
=cut
sub text_right {
my ($self, $text, @opts) = @_;
# override any stray 'align' that got through to here
return $self->text($text, @opts, 'align'=>'r');
}
=head3 text_justified
$width = $content->text_justified($text, $width, %opts)
=over
As C<text>, but stretches text using C<wordspace>, C<charspace>, and (as a
last resort) C<hscale>, to fill the desired
(available) C<$width>. Note that if the desired width is I<less> than the
natural width taken by the text, it will be I<condensed> to fit, using the
same three routines.
The unchanged C<$width> is B<returned>, unless there was some reason to
change it (e.g., overflow).
B<Options:>
=over
=item 'nocs' => value
If this option value is 1 (default 0), do B<not> use any intercharacter
spacing. This is useful for connected characters, such as fonts for Arabic,
Devanagari, Latin cursive handwriting, etc. You don't want to add additional
space between characters during justification, which would disconnect them.
I<Word> (interword) spacing values (explicit or default) are doubled if
nocs is 1. This is to make up for the lack of added/subtracted intercharacter
spacing.
=item 'wordsp' => value
The percentage of one space character (default 100) that is the maximum amount
to add to (each) interword spacing to expand the line.
If C<nocs> is 1, double C<value>.
=item 'charsp' => value
If adding interword space didn't do enough, the percentage of one em (default
100) that is the maximum amount to add to (each) intercharacter spacing to
further expand the line.
If C<nocs> is 1, force C<value> to 0.
=item 'wordspa' => value
If adding intercharacter space didn't do enough, the percentage of one space
character (default 100) that is the maximum I<additional> amount to add to
(each) interword spacing to further expand the line.
If C<nocs> is 1, double C<value>.
=item 'charspa' => value
If adding more interword space didn't do enough, the percentage of one em
(default 100) that is the maximum I<additional> amount to add to (each)
intercharacter spacing to further expand the line.
If C<nocs> is 1, force C<value> to 0.
=item 'condw' => value
The percentage of one space character (default 25) that is the maximum amount
to subtract from (each) interword spacing to condense the line.
If C<nocs> is 1, double C<value>.
=item 'condc' => value
If removing interword space didn't do enough, the percentage of one em
(default 10) that is the maximum amount to subtract from (each) intercharacter
spacing to further condense the line.
If C<nocs> is 1, force C<value> to 0.
=back
If expansion (or reduction) wordspace and charspace changes didn't do enough
to make the line fit the desired width, use C<hscale()> to finish expanding or
condensing the line to fit.
=back
=cut
sub text_justified {
my ($self, $text, $width, %opts) = @_;
# copy dashed option names to the preferred undashed names
if (defined $opts{'-wordsp'} && !defined $opts{'wordsp'}) { $opts{'wordsp'} = delete($opts{'-wordsp'}); }
if (defined $opts{'-charsp'} && !defined $opts{'charsp'}) { $opts{'charsp'} = delete($opts{'-charsp'}); }
if (defined $opts{'-wordspa'} && !defined $opts{'wordspa'}) { $opts{'wordspa'} = delete($opts{'-wordspa'}); }
if (defined $opts{'-charspa'} && !defined $opts{'charspa'}) { $opts{'charspa'} = delete($opts{'-charspa'}); }
if (defined $opts{'-condw'} && !defined $opts{'condw'}) { $opts{'condw'} = delete($opts{'-condw'}); }
if (defined $opts{'-condc'} && !defined $opts{'condc'}) { $opts{'condc'} = delete($opts{'-condc'}); }
if (defined $opts{'-nocs'} && !defined $opts{'nocs'}) { $opts{'nocs'} = delete($opts{'-nocs'}); }
# optional parameters to control how expansion or condensation are done
# 1. expand interword space up to 100% of 1 space
my $wordsp = defined($opts{'wordsp'})? $opts{'wordsp'}: 100;
# 2. expand intercharacter space up to 100% of 1em
my $charsp = defined($opts{'charsp'})? $opts{'charsp'}: 100;
# 3. expand interword space up to another 100% of 1 space
my $wordspa = defined($opts{'wordspa'})? $opts{'wordspa'}: 100;
# 4. expand intercharacter space up to another 100% of 1em
my $charspa = defined($opts{'charspa'})? $opts{'charspa'}: 100;
# 5. condense interword space up to 25% of 1 space
my $condw = defined($opts{'condw'})? $opts{'condw'}: 25;
# 6. condense intercharacter space up to 10% of 1em
my $condc = defined($opts{'condc'})? $opts{'condc'}: 10;
# 7. if still short or long, hscale()
my $nocs = defined($opts{'nocs'})? $opts{'nocs'}: 0;
if ($nocs) {
$charsp = $charspa = $condc = 0;
$wordsp *= 2;
$wordspa *= 2;
$condw *= 2;
}
# with original wordspace, charspace, and hscale settings
# note that we do NOT change any existing charspace here
my $length = $self->advancewidth($text, %opts);
my $overage = $length - $width; # > 0, raw text is too wide, < 0, narrow
my ($i, @chars, $val, $limit);
my $hs = $self->hscale(); # save old settings and reset to 0
my $ws = $self->wordspace();
my $cs = $self->charspace();
$self->hscale(100); $self->wordspace(0); $self->charspace(0);
# not near perfect fit? not within .1 pt of fitting
if (abs($overage) > 0.1) {
# how many interword spaces can we change with wordspace?
my $num_spaces = 0;
# how many intercharacter spaces can be added to or removed?
my $num_chars = -1;
@chars = split //, $text;
for ($i=0; $i<scalar @chars; $i++) {
if ($chars[$i] eq ' ') { $num_spaces++; } # TBD other whitespace?
$num_chars++; # count spaces as characters, too
}
my $em = $self->advancewidth('M');
my $sp = $self->advancewidth(' ');
if ($overage > 0) {
# too wide: need to condense it
# 1. subtract from interword space, up to -$condw/100 $sp
if ($overage > 0 && $num_spaces > 0 && $condw > 0) {
$val = $overage/$num_spaces;
$limit = $condw/100*$sp;
if ($val > $limit) { $val = $limit; }
$self->wordspace(-$val);
$overage -= $val*$num_spaces;
}
# 2. subtract from intercharacter space, up to -$condc/100 $em
if ($overage > 0 && $num_chars > 0 && $condc > 0) {
$val = $overage/$num_chars;
$limit = $condc/100*$em;
if ($val > $limit) { $val = $limit; }
$self->charspace(-$val);
$overage -= $val*$num_chars;
}
# 3. nothing more to do than scale down with hscale()
} else {
# too narrow: need to expand it (usual case)
$overage = -$overage; # working with positive value is easier
# 1. add to interword space, up to $wordsp/100 $sp
if ($overage > 0 && $num_spaces > 0 && $wordsp > 0) {
$val = $overage/$num_spaces;
$limit = $wordsp/100*$sp;
if ($val > $limit) { $val = $limit; }
$self->wordspace($val);
$overage -= $val*$num_spaces;
}
# 2. add to intercharacter space, up to $charsp/100 $em
if ($overage > 0 && $num_chars > 0 && $charsp > 0) {
$val = $overage/$num_chars;
$limit = $charsp/100*$em;
if ($val > $limit) { $val = $limit; }
$self->charspace($val);
$overage -= $val*$num_chars;
}
# 3. add to interword space, up to $wordspa/100 $sp additional
if ($overage > 0 && $num_spaces > 0 && $wordspa > 0) {
$val = $overage/$num_spaces;
$limit = $wordspa/100*$sp;
if ($val > $limit) { $val = $limit; }
$self->wordspace($val+$self->wordspace());
$overage -= $val*$num_spaces;
}
# 4. add to intercharacter space, up to $charspa/100 $em additional
if ($overage > 0 && $num_chars > 0 && $charspa > 0) {
$val = $overage/$num_chars;
$limit = $charspa/100*$em;
if ($val > $limit) { $val = $limit; }
$self->charspace($val+$self->charspace());
$overage -= $val*$num_chars;
}
# 5. nothing more to do than scale up with hscale()
}
# last ditch effort to fill the line: use hscale()
# temporarily resets hscale to expand width of line to match $width
# wordspace and charspace are already (temporarily) at max/min
if ($overage > 0.1) {
$self->hscale(100*($width/$self->advancewidth($text, %opts)));
}
} # original $overage was not near 0
# do the output, with wordspace, charspace, and possibly hscale changed
# override any stray 'align' that got through to here
$self->text($text, %opts, 'align'=>'l');
# restore settings
$self->hscale($hs); $self->wordspace($ws); $self->charspace($cs);
return $width;
} # end of text_justified()
=head2 Multiple Lines from a String
The string is split at regular blanks (spaces), x20, to find the longest
substring that will fit the C<$width>.
If a single word is longer than C<$width>, it will overflow.
To stay strictly within the desired bounds, set the option
C<spillover>=E<gt>0 to disallow spillover.
=head3 Hyphenation
If hyphenation is enabled, those methods which split up a string into multiple
lines (the "text fill", paragraph, and section methods) will attempt to split
up the word that overflows the line, in order to pack the text even more
tightly ("greedy" line splitting). There are a number of controls over where a
word may be split, but note that there is nothing language-specific (i.e.,
following a given language's rules for where a word may be split). This is left
to other packages.
There are hard coded minimums of 2 letters before the split, and 2 letters after
the split. See C<Hyphenate_basic.pm>. Note that neither hyphenation nor simple
line splitting makes any attempt to prevent widows and orphans, prevent
splitting of the last word in a column or page, or otherwise engage in
more desirable I<paragraph shaping>.
=over
=item 'hyphenate' => value
0: no hyphenation (B<default>), 1: do basic hyphenation. Always allows
splitting at a soft hyphen (\xAD). Unicode hyphen (U+2010) and non-splitting
hyphen (U+2011) are ignored as split points.
=item 'spHH' => value
0: do I<not> split at a hard hyphen (x\2D), 1: I<OK to split> (B<default>)
=item 'spOP' => value
0: do I<not> split after most punctuation, 1: I<OK to split> (B<default>)
=item 'spDR' => value
0: do I<not> split after a run of one or more digits, 1: I<OK to split> (B<default>)
=item 'spLR' => value
0: do I<not> split after a run of one or more ASCII letters, 1: I<OK to split> (B<default>)
=item 'spCC' => value
0: do I<not> split in camelCase between a lowercase letter and an
uppercase letter, 1: I<OK to split> (B<default>)
=item 'spRB' => value
0: do I<not> split on a Required Blank ( ), is B<default>.
1: I<OK to split on Required Blank.> Try to avoid this; it is a desperation
move!
=item 'spFS' => value
0: do I<not> split where it will I<just> fit (middle of word!), is B<default>.
1: I<OK to split to just fit the available space.> Try to avoid this; it is a
super desperation move, and the split will probably make no linguistic sense!
=item 'min_prefix' => value
Minimum number of letters I<before> word split point (hyphenation point).
The B<default> is 2.
=item 'min_suffix' => value
Minimum number of letters I<after> word split point (hyphenation point).
The B<default> is 3.
=back
=head3 Methods
=cut
# splits input text (on spaces) into words, glues them back together until
# have filled desired (available) width. return the new line and remaining
# text. runs of spaces should be preserved. if the first word of a line does
# not fit within the alloted space, and cannot be split short enough, just
# accept the overflow.
sub _text_fill_line {
my ($self, $text, $width, $over, %opts) = @_;
# copy dashed option names to the preferred undashed names
if (defined $opts{'-hyphenate'} && !defined $opts{'hyphenate'}) { $opts{'hyphenate'} = delete($opts{'-hyphenate'}); }
if (defined $opts{'-lang'} && !defined $opts{'lang'}) { $opts{'lang'} = delete($opts{'-lang'}); }
if (defined $opts{'-nosplit'} && !defined $opts{'nosplit'}) { $opts{'nosplit'} = delete($opts{'-nosplit'}); }
# options of interest
my $hyphenate = defined($opts{'hyphenate'})? $opts{'hyphenate'}: 0; # default off
#my $lang = defined($opts{'lang'})? $opts{'lang'}: 'en'; # English rules by default
my $lang = 'basic';
#my $nosplit = defined($opts{'nosplit'})? $opts{'nosplit'}: ''; # indexes NOT to split at, given
# as string of integers
# my @noSplit = split /[,\s]+/, $nosplit; # normally empty array
# 1. indexes start at 0 (split after character N not permitted)
# 2. SHYs (soft hyphens) should be skipped
# 3. need to map entire string's indexes to each word under
# consideration for splitting (hyphenation)
# TBD should we consider any non-ASCII spaces?
# don't split on non-breaking space (required blank).
my @txt = split(/\x20/, $text);
my @line = ();
local $"; # intent is that reset of separator ($") is local to block
$"=' '; ## no critic
my $lastWord = ''; # the one that didn't quite fit
my $overflowed = 0;
while (@txt) {
# build up @line from @txt array until overfills line.
# need to remove SHYs (soft hyphens) at this point.
$lastWord = shift @txt; # preserve any SHYs in the word
push @line, (_removeSHY($lastWord));
# one space between each element of line, like join(' ', @line)
$overflowed = $self->advancewidth("@line", %opts) > $width;
last if $overflowed;
}
# if overflowed, and overflow not allowed, remove the last word added,
# unless single word in line and we're not going to attempt word splitting.
if ($overflowed && !$over) {
if ($hyphenate && @line == 1 || @line > 1) {
pop @line; # discard last (or only) word
unshift @txt,$lastWord; # restore with SHYs intact
}
# if not hyphenating (splitting words), just leave oversized
# single-word line. if hyphenating, could have empty @line.
}
my $Txt = "@txt"; # remaining text to put on next line
my $Line = "@line"; # line that fits, but not yet with any split word
# may be empty if first word in line overflows
# if we try to hyphenate, try splitting up that last word that
# broke the camel's back. otherwise, will return $Line and $Txt as is.
if ($hyphenate && $overflowed) {
my $space;
# @line is current whole word list of line, does NOT overflow because
# $lastWord was removed. it may be empty if the first word tried was
# too long. @txt is whole word list of the remaining words to be output
# (includes $lastWord as its first word).
#
# we want to try splitting $lastWord into short enough left fragment
# (with right fragment remainder as first word of next line). if we
# fail to do so, just leave whole word as first word of next line, IF
# @line was not empty. if @line was empty, accept the overflow and
# output $lastWord as @line and remove it from @txt.
if (@line) {
# line not empty. $space is width for word fragment, not
# including blank after previous last word of @line.
$space = $width - $self->advancewidth("@line ", %opts);
} else {
# line empty (first word too long, and we can try hyphenating).
# $space is entire $width available for left fragment.
$space = $width;
}
if ($space > 0) {
my ($wordLeft, $wordRight);
# @line is word(s) (if any) currently fitting within $width.
# @txt is remaining words unused in this line. $lastWord is first
# word of @txt. $space is width remaining to fill in line.
$wordLeft = ''; $wordRight = $lastWord; # fallbacks
# if there is an error in Hyphenate_$lang, the message may be
# that the splitWord() function can't be found. debug errors by
# hard coding the require and splitWord() calls.
## test that Hyphenate_$lang exists. if not, use Hyphenate_en
## TBD: if Hyphenate_$lang is not found, should we fall back to
## English (en) rules, or turn off hyphenation, or do limited
## hyphenation (nothing language-specific)?
# only Hyphenate_basic. leave language support to other packages
require PDF::Builder::Content::Hyphenate_basic;
#eval "require PDF::Builder::Content::Hyphenate_$lang";
#if ($@) {
#print "something went wrong with require eval: $@\n";
#$lang = 'en'; # perlmonks 27443 fall back to English
#require PDF::Builder::Content::Hyphenate_en;
#}
($wordLeft,$wordRight) = PDF::Builder::Content::Hyphenate_basic::splitWord($self, $lastWord, $space, %opts);
#eval '($wordLeft,$wordRight) = PDF::Builder::Content::Hyphenate_'.$lang.'::splitWord($self, "$lastWord", $space, %opts)';
if ($@) { print "something went wrong with eval: $@\n"; }
# $wordLeft is left fragment of $lastWord that fits in $space.
# it might be empty '' if couldn't get a small enough piece. it
# includes a hyphen, but no leading space, and can be added to
# @line.
# $wordRight is the remainder of $lastWord (right fragment) that
# didn't fit. it might be the entire $lastWord. it shouldn't be
# empty, since the whole point of the exercise is that $lastWord
# didn't fit in the remaining space. it will replace the first
# element of @txt (there should be at least one).
# see if have a small enough left fragment of $lastWord to append
# to @line. neither left nor right Word should have full $lastWord,
# and both cannot be empty. it is highly unlikely that $wordLeft
# will be the full $lastWord, but quite possible that it is empty
# and $wordRight is $lastWord.
if (!@line) {
# special case of empty line. if $wordLeft is empty and
# $wordRight is presumably the entire $lastWord, use $wordRight
# for the line and remove it ($lastWord) from @txt.
if ($wordLeft eq '') {
@line = ($wordRight); # probably overflows $width.
shift @txt; # remove $lastWord from @txt.
} else {
# $wordLeft fragment fits $width.
@line = ($wordLeft); # should fit $width.
shift @txt; # replace first element of @txt ($lastWord)
unshift @txt, $wordRight;
}
} else {
# usual case of some words already in @line. if $wordLeft is
# empty and $wordRight is entire $lastWord, we're done here.
# if $wordLeft has something, append it to line and replace
# first element of @txt with $wordRight (unless empty, which
# shouldn't happen).
if ($wordLeft eq '') {
# was unable to split $lastWord into short enough fragment.
# leave @line (already has words) and @txt alone.
} else {
push @line, ($wordLeft); # should fit $space.
shift @txt; # replace first element of @txt (was $lastWord)
unshift @txt, $wordRight if $wordRight ne '';
}
}
# rebuild $Line and $Txt, in case they were altered.
$Txt = "@txt";
$Line = "@line";
} # there was $space available to try to fit a word fragment
} # we had an overflow to clean up, and hyphenation (word splitting) OK
return ($Line, $Txt);
}
# remove soft hyphens (SHYs) from a word. assume is always #173 (good for
# Latin-1, CP-1252, UTF-8; might not work for some encodings) TBD
sub _removeSHY {
my ($word) = @_;
my @chars = split //, $word;
my $out = '';
foreach (@chars) {
next if ord($_) == 173;
$out .= $_;
}
return $out;
}
=head4 text_fill_left, text_fill
($width, $leftover) = $content->text_fill_left($string, $width, %opts)
=over
Fill a line of 'width' with as much text as will fit,
and outputs it left justified.
The width actually used, and the leftover text (that didn't fit),
are B<returned>.
=back
($width, $leftover) = $content->text_fill($string, $width, %opts)
=over
Alias for text_fill_left().
=back
=cut
sub text_fill_left {
my ($self, $text, $width, %opts) = @_;
# copy dashed option names to preferred undashed names
if (defined $opts{'-spillover'} && !defined $opts{'spillover'}) { $opts{'spillover'} = delete($opts{'-spillover'}); }
# 0 = overflow past right margin NOT allowed; 1 = allowed
my $over = defined($opts{'spillover'}) && $opts{'spillover'} == 1;
$over = 0 if $over eq '';
my ($line, $ret) = $self->_text_fill_line($text, $width, $over, %opts);
# override any stray 'align' that got through to here
$width = $self->text($line, %opts, 'align'=>'l');
return ($width, $ret);
}
sub text_fill {
my $self = shift;
return $self->text_fill_left(@_);
}
=head4 text_fill_center
($width, $leftover) = $content->text_fill_center($string, $width, %opts)
=over
Fill a line of 'width' with as much text as will fit,
and outputs it centered.
The width actually used, and the leftover text (that didn't fit),
are B<returned>.
=back
=cut
sub text_fill_center {
my ($self, $text, $width, %opts) = @_;
# copy dashed option names to preferred undashed names
if (defined $opts{'-spillover'} && !defined $opts{'spillover'}) { $opts{'spillover'} = delete($opts{'-spillover'}); }
# 0 = overflow past right margin NOT allowed; 1 = allowed
my $over = defined($opts{'spillover'}) && $opts{'spillover'} == 1;
$over = 0 if $over eq '';
my ($line, $ret) = $self->_text_fill_line($text, $width, $over, %opts);
$width = $self->text_center($line, %opts);
return ($width, $ret);
}
=head4 text_fill_right
($width, $leftover) = $content->text_fill_right($string, $width, %opts)
=over
Fill a line of 'width' with as much text as will fit,
and outputs it right justified.
The width actually used, and the leftover text (that didn't fit),
are B<returned>.
=back
=cut
sub text_fill_right {
my ($self, $text, $width, %opts) = @_;
# copy dashed option names to preferred undashed names
if (defined $opts{'-spillover'} && !defined $opts{'spillover'}) { $opts{'spillover'} = delete($opts{'-spillover'}); }
# 0 = overflow past right margin NOT allowed; 1 = allowed
my $over = defined($opts{'spillover'}) && $opts{'spillover'} == 1;
$over = 0 if $over eq '';
my ($line, $ret) = $self->_text_fill_line($text, $width, $over, %opts);
$width = $self->text_right($line, %opts);
return ($width, $ret);
}
=head4 text_fill_justified
($width, $leftover) = $content->text_fill_justified($string, $width, %opts)
=over
Fill a line of 'width' with as much text as will fit,
and outputs it fully justified (stretched or condensed).
The width actually used, and the leftover text (that didn't fit),
are B<returned>.
Note that the entire line is fit to the available
width via a call to C<text_justified>.
See C<text_justified> for options to control stretch and condense.
The last line is unjustified (normal size) and left aligned by default,
although the option
B<Options:>
=over
=item 'last_align' => place
where place is 'left' (default), 'center', or 'right' (may be shortened to
first letter) allows you to specify the alignment of the last line output.
=back
=back
=cut
sub text_fill_justified {
my ($self, $text, $width, %opts) = @_;
# copy dashed option names to preferred undashed names
if (defined $opts{'-last_align'} && !defined $opts{'last_align'}) { $opts{'last_align'} = delete($opts{'-last_align'}); }
if (defined $opts{'-spillover'} && !defined $opts{'spillover'}) { $opts{'spillover'} = delete($opts{'-spillover'}); }
my $align = 'l'; # default left align last line
if (defined($opts{'last_align'})) {
if ($opts{'last_align'} =~ m/^l/i) { $align = 'l'; }
elsif ($opts{'last_align'} =~ m/^c/i) { $align = 'c'; }
elsif ($opts{'last_align'} =~ m/^r/i) { $align = 'r'; }
else { warn "Unknown last_align for justified fill, 'left' used\n"; }
}
# 0 = overflow past right margin NOT allowed; 1 = allowed
my $over = defined($opts{'spillover'}) && $opts{'spillover'} == 1;
$over = 0 if $over eq '';
my ($line, $ret) = $self->_text_fill_line($text, $width, $over, %opts);
# if last line, use $align (don't justify)
if ($ret eq '') {
my $lw = $self->advancewidth($line, %opts);
# override any stray 'align' that got through to here
if ($align eq 'l') {
$width = $self->text($line, %opts, 'align'=>'l');
} elsif ($align eq 'c') {
$width = $self->text($line, 'indent' => ($width-$lw)/2, %opts, 'align'=>'l');
} else { # 'r'
$width = $self->text($line, 'indent' => ($width-$lw), %opts, 'align'=>'l');
}
} else {
$width = $self->text_justified($line, $width, %opts);
}
return ($width, $ret);
}
=head2 Larger Text Segments
=head3 paragraph
($overflow_text, $unused_height) = $txt->paragraph($text, $width,$height, $continue, %opts)
($overflow_text, $unused_height) = $txt->paragraph($text, $width,$height, %opts)
$overflow_text = $txt->paragraph($text, $width,$height, $continue, %opts)
$overflow_text = $txt->paragraph($text, $width,$height, %opts)
=over
Print a single string into a rectangular area on the page, of given width and
maximum height. The baseline of the first (top) line is at the current text
position.
Apply the text within the rectangle and B<return> any leftover text (if could
not fit all of it within the rectangle). If called in an array context, the
unused height is also B<returned> (may be 0 or negative if it just filled the
rectangle).
C<$continue> is optional, with a default value of 0. An C<%opts> list may be
given after the fixed parameters, whether or not C<$continue> is explicitly
given.
If C<$continue> is 1, the first line does B<not> get special treatment for
indenting or outdenting, because we're printing the continuation of the
paragraph that was interrupted earlier. If it's 0, the first line may be
indented or outdented.
B<Options:>
=over
=item 'pndnt' => $indent
Give the amount of indent (positive) or outdent (negative, for "hanging")
for paragraph first lines. The unit is I<ems>.
This setting is ignored for centered text.
=item 'align' => $choice
C<$choice> is 'justified', 'right', 'center', 'left'; the default is 'left'.
See C<text_justified> call for options to control how a line is expanded or
condensed if C<$choice> is 'justified'. C<$choice> may be shortened to the
first letter.
=item 'last_align' => place
where place is 'left' (default), 'center', or 'right' (may be shortened to
first letter) allows you to specify the alignment of the last line output,
but applies only when C<align> is 'justified'.
=item 'underline' => $distance
=item 'underline' => [ $distance, $thickness, ... ]
If a scalar, distance below baseline,
else array reference with pairs of distance and line thickness.
=item 'spillover' => $over
Controls if words in a line which exceed the given width should be
"spilled over" the bounds, or if a new line should be used for this word.
C<$over> is 1 or 0, with the default 1 (spills over the width).
=back
B<Example:>
$txt->font($font,$fontsize);
$txt->leading($leading);
$txt->translate($x,$y);
$overflow = $txt->paragraph( 'long paragraph here ...',
$width,
$y+$leading-$bottom_margin );
B<Note:> if you need to change any text treatment I<within> a paragraph
(B<bold> or I<italicized> text, for instance), this can not handle it. Only
plain text (all the same font, size, etc.) can be typeset with C<paragraph()>.
Also, there is currently very limited line splitting (hyphenation) to better
fit to a given width, and nothing is done for "widows and orphans".
=back
=cut
# TBD for LTR languages, does indenting on left make sense for right justified?
# TBD for bidi/RTL languages, should indenting be on right?
sub paragraph {
my ($self, $text, $width,$height, @optsA) = @_;
# if odd number of elements in optsA, it contains $continue flag and
# remainder is %opts. if even, paragraph is being called PDF::API2 style
# with no $continue (default to 0).
my $continue = 0;
if (@optsA % 2) {
$continue = splice(@optsA, 0, 1);
}
my %opts = @optsA;
# copy dashed option names to preferred undashed names
if (defined $opts{'-align'} && !defined $opts{'align'}) { $opts{'align'} = delete($opts{'-align'}); }
if (defined $opts{'-pndnt'} && !defined $opts{'pndnt'}) { $opts{'pndnt'} = delete($opts{'-pndnt'}); }
my @line = ();
my $nwidth = 0;
my $leading = $self->leading();
my $align = 'l'; # default left
if (defined($opts{'align'})) {
if ($opts{'align'} =~ /^l/i) { $align = 'l'; }
elsif ($opts{'align'} =~ /^c/i) { $align = 'c'; }
elsif ($opts{'align'} =~ /^r/i) { $align = 'r'; }
elsif ($opts{'align'} =~ /^j/i) { $align = 'j'; }
else { warn "Unknown align value for paragraph(), 'left' used\n"; }
} # default stays at 'l'
my $indent = defined($opts{'pndnt'})? $opts{'pndnt'}: 0;
if ($align eq 'c') { $indent = 0; } # indent/outdent makes no sense centered
my $first_line = !$continue;
my $lw;
my $em = $self->advancewidth('M');
while (length($text) > 0) { # more text to go...
# indent == 0 (flush) all lines normal width
# indent (>0) first line moved in on left, subsequent normal width
# outdent (<0) first line is normal width, subsequent moved in on left
$lw = $width;
if ($indent > 0 && $first_line) { $lw -= $indent*$em; }
if ($indent < 0 && !$first_line) { $lw += $indent*$em; }
# now, need to indent (move line start) right for 'l' and 'j'
if ($lw < $width && ($align eq 'l' || $align eq 'j')) {
$self->cr($leading); # go UP one line
# 88*10 text space units per em, negative to right for TJ
$self->nl(88*abs($indent)); # come down to right line and move right
}
if ($align eq 'j') {
($nwidth,$text) = $self->text_fill_justified($text, $lw, %opts);
} elsif ($align eq 'r') {
($nwidth,$text) = $self->text_fill_right($text, $lw, %opts);
} elsif ($align eq 'c') {
($nwidth,$text) = $self->text_fill_center($text, $lw, %opts);
} else { # 'l'
($nwidth,$text) = $self->text_fill_left($text, $lw, %opts);
}
$self->nl();
$first_line = 0;
# bail out and just return remaining $text if run out of vertical space
last if ($height -= $leading) < 0;
}
if (wantarray) {
# paragraph() called in the context of returning an array
return ($text, $height);
}
return $text;
}
=head3 section, paragraphs
($overflow_text, $continue, $unused_height) = $txt->section($text, $width,$height, $continue, %opts)
$overflow_text = $txt->section($text, $width,$height, $continue, %opts)
=over
The C<$text> contains a string with one or more paragraphs C<$width> wide,
starting at the current text position, with a newline \n between each
paragraph. Each paragraph is output (see C<paragraph>) until the C<$height>
limit is met (a partial paragraph may be at the bottom). Whatever wasn't
output, will be B<returned>.
If called in an array context, the
unused height and the paragraph "continue" flag are also B<returned>.
C<$continue> is 0 for the first call of section(), and then use the value
returned from the previous call (1 if a paragraph was cut in the middle) to
prevent unwanted indenting or outdenting of the first line being printed.
B<Options:>
=over
=item 'pvgap' => $vertical
Additional vertical space (unit: pt) between paragraphs (default 0).
Note that this space will also be added after the last paragraph printed,
B<unless> you give a negative value. The |pvgap| is the value used (positive);
negative tells C<section> I<not> to add the gap (space) after the last
paragraph in the section.
=back
See C<paragraph> for other C<%opts> you can use, such as C<align> and C<pndnt>.
B<Alternate name:> paragraphs
This is for compatibility with PDF::API2, which renamed C<section>.
=back
=cut
# alias for compatibility
sub paragraphs {
return section(@_);
}
sub section {
my ($self, $text, $width,$height, $continue, %opts) = @_;
# copy dashed option names to preferred undashed names
if (defined $opts{'-pvgap'} && !defined $opts{'pvgap'}) { $opts{'pvgap'} = delete($opts{'-pvgap'}); }
my $overflow = ''; # text to return if height fills up
my $pvgap = defined($opts{'pvgap'})? $opts{'pvgap'}: 0;
my $pvgapFlag = ($pvgap >= 0)?1 :0;
$pvgap = abs($pvgap);
# $continue =0 if fresh paragraph, or =1 if continuing one cut in middle
my @paras = split(/\n/, $text);
for (my $i=0; $i<@paras; $i++) {
my $para = $paras[$i];
# regardless of whether we've run out of space vertically, we will
# loop through all the paragraphs requested
# already seen inability to output more text?
# just put unused text back together into the string
# $continue should stay 1
if (length($overflow) > 0) {
$overflow .= "\n" . $para;
next;
}
($para, $height) = $self->paragraph($para, $width,$height, $continue, %opts);
$continue = 0;
if (length($para) > 0) {
# we cut a paragraph in half. set flag that continuation doesn't
# get indented/outdented (continue current left margin)
$overflow .= $para;
$continue = 1;
}
# inter-paragraph vertical space? (0 length $para means that the
# entire paragraph was consumed)
# note that the last paragraph will also get the extra space after it
# and first paragraph did not
# if this is the last paragraph in the section, still want a gap to
# the next section's starting paragraph, so can't simply omit gap.
# however, want to avoid a pending gap (Td) if that's the last of all.
if (length($para) == 0 && $pvgap != 0 &&
($i < scalar(@paras)-1 || $pvgapFlag)) {
# move DOWN page by pvgap amount (is > 0)
$self->cr(-$pvgap); # creates pending Td command
$height -= $pvgap;
}
}
if (wantarray) {
# section() called in the context of returning an array
return ($overflow, $continue, $height);
}
return $overflow;
}
=head3 textlabel
$width = $txt->textlabel($x,$y, $font, $size, $text, %opts)
=over
Place a line of text at an arbitrary C<[$x,$y]> on the page, with various text
settings (treatments) specified in the call.
=over
=item $font
A previously created font.
=item $size
The font size (points).
=item $text
The text to be printed (a single line).
=back
B<Options:>
=over
=item 'rotate' => $deg
Rotate C<$deg> degrees counterclockwise from due East.
=item 'color' => $cspec
A color name or permitted spec, such as C<#CCE840>, for the character I<fill>.
=item 'strokecolor' => $cspec
A color name or permitted spec, such as C<#CCE840>, for the character I<outline>.
=item 'charspace' => $cdist
Additional distance between characters.
=item 'wordspace' => $wdist
Additional distance between words.
=item 'hscale' => $hfactor
Horizontal scaling mode (percentage of normal, default is 100).
=item 'render' => $mode
Character rendering mode (outline only, fill only, etc.). See C<render> call.
=item 'left' => 1
Left align on the given point. This is the default.
=item 'center' => 1
Center the text on the given point.
=item 'right' => 1
Right align on the given point.
=item 'align' => $placement
Alternate to left, center, and right. C<$placement> is 'left' (default),
'center', or 'right'.
=back
Other options available to C<text>, such as underlining, can be used here.
The width used (in points) is B<returned>.
=back
B<Please note> that C<textlabel()> was not designed to interoperate with other
text operations. It is a standalone operation, and does I<not> leave a "next
write" position (or any other setting) for another C<text> mode operation. A
following write will likely be at C<(0,0)>, and not at the expected location.
C<textlabel()> is intended as an "all in one" convenience function for single
lines of text, such as a label on some
graphics, and not as part of putting down multiple pieces of text. It I<is>
possible to figure out the position of a following write (either C<textlabel>
or C<text>) by adding the returned width to the original position's I<x> value
(assuming left-justified positioning).
=cut
sub textlabel {
my ($self, $x,$y, $font, $size, $text, %opts) = @_;
# copy dashed option names to preferred undashed names
if (defined $opts{'-rotate'} && !defined $opts{'rotate'}) { $opts{'rotate'} = delete($opts{'-rotate'}); }
if (defined $opts{'-color'} && !defined $opts{'color'}) { $opts{'color'} = delete($opts{'-color'}); }
if (defined $opts{'-strokecolor'} && !defined $opts{'strokecolor'}) { $opts{'strokecolor'} = delete($opts{'-strokecolor'}); }
if (defined $opts{'-charspace'} && !defined $opts{'charspace'}) { $opts{'charspace'} = delete($opts{'-charspace'}); }
if (defined $opts{'-hscale'} && !defined $opts{'hscale'}) { $opts{'hscale'} = delete($opts{'-hscale'}); }
if (defined $opts{'-wordspace'} && !defined $opts{'wordspace'}) { $opts{'wordspace'} = delete($opts{'-wordspace'}); }
if (defined $opts{'-render'} && !defined $opts{'render'}) { $opts{'render'} = delete($opts{'-render'}); }
if (defined $opts{'-right'} && !defined $opts{'right'}) { $opts{'right'} = delete($opts{'-right'}); }
if (defined $opts{'-center'} && !defined $opts{'center'}) { $opts{'center'} = delete($opts{'-center'}); }
if (defined $opts{'-left'} && !defined $opts{'left'}) { $opts{'left'} = delete($opts{'-left'}); }
if (defined $opts{'-align'} && !defined $opts{'align'}) { $opts{'align'} = delete($opts{'-align'}); }
my $wht;
my %trans_opts = ( 'translate' => [$x,$y] );
my %text_state = ();
$trans_opts{'rotate'} = $opts{'rotate'} if defined($opts{'rotate'});
my $wastext = $self->_in_text_object();
if ($wastext) {
%text_state = $self->textstate();
$self->textend();
}
$self->save();
$self->textstart();
$self->transform(%trans_opts);
$self->fillcolor(ref($opts{'color'}) ? @{$opts{'color'}} : $opts{'color'}) if defined($opts{'color'});
$self->strokecolor(ref($opts{'strokecolor'}) ? @{$opts{'strokecolor'}} : $opts{'strokecolor'}) if defined($opts{'strokecolor'});
$self->font($font, $size);
$self->charspace($opts{'charspace'}) if defined($opts{'charspace'});
$self->hscale($opts{'hscale'}) if defined($opts{'hscale'});
$self->wordspace($opts{'wordspace'}) if defined($opts{'wordspace'});
$self->render($opts{'render'}) if defined($opts{'render'});
if (defined($opts{'right'}) && $opts{'right'} ||
defined($opts{'align'}) && $opts{'align'} =~ /^r/i) {
$wht = $self->text_right($text, %opts);
} elsif (defined($opts{'center'}) && $opts{'center'} ||
defined($opts{'align'}) && $opts{'align'} =~ /^c/i) {
$wht = $self->text_center($text, %opts);
} elsif (defined($opts{'left'}) && $opts{'left'} ||
defined($opts{'align'}) && $opts{'align'} =~ /^l/i) {
# override any stray 'align' that got through to here
$wht = $self->text($text, %opts, 'align'=>'l'); # explicitly left aligned
} else {
# override any stray 'align' that got through to here
$wht = $self->text($text, %opts, 'align'=>'l'); # left aligned by default
}
$self->textend();
$self->restore();
if ($wastext) {
$self->textstart();
$self->textstate(%text_state);
}
return $wht;
}
# --------------------- start of column() section ---------------------------
# WARNING: be sure to keep in synch with changes to POD elsewhere, especially
# Column_docs.pm
=head3 column
See L<PDF::Builder::Content::Column_docs> for documentation.
=cut
# TBD, future:
# * = not official HTML5 or CSS (i.e., an extension)
# perhaps 3.029?
# arbitrary paragraph shapes (path)
# at a minimum, hyphenate-basic usage including &SHY;
# <img>, <sup>, <sub>, <pre>, <nobr>, <br>, <dl>/<dt>/<dd>, <center>*
# <big>*, <bigger>*, <smaller>*, <small>
# <cite>, <q>, <code>, <kbd>, <samp>, <var>
# CSS _expand* to call hscale() and/or condensed/expanded type in get_font()
# (if not doing synfont() call)
# CSS text transform, such as uppercase and lowercase flavors
# CSS em and ex sizes relative to current font size (like %),
# other absolute sizes such as in, cm, mm, px (?)
#
# TBD link page numbers: currently nothing shown ($page_numbers = 0)
# add <_link_page> text</_link_page> inserted BEFORE </_ref>
# page_numbers=1 " on page $fpn" (internal) " on [page $fpn]" (external)
# =2 " on this page" " on previous page" "on following page" etc
# permits user to choose formatting CSS that often will be a bit different
# from rest of link text, such as Roman while link text is italic
# consider $extname of some sort for external links not just [ ] e.g.,
# " on page [$extname $fpn]" extname not necessarily same as file name
# link to id already knows ppn and fpn. link to #p could use an additional
# pass for forward references to get the $fpn. link to ##ND ? might be
# able to determine physical and forrmatted page numbers
# local override (attribute, {&...}) of page_numbers to repair problem areas
#
# possibly...
# <abbr>, <base>, <wbr>
# <article>, <aside>, <section> as predefined page areas?
#
# extensions to HTML and CSS...
# <_sc>* preprocess: around runs of lowercase put <span style="font-size: 80%;
# expand: 110%"> and fold to UPPER CASE. this is post-mytext creation!
# <_pc>* (Petite case) like <sc> but 1ex font-size, expand 120%
# <_dc>* drop caps
# <_ovl>* overline (similar to underline) using CSS text-decoration: overline
# <_k>* kern text (shift left or right) with CSS _kern, or general
# positioning: ability to form (La)TeX logo through character positioning
# what to do at HTML level? x+/- %fs, y+/- %fs
# also useful for <sup>4</sup><sub>2</sub>He notation
# <_vfrac>* vulgar fraction, using sup, sup, kern
# HTML attributes to tune (force end) of something, such as early </sc>
# after X words and/or end of line. flag to ignore next </sc> coming up,
# or just make self-closing with children?
# <_endc>* force end of column here (at this y, while still filling line)
# e.g., to prevent an orphan. optional conditional (e.g., less than 1"
# of vertical space left in column)
# <_keep>* material to keep together, such as headings and paragraph text
# leading (line-height) as a dimension instead of a ratio, convert to ratio
#
# 3.030 or later?
# left/right auto margins? <center> may need this
# Text::KnuthLiang hyphenation
# <hyp>*, <nohyp>* control hypenation in a word (and remember
# rules when see this word again)
# <lang>* define language of a span of text, for hyphenation/audio purposes
# Knuth-Plass paragraph shaping (with proper hyphenation)
# HarfBuzz::Shaper for ligatures, callout of specific glyphs (not entities),
# RTL and non-Western language support. <bdi>, <bdo>
# <nolig></nolig>* forbid ligatures in this range
# <lig gid='nnn'> </lig>* replace character(s) by a ligature
# <alt gid='nnn'> </alt>* replace character(s) by alternate glyph
# such as a swash. font-dependent
# <eqn>* (needs image support, SVG processing)
sub column {
my ($self, $page, $text, $grfx, $markup, $txt, %opts) = @_;
my $pdf = $self->{' api'}->{' FM'}->{' pdf'};
my $rc = 0; # so far, a normal call with input completely consumed
my $unused = undef;
# array[1] will be consolidated CSS from any <style> tags
my ($x, $y);
my $font_size = 12; # basic default, override with font-size
#if ($text->{' fontsize'} > 0) { $font_size = $text->{' fontsize'}; } # already defined font size?
if (defined $opts{'font_size'}) { $font_size = $opts{'font_size'}; }
my $leading = 1.125; # basic default, override with line-height
if (defined $opts{'leading'}) { $leading=$opts{'leading'}; }
my $marker_width = 1*$font_size; # 2em space for list markers
my $marker_gap = $font_size; # 1em space between list marker and item
if (defined $opts{'marker_width'}) { $marker_width=$opts{'marker_width'}; }
if (defined $opts{'marker_gap'}) { $marker_gap=$opts{'marker_gap'}; }
my $page_numbers = 0; # default: formatted pgno not used in links (TBD)
#if (defined $opts{'page_numbers'}) { $page_numbers=$opts{'page_numbers'}; }
my $restore = 0; # restore text state and color at end
if (defined $opts{'restore'}) { $restore = $opts{'restore'}; }
my @entry_state = (); # font state, color and graphics color
push @entry_state, $text->{' font'}; # initially may be undef, then hashref
push @entry_state, $text->{' fontsize'}; # initially 0
push @entry_state, $text->{' fillcolor'}; # an arrayref, often single number or string
push @entry_state, $text->{' strokecolor'}; # an arrayref, often single number or string
if (defined $grfx && ref($grfx) =~ m/^PDF::Builder::Content=HASH/){
# we have a valid grfx, so can use its values
push @entry_state, $grfx->{' fillcolor'}; # an array, often single number or string
push @entry_state, $grfx->{' strokecolor'}; # an array, often single number or string
} else {
# no grfx, so use undef for values
push @entry_state, undef;
push @entry_state, undef;
}
# fallback CSS properties, inserted at array[0]
my $default_css = _default_css($pdf, $text, $font_size, $leading, %opts); # per-tag properties
# dump @mytext list within designated column @outline
# for now, the outline is a simple rectangle
my $outline_color = 'none'; # optional outline of the column
$outline_color = $opts{'outline'} if defined $opts{'outline'};
# define coordinates of column, currently just 'rect' rectangle, but
# in future could be very elaborate
my @outline = _get_column_outline($grfx, $outline_color, %opts);
my ($col_min_x, $col_min_y, $col_max_x, $col_max_y) =
_get_col_extents(@outline);
my $start_y = $col_max_y; # default is at top of column
my $topCol = 1; # paragraph is at top of column, don't use margin-top
$start_y = $opts{'start_y'} if defined $opts{'start_y'};
if ($start_y != $col_max_y) {
# topCol reset to 0 b/c not at top of column
$topCol = 0; # go ahead with any extra top margin
}
# 'page' parameters
my ($pass_count, $max_passes, $ppn, $extfilepath, $fpn, $LR, $bind);
$ppn = $extfilepath = $fpn = undef;
# physical page number 1,2,..., filepath/name/ext for THIS output,
# formatted page number string (all for link creation)
$LR = 'R'; # for now, just right-hand page
$bind = 0; # for now, offset column by 0 points to "outside" of page
if (defined $opts{'page'}) {
if (!( ref($opts{'page'}) eq 'ARRAY' &&
7 == @{$opts{'page'}} )) {
carp "page not anonymous array of length 7, ignored.";
} else {
$pass_count = $opts{'page'}->[0];
$max_passes = $opts{'page'}->[1];
$ppn = $opts{'page'}->[2];
if (defined $ppn && $ppn !~ /^[1-9]\d*$/) {
carp "physical page number must be integer > 0";
$ppn = 1;
}
$extfilepath = $opts{'page'}->[3];
# external name for THIS output (other docs can link to it)
# undef OK, if will never link to this from outside. this name
# is the path and name of this output file in its FINAL home,
# not necessarily where it is created!
$fpn = $opts{'page'}->[4];
# formatted page string (THIS page)
$LR = $opts{'page'}->[5];
if (!defined $LR) { $LR = 'R'; }
if (defined $LR && $LR ne 'L' && $LR ne 'R') {
carp "LR setting should be L or R. force to R";
$LR = 'R';
}
# TBD handle 'L' and 'R', for now ignore $LR
$bind = $opts{'page'}->[6];
# TBD for now, ignore $bind
}
} else {
# for situations where $opts{'page'} is not passed in because
# we're not doing links and similar. some will be used.
$pass_count = 1;
$max_passes = 1;
$ppn = 1;
$extfilepath = '';
$fpn = '1';
$LR = 'R';
$bind = 0;
}
# what is the state of %state parameter (hashref $state)
my $state = undef; # OK, but xrefs and other links disallowed!
# TBD everywhere $state used, check if defined!
# disable all the _ref and _reft stuff if no state
if (defined $opts{'state'} && ref($opts{'state'}) eq 'HASH') {
$state = $opts{'state'};
# TBD {source} {target} {params} to read in, write out
# before first pass of first PDF (if multiple), external initialize
}
# what is the content of $text: string, array, or array of hashes?
# (or already set up, per 'pre' markup)
# break up text into array of hashes so we have one common input
my @mytext = _break_text($txt, $markup, %opts,'page_numbers'=>$page_numbers);
unshift @mytext, $default_css;
# each element of mytext is an anonymous hash, with members text=>text
# content, font_size, color, font, variants, etc.
#
# if markup=pre, it's already in final form (array of hashes)
# if none, separate out paragraphs into array of hashes
# if md1 or md2, convert to HTML (error if no converter)
# if html, need to interpret (error if no converter)
# finally, resulting array of hashes is interpreted and fit in column
# process style attributes, tag attributes, style tags, column() options,
# and fixed default attributes in that order to fill in each tag's
# attribute list. on exit from tag, set attributes to restore settings
@mytext = _tag_attributes($markup, @mytext);
_check_CSS_properties(@mytext);
($rc, $start_y, $unused) = _output_text($start_y, $col_min_y, \@outline, $pdf, $page, $text, $grfx, $restore, $topCol, $font_size, $markup, $marker_width, $marker_gap, $leading, $opts{'page'}, $page_numbers, $pass_count, $max_passes, $state, @mytext);
if ($rc > 1) {
# restore = 2 request restore to @entry_state for rc=0, 3 for 1
$text->{' font'} = $entry_state[0];
$text->{' fontsize'} = $entry_state[1];
$text->{' fillcolor'} = $entry_state[2];
$text->{' strokecolor'} = $entry_state[3];
if (defined $grfx && ref($grfx) =~ m/^PDF::Builder::Content=HASH/){
# we have a valid grfx, so can use its values
$grfx->{' fillcolor'} = $entry_state[4];
$grfx->{' strokecolor'} = $entry_state[5];
} else {
# no grfx, so do nothing
}
$rc -= 2;
}
return ($rc, $start_y, $unused);
} # end of column()
# set up an element containing all the default settings, as well as those
# passed in by column() parameters and options. this is generated once for
# each call to column, in case any parameters or options change.
sub _default_css {
my ($pdf, $text, $font_size, $leading, %opts) = @_;
# font size is known
# if user wishes to set font OUTSIDE of column
# if FontManager called outside column() and wish to inherit settings for
# face, style, weight, color (fill), 'font_info'=>'-fm-'
# if FontManager NOT used to set font externally, can just inherit font
# (don't know what it is), current font = -external-. all styles and
# weights are this one font
# otherwise, 'font_info'=>'face:style:weight:color' where style = italic
# or normal, weight = bold or normal, color = a color name e.g., black.
# this face must be known to FontManager
# as last resort, if font not set outside of column, FontManager default
my (@cur_font, @cur_color, $current_color);
if (!defined $opts{'font_info'}) {
# default action: -fm-
$opts{'font_info'} = '-fm-';
}
# override any predefined font
if ($opts{'font_info'} eq '-fm-') {
# use whatever FontManager thinks is the default font
$pdf->get_font('face'=>'default'); # set current font to default
@cur_font = $pdf->get_font();
$cur_font[1] = $cur_font[2] = 0; # no italic or bold
# use [0..2] of returned array
} elsif ($opts{'font_info'} eq '-ext-') {
# requesting preloaded font, as '-external-'
# there IS a predefined font, from somewhere, to use?
if ($pdf->get_external_font($text)) {
# failed to find a predefined font. use default
$pdf->get_font('face'=>'default'); # set current font to default
}
@cur_font = $pdf->get_font(); # use [0..2] of returned array,
# either predefined -external- font, or default font
} else {
# explicitly given font must be KNOWN to FontManager
# family:style:weight:color (normal/0/italic/1, normal/0/bold/1)
@cur_font = split /:/, $opts{'font_info'};
# add normal style and weight if not given
if (@cur_font == 2) { push @cur_font, 0; }
if (@cur_font == 1) { push @cur_font, 0,0; }
if ("$cur_font[1]" eq 'normal') { $cur_font[1] = 0; }
if ("$cur_font[1]" eq 'italic') { $cur_font[1] = 1; }
if ("$cur_font[2]" eq 'normal') { $cur_font[2] = 0; }
if ("$cur_font[2]" eq 'bold' ) { $cur_font[2] = 1; }
# set the current font
if (@cur_font == 4) { $text->fillcolor($cur_font[3]); } # color
$pdf->get_font('face'=>$cur_font[0],
'italic'=>$cur_font[1],
'bold'=>$cur_font[2]);
@cur_font = $pdf->get_font();
}
# @cur_font should have (at least) face, italic 0/1, bold 0/1
# to load into 'body' properties later
@cur_color = $text->fillcolor();
# if (defined $opts{'font_color'}) {
# # request override of current text color on entry
# @cur_color = ($opts{'font_color'});
# }
if (@cur_color == 1) {
# 'name', '#rrggbb' etc. suitable for CSS usage
# TBD: single gray scale value s/b changed to '#rrggbb'
# (might be 0..1, 0..100, 0..ff)? 0 = black
$current_color = $cur_color[0];
} else {
# returned an array of values, unsuitable for CSS
# TBD: 3 values 0..1 turn into #rrggbb
# TBD: 3 values 0..100 turn into #rrggbb
# TBD: 3 values 0..ff turn into #rrggbb
# TBD: 4 values like 3, but CMYK
# for now, default to 'black'
$current_color = 'black';
}
my %style;
$style{'tag'} = 'defaults';
$style{'text'} = '';
$style{'body'} = {};
$style{'p'} = {};
$style{'ol'} = {};
$style{'ul'} = {};
$style{'_sl'} = {};
$style{'h1'} = {};
$style{'h2'} = {};
$style{'h3'} = {};
$style{'h4'} = {};
$style{'h5'} = {};
$style{'h6'} = {};
$style{'i'} = {};
$style{'em'} = {};
$style{'b'} = {};
$style{'strong'} = {};
$style{'code'} = {};
$style{'hr'} = {};
$style{'a'} = {};
$style{'_ref'} = {};
$style{'_reft'} = {}; # no visible content
$style{'_nameddest'} = {}; # no visible content
$style{'body'}->{'font-size'} = $font_size; # must be in points
$style{'body'}->{'_parent-fs'} = $font_size; # carry current value
$style{'body'}->{'line-height'} = $leading;
# HARD-CODED default for paragraph indent, top margin
my $para = [ 1, 1*$font_size, 0 ];
# if font_size changes, change indentation
# REVISED default if 'para' option given
if (defined $opts{'para'}) {
#$para->[0] # flag: 0 = <p> is normal top of paragraph (with indent
# and margin), 1 = at top of column, so suppress extra top margin
# (and reset once past this first line)
$para->[1] = $opts{'para'}->[0]; # indentation
$para->[2] = $opts{'para'}->[1]; # extra top margin
}
# $para flag determines whether these settings are used or ignored (=1,
# we are at the top of a column, ignore text-indent and margin-top)
# set paragraph CSS defaults, may be overridden below
$style{'p'}->{'text-indent'} = $para->[1];
$style{'p'}->{'margin-top'} = $para->[2];
my $color = $current_color; # text default color
$color = $opts{'color'} if defined $opts{'color'};
$style{'body'}->{'color'} = $color;
# now for fixed settings
$style{'body'}->{'font-family'} = $cur_font[0]; # face
$style{'body'}->{'font-style'} = $cur_font[1]? 'italic': 'normal';
# TBD future: multiple gradations of weight, numeric and named
$style{'body'}->{'font-weight'} = $cur_font[2]? 'bold': 'normal';
#$style{'body'}->{'font-variant'} = 'normal'; # small-caps, petite caps
# TBD future: optical size select subfont, slant separate from italic flagm,
# stretch amount (expand/condense)
# TBD future: 'margin' consolidated entry
$style{'body'}->{'margin-top'} = '0';
$style{'body'}->{'margin-right'} = '0';
$style{'body'}->{'margin-bottom'} = '0';
$style{'body'}->{'margin-left'} = '0';
$style{'body'}->{'_left'} = '0';
$style{'body'}->{'_left_nest'} = '0';
$style{'body'}->{'_right'} = '0';
$style{'body'}->{'text-indent'} = '0';
$style{'body'}->{'text-align'} = 'left';
#$style{'body'}->{'text-transform'} = 'none'; # capitalize, uppercase, lowercase
#$style{'body'}->{'border-style'} = 'none'; # solid, dotted, dashed... TBD
#$style{'body'}->{'border-width'} = '1pt';
#$style{'body'}->{'border-color'} = 'inherit';
# TBD border-* individually specify for top/right/bottom/left
# also 'border' consolidated entry
$style{'body'}->{'text-decoration'} = 'none';
$style{'body'}->{'display'} = 'block';
$style{'body'}->{'width'} = '-1'; # used for <hr> length in pts, -1 is full column
$style{'body'}->{'height'} = '-1'; # used for <hr> size (thickness) in pts
$style{'body'}->{'_href'} = '';
$style{'body'}->{'_marker-before'} = '';
$style{'body'}->{'_marker-after'} = '.';
$style{'body'}->{'_marker-color'} = '';
$style{'body'}->{'_marker-font'} = '';
$style{'body'}->{'_marker-size'} = $font_size;
$style{'body'}->{'_marker-style'} = '';
$style{'body'}->{'_marker-text'} = '';
$style{'body'}->{'_marker-weight'} = '';
$style{'body'}->{'_marker-align'} = 'right';
$style{'p'}->{'display'} = 'block';
$style{'font'}->{'display'} = 'inline';
$style{'span'}->{'display'} = 'inline';
$style{'ul'}->{'list-style-type'} = '.u';
# disc, circle, square, box, none
$style{'ul'}->{'list-style-position'} = 'outside'; # or inside or numeric
$style{'ul'}->{'display'} = 'block';
# TBD future: padding and padding-*
$style{'ul'}->{'margin-top'} = '50%'; # relative to text's font-size
$style{'ul'}->{'margin-bottom'} = '50%';
$style{'ul'}->{'_marker-font'} = 'ZapfDingbats';
$style{'ul'}->{'_marker-style'} = 'normal';
$style{'ul'}->{'_marker-weight'} = 'bold';
$style{'ul'}->{'_marker-size'} = "50%";
$style{'ul'}->{'_marker-align'} = "right";
$style{'_sl'}->{'list-style-type'} = 'none';
$style{'_sl'}->{'list-style-position'} = 'outside'; # or inside or numeric
$style{'_sl'}->{'display'} = 'block';
$style{'_sl'}->{'margin-top'} = '50%'; # relative to text's font-size
$style{'_sl'}->{'margin-bottom'} = '50%';
$style{'ol'}->{'list-style-type'} = '.o';
# decimal, lower-roman, upper-roman, lower-alpha, upper-alpha, none
# arabic is synonym for decimal
$style{'ol'}->{'list-style-position'} = 'outside'; # or inside or numeric
$style{'ol'}->{'display'} = 'block';
$style{'ol'}->{'margin-top'} = '50%'; # relative to text's font-size
$style{'ol'}->{'margin-bottom'} = '50%';
$style{'ol'}->{'_marker-before'} = ''; # content to add before marker
$style{'ol'}->{'_marker-after'} = '.'; # content to add after marker
$style{'ol'}->{'_marker-font'} = ''; # unchanged
$style{'ol'}->{'_marker-style'} = 'normal';
$style{'ol'}->{'_marker-weight'} = 'bold';
$style{'ol'}->{'_marker-size'} = '100%';
$style{'ol'}->{'_marker-align'} = "right";
$style{'li'}->{'display'} = 'inline'; # should inherit from ul or ol
# marker is block, forcing new line, and li immediately follows
#$style{'h6'}->{'text-transform'} = 'uppercase'; # heading this level CAPS
$style{'h6'}->{'font-weight'} = 'bold'; # all headings bold
$style{'h6'}->{'font-size'} = '75%'; # % of original font-size
$style{'h6'}->{'margin-top'} = '106%'; # relative to the font-size
$style{'h6'}->{'margin-bottom'} = '80%'; # relative to the font-size
$style{'h6'}->{'display'} = 'block'; # block (start on new line)
$style{'h5'}->{'font-weight'} = 'bold';
$style{'h5'}->{'font-size'} = '85%';
$style{'h5'}->{'margin-top'} = '95%';
$style{'h5'}->{'margin-bottom'} = '71%';
$style{'h5'}->{'display'} = 'block';
$style{'h4'}->{'font-weight'} = 'bold';
$style{'h4'}->{'font-size'} = '95%';
$style{'h4'}->{'margin-top'} = '82%';
$style{'h4'}->{'margin-bottom'} = '61%';
$style{'h4'}->{'display'} = 'block';
$style{'h3'}->{'font-weight'} = 'bold';
$style{'h3'}->{'font-size'} = '115%';
$style{'h3'}->{'margin-top'} = '68%';
$style{'h3'}->{'margin-bottom'} = '51%';
$style{'h3'}->{'display'} = 'block';
$style{'h2'}->{'font-weight'} = 'bold';
$style{'h2'}->{'font-size'} = '150%';
$style{'h2'}->{'margin-top'} = '54%';
$style{'h2'}->{'margin-bottom'} = '40%';
$style{'h2'}->{'display'} = 'block';
$style{'h1'}->{'font-weight'} = 'bold';
$style{'h1'}->{'font-size'} = '200%';
$style{'h1'}->{'margin-top'} = '40%';
$style{'h1'}->{'margin-bottom'} = '30%';
$style{'h1'}->{'display'} = 'block';
$style{'i'}->{'font-style'} = 'italic';
$style{'i'}->{'display'} = 'inline';
$style{'b'}->{'font-weight'} = 'bold';
$style{'b'}->{'display'} = 'inline';
$style{'em'}->{'font-style'} = 'italic';
$style{'em'}->{'display'} = 'inline';
$style{'strong'}->{'font-weight'} = 'bold';
$style{'strong'}->{'display'} = 'inline';
$style{'code'}->{'display'} = 'inline';
$style{'code'}->{'font-family'} = 'Courier'; # TBD why does ' default-constant' fail?
$style{'code'}->{'font-size'} = '85%';
$style{'u'}->{'display'} = 'inline';
$style{'u'}->{'text-decoration'} = 'underline';
$style{'ins'}->{'display'} = 'inline';
$style{'ins'}->{'text-decoration'} = 'underline';
$style{'s'}->{'display'} = 'inline';
$style{'s'}->{'text-decoration'} = 'line-through';
$style{'strike'}->{'display'} = 'inline';
$style{'strike'}->{'text-decoration'} = 'line-through';
$style{'del'}->{'display'} = 'inline';
$style{'del'}->{'text-decoration'} = 'line-through';
# non-standard tag for overline TBD
#$style{'_ovl'}->{'display'} = 'inline';
#$style{'_ovl'}->{'text-decoration'} = 'overline';
# non-standard tag for kerning (+ font-size fraction to move left, - right)
# e.g., for vulgar fraction adjust / and denominator <sub> TBD
#$style{'_k'}->{'display'} = 'inline';
#$style{'_k'}->{'_kern'} = '0.2';
$style{'hr'}->{'display'} = 'block';
$style{'hr'}->{'height'} = '0.5'; # 1/2 pt default thickness
$style{'hr'}->{'width'} = '-1'; # default width is full column
$style{'hr'}->{'margin-top'} = '100%';
$style{'hr'}->{'margin-bottom'} = '100%';
$style{'blockquote'}->{'display'} = 'block';
$style{'blockquote'}->{'margin-top'} = '56%';
$style{'blockquote'}->{'margin-bottom'} = '56%';
$style{'blockquote'}->{'margin-left'} = '300%'; # want 3em TBD
$style{'blockquote'}->{'margin-right'} = '300%';
$style{'blockquote'}->{'line-height'} = '1.00'; # close spacing
$style{'blockquote'}->{'font-size'} = '80%'; # smaller type
# only browser (URL) applies here, so leave browser style
# other links changed to '_ref', with its own style
$style{'a'}->{'text-decoration'} = 'underline'; # browser style
# none, underline, overline, line-through or a combination
# separated by spaces
$style{'a'}->{'color'} = 'blue';
$style{'a'}->{'display'} = 'inline';
$style{'a'}->{'_href'} = '';
$style{'_ref'}->{'color'} = '#660066'; # default link for xrefs
$style{'_ref'}->{'font-style'} = 'italic';
$style{'_ref'}->{'display'} = 'inline';
# <_reft> and <_nameddest> no visible content, so no styling
#$style{'sc'}->{'font-size'} = '80%'; # smaller type TBD
#$style{'sc'}->{'_expand'} = '110%'; # wider type TBD _expand
#likewise for pc (petite caps) TBD
$style{'_marker'}->{'display'} = 'block';
$style{'_marker'}->{'text-align'} = 'right'; # overwrite with _marker-align
# _marker-align defaulted 'right' in 'ul' and 'ol', N/A in '_sl'
# can set properties in <ol> or <ul> to apply to entire list (inherited)
# this is why unique CSS names _marker-* is needed rather than std names
return \%style;
} # end of _default_css()
# make sure each tag's attributes are proper property names
# consolidate attributes and style attribute (if any)
# mark empty tags (no explicit end tag will be found)
#
# also insert <_marker> tag before every <li> lacking an explicit one
sub _tag_attributes {
my ($markup, @mytext) = @_;
# start at [2], so defaults and styles skipped
for (my $el=2; $el < @mytext; $el++) {
if (ref($mytext[$el]) ne 'HASH') { next; }
if ($mytext[$el]->{'tag'} eq '') { next; }
my $tag = lc($mytext[$el]->{'tag'});
if (!defined $tag) { next; }
if ($tag =~ m#^/#) { next; }
# we have a tag that might have one or more attributes that may
# need to be renamed as a CSS property
if ($tag eq 'font') {
if (defined $mytext[$el]->{'face'}) {
$mytext[$el]->{'font-family'} = delete($mytext[$el]->{'face'});
}
if (defined $mytext[$el]->{'size'}) {
$mytext[$el]->{'font-size'} = delete($mytext[$el]->{'size'});
# TBD some sizes may need to be converted to points. for now,
# assume is a bare number (pt), pt, or % like font-size CSS
}
} elsif ($tag eq 'ol') {
if (defined $mytext[$el]->{'type'}) {
$mytext[$el]->{'list-style-type'} = delete($mytext[$el]->{'type'});
}
# note that list-style-type would be aAiI1
# 'start' left unchanged
} elsif ($tag eq 'ul') {
if (defined $mytext[$el]->{'type'}) {
$mytext[$el]->{'list-style-type'} = delete($mytext[$el]->{'type'});
}
} elsif ($tag eq 'li') {
#if (defined $mytext[$el]->{'type'}) {
# $mytext[$el]->{'list-style-type'} = delete($mytext[$el]->{'type'});
#}
# 'value' left unchanged, to be used by <_marker> before this <li>
# 'type' to be used by <_marker> (both, under <ol> only)
} elsif ($tag eq 'a') {
if (defined $mytext[$el]->{'href'}) {
$mytext[$el]->{'_href'} = delete($mytext[$el]->{'href'});
}
} elsif ($tag eq 'hr') {
if (defined $mytext[$el]->{'size'}) {
$mytext[$el]->{'height'} = delete($mytext[$el]->{'size'});
}
}
# add any additional tag attributes -> CSS property here
# process any style attribute and override attribute values
if (defined $mytext[$el]->{'style'}) {
my $style_attr = _process_style_string({}, $mytext[$el]->{'style'});
# hash of property_name => value pairs
foreach (keys %$style_attr) {
# create or override any existing property by this name
$mytext[$el]->{$_} = $style_attr->{$_};
}
}
# list-style-type for ol/ul/li needs fleshing out
if (defined $mytext[$el]->{'list-style-type'}) {
if ($mytext[$el]->{'list-style-type'} eq '1') {
$mytext[$el]->{'list-style-type'} = 'decimal';
} elsif ($mytext[$el]->{'list-style-type'} eq 'A') {
$mytext[$el]->{'list-style-type'} = 'upper-alpha';
} elsif ($mytext[$el]->{'list-style-type'} eq 'a') {
$mytext[$el]->{'list-style-type'} = 'lower-alpha';
} elsif ($mytext[$el]->{'list-style-type'} eq 'I') {
$mytext[$el]->{'list-style-type'} = 'upper-roman';
} elsif ($mytext[$el]->{'list-style-type'} eq 'i') {
$mytext[$el]->{'list-style-type'} = 'lower-roman';
} elsif ($mytext[$el]->{'list-style-type'} eq 'upper-latin') {
$mytext[$el]->{'list-style-type'} = 'upper-alpha';
} elsif ($mytext[$el]->{'list-style-type'} eq 'lower-latin') {
$mytext[$el]->{'list-style-type'} = 'lower-alpha';
}
# note that there are dozens more valid order list formats that
# are NOT currenty supported (TBD). also, although upper/lower-
# latin is valid, the code is expecting alpha
}
# VOID elements (br, hr, img, area, base, col, embed, input,
# link, meta, source, track, wbr) do not have a separate end
# tag (no children). also incude style and defaults in this list in
# case a stray one shows up (does not have an end tag). this is NOT
# really "self-closing", although the terms are often used
# interchangeably.
if ($tag eq 'br' || $tag eq 'hr' || $tag eq 'img' || $tag eq 'area' ||
$tag eq 'base' || $tag eq 'col' || $tag eq 'embed' ||
$tag eq 'input' || $tag eq 'link' || $tag eq 'meta' ||
$tag eq 'source' || $tag eq 'track' || $tag eq 'wbr' ||
$tag eq 'defaults' || $tag eq 'style') {
$mytext[$el]->{'empty_element'} = 1;
}
# 'next' to here
} # for loop through all user-defined elements
return @mytext;
} # end of _tag_attributes()
# go through <style> tags (element 1) and all element style tags (elements 2+)
# and find any bogus CSS property names. assume anything built into the code
# (defaults, etc.) is legitimate -- this is only for user-supplied CSS.
sub _check_CSS_properties {
my @mytext = @_;
my ($tag, $style, $stylehash);
my @supported_properties = qw(
color font-size line-height margin-top margin-right margin-bottom
margin-left text-indent text-align font-family font-weight font-style
display height width text-decoration _marker-before _marker-after
_marker-color _marker-font _marker-size _marker-style _marker-text
_marker-weight _marker-align list-style-type list-style-position
);
# 1. element 0 is default CSS, no need to check.
# element 1 is user-supplied <style> tags and style=> column() option.
# should be tag=>'style' and 'text'=>''
foreach my $tagname (keys %{ $mytext[1] }) {
if ($tagname eq 'tag') { next; }
if ($tagname eq 'text') { next; }
#print "tagname <$tagname> check\n";
foreach my $propname (keys %{ $mytext[1]->{$tagname} }) {
#print "checking <$tagname> property '$propname'\n";
my $found = 0;
for (my $sup=0; $sup < @supported_properties; $sup++) {
if ($propname eq $supported_properties[$sup]) {
$found = 1;
last;
}
}
if (!$found) {
print STDERR "Warning: CSS property name '$propname' found in style option or <style>\n is either invalid, or is unsupported by PDF::Builder.\n";
}
#my $style_string = $mytext[1]->{$sel}; TBD check value
}
}
# 2. elements 2 and up are tags and text. check tags for style attribute
# and check property names there
for (my $el = 2; $el < @mytext; $el++) {
$tag = $mytext[$el]->{'tag'};
if ($tag eq '' || substr($tag, 0, 1) eq '/') { next; }
$style = $mytext[$el]->{'style'};
if (!defined $style) { next; }
$stylehash = _process_style_string({}, $style);
# look at each defined property. do we support it?
foreach (keys %$stylehash) {
my $propname = $_;
my $found = 0;
for (my $sup=0; $sup < @supported_properties; $sup++) {
if ($propname eq $supported_properties[$sup]) {
$found = 1;
last;
}
}
if (!$found) {
print STDERR "Warning: CSS property name '$propname' found in element $el (tag <$tag>)\n";
print STDERR " style is either invalid, or is unsupported by PDF::Builder.\n";
}
}
# TBD stylehash->$_ check values here
}
return;
} # end of _check_CSS_properties
# the workhorse of the library: output text (modified by tags) in @mytext
sub _output_text {
my ($start_y, $min_y, $outl, $pdf, $page, $text, $grfx, $restore, $topCol,
$font_size, $markup, $marker_width, $marker_gap, $leading, $optpage,
$page_numbers, $pass_count, $max_passes, $state, @mytext)
= @_;
my @outline = @$outl;
# 'page' in opts, for cross references and left-right paging
my $pc = 1;
my $mp = 1;
my $ppn = 1;
my $filename = '';
my $fpn = '1';
my $LR = 'R';
my $bind = 0; # global item
if (defined $optpage) {
($pc, $mp, $ppn, $filename, $fpn, $LR, $bind) = @$optpage;
}
# start_y is the lowest extent of the previous line, or the highest point
# of the column outline, and is where we start the next one.
# min_y is the lowest y available within the column outline, outl.
# pdf is the pdf top-level object.
# text is the text context.
# para is a flag that we are at the top of a column (no margin-top added).
# font_size is the default font size to use.
# markup is 'html', 'pre' etc. in case you need to do something different
# marker_width is width (pt) of list markers (right justify within)
# marker_gap is space (pt) between list marker and item text
# leading is the default leading ratio to use.
# mytext is the array of hashes containing tags, attributes, and text.
my ($start_x, $x,$y, $width, $endx); # current position of text
my ($asc, $desc, $desc_leading);
my $next_y = $start_y;
# we loop to fill next line, starting with a y position baseline set when
# encounter the next text, and know the font, font_size, and thus the
# ascender/descender extents (which may grow). from that we can find
# the next baseline (which could be moved downwards).
# we loop until we either run out of input text, or run out of column
my $need_line = 1; # need to start a new line? always 'yes' (1) on
# call to column(). set to 'yes' if tag is for a block
# level display (treat like a paragraph)
my $add_x = 0; # amount to add for indent
my $add_y = 0; # amount to drop for first line's top margin
my @line_extents = (); # for dealing with changes to vertical extents
# changes mid-line
my $start = 1; # counter for ordered lists
my $list_depth_u = 0; # nesting level of ul
my $list_depth_s = 0; # nesting level of _sl
my $list_depth_o = 0; # nesting level of ol
my $list_marker = ''; # li marker text
my $reversed_ol = 0; # count down from start
my $phrase='';
my $remainder='';
my $desired_x; # leave undef, is correction for need_line reset of x
my @vmargin = (0, 0); # build up largest vertical margin (most negative and most positive)
my $current_prop = _init_current_prop(); # determine if a property has
# changed and PDF::Builder routines need calling. see
# _init_current_prop() for list of properties
my @properties = ({}); # stack of properties from tags
_update_properties($properties[0], $mytext[0], 'body');
_update_properties($properties[0], $mytext[1], 'body');
my $call_get_font = 0;
my %bad_tags; # keep track of invalid HTML tags
my $x_adj = 0; # ul, ol list marker move left from right-align position
my $y_adj = 0; # ul list marker elevation
# mytext[0] should be default css values
# mytext[1] should be any <style> tags (consolidated) plus opts 'style'
# user input tags/text start at mytext[2]
# starting available space, will be updated as new line needed
($start_x,$y, $width) = _get_baseline($start_y, @outline);
for (my $el = 2; $el < scalar @mytext; $el++) {
# discard any empty elements
if (ref($mytext[$el]) ne 'HASH') { next; }
if (!keys %{$mytext[$el]}) { next; }
if ($mytext[$el]->{'tag'} ne '') {
# tags/end-tags
# should be a tag or end-tag element defined
# for the most part, just set properties at stack top. sometimes
# special actions need to be taken, with actual output (e.g.,
# <hr> or <img>). remember that the properties stack includes
# any units (%, pt, etc.), while current_prop has been converted
# to points.
my $tag = lc($mytext[$el]->{'tag'});
# ================ <tag> tags ==========================
if (substr($tag, 0, 1) ne '/') {
# take care of 'beginning' tags. dup the top of the properties
# stack, update properties in the stack top element. note that
# current_prop usually isn't updated until the text is being
# processed. some tags need some special processing if they
# do something that isn't just a property change
# watch for INK HERE where PDF needs to be told to change
# properties stack new element ---------------------------------
# 1. dup the top of the properties stack for a new set of
# properties to be modified by attributes and CSS
push @properties, {};
foreach (keys %{$properties[-2]}) {
$properties[-1]->{$_} = $properties[-2]->{$_};
}
# current_prop is still previous text's properties
# 1a. "drop" any property which should not be inherited
# unless value is 'inherit' (explicit inheritance, TBD)
# width (used by <hr>), margin-*, TBD: border-*,
# background-*, perhaps others. if list gets long enough,
# put in separate routine.
$properties[-1]->{'width'} = 0; # used for <hr>
$properties[-1]->{'height'} = 0; # used for <hr>
$properties[-1]->{'margin-top'} = 0;
$properties[-1]->{'margin-bottom'} = 0;
$properties[-1]->{'margin-left'} = 0;
$properties[-1]->{'margin-right'} = 0;
# 1b. unless first entry, save parent's font-size (points)
if (@properties > 1) {
$properties[-1]->{'_parent-fs'} = $properties[-2]->{'font-size'};
} else {
# very first tag in list, no parent (use body.font-size) should be points
$properties[-1]->{'_parent-fs'} = $mytext[0]->{'body'}->{'font-size'};
$properties[-1]->{'_parent-fs'} = $mytext[1]->{'body'}->{'font-size'}
if defined $mytext[1]->{'body'}->{'font-size'};
# strip off any 'pt' unit and leave as bare number
$properties[-1]->{'_parent-fs'} =~ s/pt$//;
}
# 2. update properties top with element [0] (default CSS)
# per $tag
_update_properties($properties[-1], $mytext[0], $tag);
# 3. update properties top with element [1] (styles CSS)
# per $tag
_update_properties($properties[-1], $mytext[1], $tag);
# 4. update properties top with element [1] per any .class
# (styles CSS, which is only one with .class selectors)
if (defined $mytext[$el]->{'class'}) {
_update_properties($properties[-1], $mytext[1],
'.'.$mytext[$el]->{'class'});
}
# 5. update properties top with element [1] per any #id
# (styles CSS, which is only one with #id selectors)
if (defined $mytext[$el]->{'id'}) {
_update_properties($properties[-1], $mytext[1],
'#'.$mytext[$el]->{'id'});
}
# 6. update properties top with any tag/style attributes.
# these come from the tag itself: its attributes,
# overridden by any style attribute. these are the
# highest priority properties. everything copied over to
# the stack top, but anything not a real property will end
# up not being used.
_update_properties($properties[-1], $mytext[$el]);
# 6a. 3.028 and 3.029 releases, allow text-height as alias
# for line-height (currently only multiplier of font size)
if (defined $properties[-1]->{'text-height'}) {
$properties[-1]->{'line-height'} =
delete $properties[-1]->{'text-height'}; }
# 7. update size properties to be simply bare points, rather than e.g., 75%
# remember that $current_prop->{'font-size'} init -1, is what was last written to PDF
# current font size (pt) before properties applied
my $fs = $properties[-1]->{'_parent-fs'}; # old font size (should always be one, in points > 0)
$fs = $properties[-1]->{'font-size'} = _size2pt($properties[-1]->{'font-size'}, $fs, 'usage'=>'font-size');
$fs = $font_size if $fs == -1; # just in case a -1 sneaks through, $font_size
# should default to 12, override with 'font_size'=>value
$properties[-1]->{'margin-top'} = _size2pt($properties[-1]->{'margin-top'}, $fs, 'usage'=>'margin-top');
$properties[-1]->{'margin-right'} = _size2pt($properties[-1]->{'margin-right'}, $fs, 'usage'=>'margin-right');
$properties[-1]->{'margin-bottom'} = _size2pt($properties[-1]->{'margin-bottom'}, $fs, 'usage'=>'margin-bottom');
$properties[-1]->{'margin-left'} = _size2pt($properties[-1]->{'margin-left'}, $fs, 'usage'=>'margin-left');
# border-* width (TBD, with border to set all four)
# padding-* (TBD, with padding to set all four)
# width = length of <hr> in pts
$properties[-1]->{'width'} = _size2pt($properties[-1]->{'width'}, $fs, 'usage'=>'width');
# height (thickness/size of <hr>) in pts
$properties[-1]->{'height'} = _size2pt($properties[-1]->{'height'}, $fs, 'usage'=>'height');
$properties[-1]->{'text-indent'} = _size2pt($properties[-1]->{'text-indent'}, $fs, 'usage'=>'text-indent');
$properties[-1]->{'_marker-size'} = _size2pt($properties[-1]->{'_marker-size'}, $fs, 'usage'=>'_marker-size');
# TBD should inside and outside be set to point values here?
if (defined $properties[-1]->{'list-style-position'} &&
$properties[-1]->{'list-style-position'} ne 'inside' &&
$properties[-1]->{'list-style-position'} ne 'outside') {
$properties[-1]->{'list-style-position'} = _size2pt($properties[-1]->{'list-style-position'}, $fs,
'parent_size'=>$marker_width + $marker_gap, 'usage'=>'list-style-position');
}
# update current_prop hash -------------------------------------
# properties stack already updated
# some current_prop must be updated here, such as stroke
# color for <hr>, font-size for top and bottom margins
# block level elements -----------------------------------------
if ($properties[-1]->{'display'} eq 'block') {
$need_line = 1;
$start_y = $next_y;
$add_x = $add_y = 0;
# block display with a non-zero top margin and/or bottom
# margin... set skip to larger of the two.
# when text is ready to be output, figure both any new
# top margin (for that text) and compare to the existing
# bottom margin (in points) saved at the end of the previous
# text.
# if paragraph and is marked as a continuation (i.e., spanned two columns),
# suppress indent (below) and suppress top margin by setting topCol flag
my $pcont = ($tag eq 'p' && defined $mytext[$el]->{'cont'} && $mytext[$el]->{'cont'})? 1: 0;
$topCol = 1 if $pcont;
$vmargin[0] = min($vmargin[0], $properties[-1]->{'margin-top'});
$vmargin[1] = max($vmargin[1], $properties[-1]->{'margin-top'});
# now that need_line etc. has been set due to block display,
# change stack top into 'inline'
$properties[-1]->{'display'} = 'inline';
}
# handle specific kinds of tags' special processing
# if no code for a tag, yet uncommented, it's supported
# (just no special processing at this point)
# in many cases, all that was needed was to set properties,
# and normal text output takes care of the rest
#
if ($tag eq 'p') {
# indent for start of paragraph
$add_x = $properties[-1]->{'text-indent'}; # indent by para indent amount
$add_y = 0;
# p with cont=>1 is continuation of paragraph in new column
# no indent and no top margin... just start a new line
if (defined $mytext[$el]->{'cont'} && $mytext[$el]->{'cont'}) {
$add_x = $add_y = 0;
}
} elsif ($tag eq 'i') {
} elsif ($tag eq 'em') {
} elsif ($tag eq 'b') {
} elsif ($tag eq 'strong') {
} elsif ($tag eq 'font') { # face already renamed to
# font-family, size already renamed to font-size, color
} elsif ($tag eq 'span') {
# needs style= or <style> to be useful
} elsif ($tag eq 'ul') {
$list_depth_u++; # for selecting default marker text
# indent each list level by same amount (initially 0)
$properties[-1]->{'_left'} = $properties[-1]->{'_left_nest'};
# next list to be nested will start here
$properties[-1]->{'_left_nest'} += $marker_width+$marker_gap;
} elsif ($tag eq '_sl') {
$list_depth_s++; # for indent level
# indent each list level by same amount (initially 0)
$properties[-1]->{'_left'} = $properties[-1]->{'_left_nest'};
# next list to be nested will start here
$properties[-1]->{'_left_nest'} += $marker_width+$marker_gap;
} elsif ($tag eq 'ol') {
# save any existing start and reversed_ol values
$properties[-2]->{'_start'} = $start; # current start
$properties[-2]->{'_reversed_ol'} = $reversed_ol; # cur flag
$start = 1;
if (defined $mytext[$el]->{'start'}) {
$start = $mytext[$el]->{'start'};
}
if (defined $mytext[$el]->{'reversed'}) {
$reversed_ol = 1;
} else {
$reversed_ol = 0;
}
$list_depth_o++; # for selecting default marker format
# indent each list level by same amount (initially 0)
$properties[-1]->{'_left'} = $properties[-1]->{'_left_nest'};
$properties[-1]->{'_left_nest'} += $marker_width+$marker_gap;
#} elsif ($tag eq 'img') { # hspace and vspace already
# margins, width, height
# TBD for 3.029 currently ignored
} elsif ($tag eq 'a') {
# no special treatment at this point
#} elsif ($tag eq 'pre') {
# white-space etc. no consolidating whitespace
# TBD for 3.029 currently ignored
} elsif ($tag eq 'code') { # font-family sans-serif + constant width 75% font-size
} elsif ($tag eq 'blockquote') {
} elsif ($tag eq 'li') {
# where to start <li> text
# after /marker, $x is in desired place
# set its new _left for subsequent lines
if ($properties[-1]->{'list-style-position'} eq 'inside') {
# _left unchanged
} elsif ($properties[-1]->{'list-style-position'} eq 'outside') {
# li's copy of _left, should be reset at /li
$properties[-1]->{'_left'} += $marker_width+$marker_gap;
} else {
# extension to CSS (should already be in pts)
$properties[-1]->{'_left'} += $properties[-1]->{'list-style-position'};
}
} elsif ($tag eq 'h1') { # TBD align
# treat headings as paragraphs
} elsif ($tag eq 'h2') {
} elsif ($tag eq 'h3') {
} elsif ($tag eq 'h4') {
} elsif ($tag eq 'h5') {
} elsif ($tag eq 'h6') {
} elsif ($tag eq 'hr') {
# actually draw a horizontal line INK HERE
$start_y = $next_y;
# drop down page by any pending vertical margin spacing
if ($vmargin[0] != 0 || $vmargin[1] != 0) {
if (!$topCol) {
$start_y -= ($vmargin[0]+$vmargin[1]);
}
@vmargin = (0, 0); # reset counters
}
$topCol = 0; # for rest of column do not suppress vertical margin
my $oldcolor = $grfx->strokecolor();
$grfx->strokecolor($properties[-1]->{'color'});
my $oldlinewidth = $grfx->linewidth();
my $thickness = $properties[-1]->{'height'} || 1; # HTML size attribute
$grfx->linewidth($thickness);
my $y = $start_y - $thickness/2;
($start_x,$y, $width) = _get_baseline($y, @outline);
$x = $start_x + $properties[-1]->{'_left'};
$width -= $properties[-1]->{'_left'} + $properties[-1]->{'_right'}; # default full width
my $available = $width; # full width amount
# if there is a requested width, use the smaller of the two
# TBD future, width as % of possible baseline,
# center or right aligned, explicit units (pt default)
if ($properties[-1]->{'width'} > 0 && # default to use full width is -1
$properties[-1]->{'width'} < $width) {
$width = $properties[-1]->{'width'}; # reduced width amount
}
my $align = 'center';
if (defined $mytext[$el]->{'align'}) {
$align = lc($mytext[$el]->{'align'});
}
if ($align eq 'left') {
# no change to x
} elsif ($align eq 'right') {
$x += ($available-$width);
} else {
if ($align ne 'center') {
carp "<hr> align not 'left', 'center', or 'right'. Ignored.";
$align = 'center';
}
$x += ($available-$width)/2;
}
$endx = $x + $width;
$grfx->move($x, $y);
$grfx->hline($endx);
$grfx->stroke();
$y -= $thickness/2;
$next_y = $y;
# empty (self closing) tag, so won't go through a /hr to set bottom margin.
# is in empty tag list, so will get proper treatment
# restore changed values
$grfx->linewidth($oldlinewidth);
$grfx->strokecolor($oldcolor);
#} elsif ($tag eq 'br') { # TBD force new line
#} elsif ($tag eq 'sup') { # TBD
#} elsif ($tag eq 'sub') { # TBD
} elsif ($tag eq 'u') {
} elsif ($tag eq 'ins') {
} elsif ($tag eq 's') {
} elsif ($tag eq 'strike') {
} elsif ($tag eq 'del') {
# tags maybe some time in the future TBD
#} elsif ($tag eq 'address') { # inline formatting
#} elsif ($tag eq 'article') { # discrete section
#} elsif ($tag eq 'aside') { # discrete section
#} elsif ($tag eq 'base') {
#} elsif ($tag eq 'basefont') {
#} elsif ($tag eq 'big') { # font-size 125%
# already taken care of head, body
#} elsif ($tag eq 'canvas') {
#} elsif ($tag eq 'caption') {
#} elsif ($tag eq 'center') { # margin-left/right auto
#} elsif ($tag eq 'cite') { # quotes, face?
#} elsif ($tag eq 'dl') { # similar to ul/li
#} elsif ($tag eq 'dt') {
#} elsif ($tag eq 'dd') {
#} elsif ($tag eq 'div') { # requires width, height, left, etc.
#} elsif ($tag eq 'figure') {
#} elsif ($tag eq 'figcap') {
#} elsif ($tag eq 'footer') { # discrete section
#} elsif ($tag eq 'header') { # discrete section
#} elsif ($tag eq 'kbd') { # font-family sans-serif +
# constant width 75% font-size
#} elsif ($tag eq 'mark') {
#} elsif ($tag eq 'nav') { # discrete section
#} elsif ($tag eq 'nobr') { # treat all spaces within as NBSPs?
#} elsif ($tag eq 'q') { # ldquo/rdquo quotes around
#} elsif ($tag eq 'samp') { # font-family sans-serif +
# constant width 75% font-size
#} elsif ($tag eq 'section') { # discrete section
#} elsif ($tag eq 'small') { # font-size 75%
#} elsif ($tag eq 'summary') { # discrete section
} elsif ($tag eq 'style') {
# sometimes some stray empty style tags seem to come
# through... can be ignored
} elsif ($tag eq '_marker') {
# at this point, all properties are set in usual way. only
# tasks remaining are to 1) determine the text,
# 2) set CSS properties to default marker conventions.
# 3) override text, color, etc. from _marker-* properties.
# 4) if not left justified, set reference x location
#
# paragraph, but label depends on parent (list-style-type)
# type and value attributes can override parent
# list-style-type and start
if (defined $properties[-1]->{'_marker-text'} &&
$properties[-1]->{'_marker-text'} ne '') {
# explicitly-defined _marker-text overrides all else
$list_marker = $properties[-1]->{'_marker-text'};
} else {
# li's 'value', if any. li is at el+3.
# TBD check if parent is ol? (current_list top == o)
if (defined $mytext[$el+3]->{'value'}) {
$start = $mytext[$el+3]->{'value'};
}
# li's 'list-style-type', if any (was 'type'). li is at el+3.
# TBD does this only apply to <ol>? check?
if (defined $mytext[$el+3]->{'type'}) {
$properties[-1]->{'list-style-type'} =
$mytext[$el+3]->{'type'};
}
# determine li marker
$list_marker = _marker(
$properties[-1]->{'list-style-type'},
$list_depth_u, $list_depth_o, $list_depth_s,
$start,
$properties[-1]->{'_marker-before'},
$properties[-1]->{'_marker-after'});
if (substr($list_marker, 0, 1) eq '.') {
# it's a bullet character (or '')
} else {
# fully formatted ordered list item
if ($reversed_ol) {
$start--;
} else {
$start++;
}
}
# starting at _left, position x for marker LJ, CJ, or RJ
# WITHIN _left to _left+marker_width
$desired_x = $start_x + $properties[-1]->{'_left'};
if ($properties[-1]->{'_marker-align'} eq 'left') {
# should already be at _left
$properties[-1]->{'text-align'} = 'left';
} elsif ($properties[-1]->{'_marker-align'} eq 'center') {
$desired_x += $marker_width/2;
$properties[-1]->{'text-align'} = 'center';
} else { # right (default)
$desired_x += $marker_width;
$properties[-1]->{'text-align'} = 'right';
}
# dl: variable length marker width, minimum size given,
# which is where dd left margin is
# handle dl/dt/dd separately from ul/ol/_sl
}
# list_marker is set
if ($list_marker eq '.none' || $list_marker =~ /^ *$/) {
# list_marker '' or ' ' or '.none': don't reset
# properties as it generates redundant color, font,
# size, etc. changes because no ink laid down
} else {
# issue property changes when necessary
my $fs = $properties[-1]->{'font-size'};
# override any other property with corresponding _marker-*
# properties-to-PDF-calls have NOT yet been done
if (defined $properties[-1]->{'_marker-color'} &&
$properties[-1]->{'_marker-color'} ne '') {
$properties[-1]->{'color'} =
$properties[-1]->{'_marker-color'};
}
if (defined $properties[-1]->{'_marker-font'} &&
$properties[-1]->{'_marker-font'} ne '') {
$properties[-1]->{'font-family'} =
$properties[-1]->{'_marker-font'};
}
if (defined $properties[-1]->{'_marker-style'} &&
$properties[-1]->{'_marker-style'} ne '') {
$properties[-1]->{'font-style'} =
$properties[-1]->{'_marker-style'};
}
if (defined $properties[-1]->{'_marker-size'} &&
$properties[-1]->{'_marker-size'} ne '') {
$properties[-1]->{'font-size'} =
$properties[-1]->{'_marker-size'};
}
if (defined $properties[-1]->{'_marker-weight'} &&
$properties[-1]->{'_marker-weight'} ne '') {
$properties[-1]->{'font-weight'} =
$properties[-1]->{'_marker-weight'};
}
# _marker-align is not a standard CSS property
# finally, update the text within the _marker
if ($list_marker ne '') {
# list marker should be nonblank for <ol> and <ul>,
# empty for <_sl> (just leave marker text alone)
# output the marker. x,y is the upper left baseline of
# the <li> text, so text_right() the marker
if ($list_marker =~ m/^\./) {
# it's a symbol for <ul>. 50% size, +y by 33% size
# TBD url image and other character symbols
# (possibly in other than Zapf Dingbats).
if ($list_marker eq '.disc') {
$list_marker = chr(108); # 'l'
} elsif ($list_marker eq '.circle') {
$list_marker = chr(109); # 'm'
} elsif ($list_marker eq '.square') {
$list_marker = chr(110); # 'n'
} elsif ($list_marker eq '.box') {
$list_marker = chr(111); # non-standard 'o'
} elsif ($list_marker eq '.none') {
$list_marker = '';
}
# ul defaults
$x_adj = $y_adj = 0;
if ($list_marker ne '') {
# x_adj (- to left) .3em+2pt for gap marker to text
#$x_adj = -(0.3 * $fs + 2);
# figure y_adj for ul marker (raise, since smaller)
# TBD: new CSS to set adjustments
$y_adj = -0.33*_size2pt($properties[-1]->{'font-size'}, $fs, 'usage'=>'list marker raise')/$fs + 0.33;
$y_adj *= $fs;
} else {
# empty text
}
} else {
# it's a formatted count for <ol>
# ol defaults
# x_adj (- to left) .3em for gap marker to text
#$x_adj = -(0.3 * $fs);
}
} else {
# '' list-marker for _sl, leave as is so no output
# no change to font attributes
}
# insert list_marker into text field at $el+1 and end
# of marker at $el+2. no need to change $el.
# IF existing text not empty or blank, leave alone!
if ($mytext[$el+1]->{'text'} =~ /^ *$/) {
$mytext[$el+1]->{'text'} = $list_marker;
}
} # list marker NOT to be skipped
$list_marker = '';
#} elsif ($tag eq '_ovl') { # TBD
#} elsif ($tag eq '_k') { # TBD
} elsif ($tag eq '_move') {
# move left or right on current baseline, per 'x' and/or
# 'dx' attribute values
# TBD: consider y/dy positioning too, would need to adjust
# baseline to new y before getting fresh start_x and x
# first, we need valid $x and $y. if left by the previous
# write, use them. otherwise need to start at the left edge
# of the column (start_x) and y on the baseline
if (!defined $y) {
$y = $start_y - 8.196;
}
($start_x,$y, $width) = _get_baseline($y, @outline);
if (!defined $x) {
$x = $start_x;
}
# need to increase x and decrease width by any
# left margin amount
$x = $start_x + $properties[-1]->{'_left'};
$width -= $properties[-1]->{'_left'} + $properties[-1]->{'_right'};
$endx = $start_x + $width;
my ($attr, $attrv, $attru);
# handle "x" attribute first (absolute positioning),
# leaving $x at the new position. no check on going beyond
# either end of the line.
if (defined $mytext[$el]->{'x'}) {
# 'x' attribute given, treat as move relative to start_x
$attr = $mytext[$el]->{'x'};
# TBD: a more rigorous number check
if ($attr =~ m/^(-?[\d.]+)(pt$|%$|$)/i) {
$attrv = $1;
$attru = $2;
if ($attru eq '%') {
$x = $start_x + $attrv/100*$width; # % of width
} else {
$x = $start_x + $attrv; # pts
}
} # if can't match pattern, x remains unchanged
}
# now handle "dx" attribute (relative positioning),
# leaving $x at the new position. no check on going beyond
# either end of the line.
if (defined $mytext[$el]->{'dx'}) {
# 'dx' attribute given, treat as move relative to where
# 'x' left it (if given), else relative to current x
$attr = $mytext[$el]->{'dx'};
# TBD: a more rigorous number check
if ($attr =~ m/^(-?[\d.]+)(pt$|%$|$)/i) {
$attrv = $1;
$attru = $2;
if ($attru eq '%') {
$x += $attrv/100*$width; # % of width
} else {
$x += $attrv; # pts
}
} # if can't match pattern, x remains unchanged
}
# allow <0 or >width to go beyond baseline at user's risk
# (likely to be cut off if exceed line end on right, who
# knows what will happen on the left)
$text->translate($x, $y);
# any pending need_line will reset x to start_x, so save
# desired x (otherwise is undef)
$desired_x = $x;
# HTML::TreeBuilder may have left a /_move tag. problem?
} elsif ($tag eq '_ref') {
# cross reference tag tgtid= fit=
# $mytext[$el] is this tag, $el+1 is link text (update
# from target if empty or undefined), so there IS a
# child text and end tag for _ref
# add 'annot' info to link text field. output only current
# text of link, save link data for very end.
my ($tgtid, $fit, $title);
$tgtid = $mytext[$el]->{'tgtid'}; # required!
if (!defined $tgtid) { croak "<_ref> missing tgtid=."; }
$fit = $mytext[$el]->{'fit'}; # optional
$fit //= ''; # use default fit
$title = $mytext[$el]->{'title'}; # optional
$title //= '';
$title = "[no title given]" if $title eq '';
# if no title, try to get from target
# TBD override of page_numbers
my ($tfn, $tppn, $tid);
# first, #id convert to just id (only at beginning), or
# #p-x-y[-z] split into #p and fit
if ($tgtid =~ /^#[^#]/) {
# starts with single #
my @fields = split /-/, $tgtid;
# if size 1, is just #id or #p
if (@fields == 1) {
# if just #p, see if p is integer 1+
if ($tgtid =~ /^#[1-9]\d*$/) {
# is #p so leave $tgtid as is
} else {
# is #id -- strip off leading #
$tgtid = substr($tgtid, 1);
}
} elsif (@fields == 3 || @fields == 4) {
# possibly #p-x-y-z default z = null
# only checking if p is integer 1+
# TBD check if x and y are numbers >= 0
# TBD check if z is number > 0 or 'null' or 'undef'
if ($fields[0] =~ /^#[1-9]\d*$/) {
# is #p so build $fit
$tgtid = $fields[0];
if (@fields == 3) { push @fields, 'null'; }
if ($fields[3] eq 'undef') { $fields[3] = 'null'; }
$fit = "xyz,$fields[1],$fields[2],$fields[3]";
} else {
# is #id -- strip off leading #
$tgtid = substr($tgtid, 1);
}
} else {
# wrong number of fields, is just #id
# so strip off leading #
$tgtid = substr($tgtid, 1);
}
}
# split up tgtid into various fields
if ($tgtid =~ /##/) {
# external link's file, and ppn of target
($tfn, $tppn) = split /##/, $tgtid;
$tfn //= '';
$tid = "##$tppn";
} elsif ($tgtid =~ /#/) {
# external link's file, and Named Destination
($tfn, $tppn) = split /#/, $tgtid;
$tfn //= '';
$tid = "#$tppn";
} else {
# an id=
$tfn = ''; # internal link only
$tppn = -1; # unknown at this time
$tid = $tgtid;
}
# add a new array entry to xrefs, or update existing one
# knowing title, fit, tid, tfn, tppn from <_ref>
# sptr = pointer (ref) to this entry in xrefs
# tptr = pointer (ref) to matching target in xreft
my $sindex = $state->{'sindex'};
my ($sptr, $tfpn, $tptr);
if ($pass_count == 1 && defined $sindex) {
# add new entry at $sindex
$state->{'xrefs'}->[$sindex] = {};
# ptr to hash {id} and its siblings (see Builder.pm)
$sptr = $state->{'xrefs'}->[$sindex];
# the following items should never change after the
# first pass
# it's possible that this _ref is totally self-contained
# and does not refer to any target id
$sptr->{'id'} = $tid;
$sptr->{'fit'} = $fit;
$sptr->{'tfn'} = $tfn;
# items that CAN change between passes
$sptr->{'title'} = $title;
$sptr->{'tx'} = 0;
$sptr->{'ty'} = 0;
$sptr->{'tfpn'} = '';
} else {
# entry already exists, at $sindex
# update anything that might change pass-to-pass
# set 'changed' flag only if updated AFTER this pass's
# title text and other_pg have been laid down.
# if $page_numbers == 2, a change in ppn's either
# source or target is of concern TBD
$sptr = $state->{'xrefs'}->[$sindex] if defined $sindex;
# nothing in this section to warrant changed flag
# and we're about to output a fresh copy of link text
# and 'other_pg' text
}
# whether pass 1 initialization or pass 2+ update
# the following can change without forcing another pass
#
$sptr->{'tppn'} = $tppn;
$sptr->{'sppn'} = $ppn;
# have we found this target id already?
if (defined $state->{'xreft'}{'_reft'}{$tid}) {
$tptr = $state->{'xreft'}{'_reft'}{$tid};
} else {
$tptr = undef; # just to be certain
}
if (defined $tptr) {
# does the title need an update from target?
if ($sptr->{'title'} eq '[no title given]' &&
$tptr->{'title'} ne '[no title given]') {
$sptr->{'title'} = $tptr->{'title'};
# no need to mark as changed, as about to output
# the link text (title, other_pg)
#$state->{'changed_target'}->{$tid} = 1;
# update child text
$mytext[$el+1]{'text'} = $sptr->{'title'};
}
# other fields that may change
$sptr->{'tx'} = $tptr->{'tx'};
$sptr->{'ty'} = $tptr->{'ty'};
$sptr->{'tfpn'} = $tptr->{'tfpn'}; # affects other_pg
# other fields that may be overridden by target
$sptr->{'tppn'} = $tptr->{'tppn'}
if ($sptr->{'tppn'} == -1); # affects other_pg
$sptr->{'tag'} = $tptr->{'tag'};
}
# TBD figure 'other_pg' text when actually output it,
# and update field and set flag if changed (pass > 1)
# once know sppn and tppn (in same PDF) and
# $page_numbers > 0. note that a _ref can override
# the global page_numbers with its own (e.g., to
# force = 1 'on page N' when global == 2)
$sptr->{'other_pg'} = $sptr->{'prev_other_pg'} = ''; # TBD
#
# Note that Named Destinations do not get a page
# designation output (no "on page $" etc.) regardless
# of $page_numbers setting. TBD what about internal jumps?
# may not know page of an external jump.
# via 'annot' flag tell title text to grab rectangle corners
# and stick in {'click'} area array. may be multiple such
# rectangles (click areas) if text wraps. also determine
# 'other_pg' string and update entry (TBD)
$sptr->{'click'} = [];
# TBD title that includes embedded tags to support
$mytext[$el+1]->{'annot'} = $sindex;
$state->{'sindex'} = ++$sindex;
} elsif ($tag eq '_reft') {
# cross reference target tag id=
# for markdown, only target available
my $id = $mytext[$el]->{'id'}; # required!
if (!defined $id) { croak "<_reft> missing id=."; }
my $title = $mytext[$el]->{'title'}; # optional
# code handling id= and checking tag_lists from here on out
# to deal with <_reft>
} elsif ($tag eq '_nameddest') {
# define a Named Destination at this point
# possibly a fit attribute is defined
my $name = $mytext[$el]->{'name'}; # required!
if (!defined $name) { croak "<_nameddest> missing name=."; }
my $fit = $mytext[$el]->{'fit'}; #optional
$fit //= '';
my $ptr = $state->{'nameddest'};
$ptr->{$name} = {};
$ptr->{$name}{'fit'} = $fit;
$ptr->{$name}{'ppn'} = $ppn; # this and following can change
$ptr->{$name}{'x'} = $x; # on subsequent passes
$ptr->{$name}{'y'} = $y;
# special directives such as (TBD)
# <_endc> force end of column here (while still filling line)
# e.g., to prevent an orphan
# <_nolig></_nolig> forbid ligatures in this range
# <_lig gid='nnn'>c</_lig> replace character(s) by a ligature
# <_alt gid='nnn'>c</_alt> replace character(s) by alternate
# glyph such as a swash. font-dependent
# <_hyp>, <_nohyp> control hypenation in a word (and remember
# rules when see this word again)
} else {
# unsupported or invalid tag found
# keep list of those found, error message once per tag
# per column() call
if (!defined $bad_tags{$tag}) {
print STDERR "Warning: tag <$tag> either invalid or currently unsupported by PDF::Builder.\n";
$bad_tags{$tag} = 1;
}
# treat as <span>
$tag = $mytext[$el]->{'tag'} = 'span';
}
# any common post-tag work -------------------------------------
# does this tag have an id attribute, and is it in one or
# more of the watch lists to add to references?
# _reft tags already checked that id= given
if (defined $state && exists $mytext[$el]->{'id'}) {
my $id = $mytext[$el]->{'id'};
# might have a title, too
my $title = $mytext[$el]->{'title'}; # optional (_reft)
$title = '' if !defined $title;
# if no title in source or target tags, will have to
# look at child text of various tags
# yes, it has an id. now check against lists
# this tag will produce an entry in xreft for each list
# that it is in TBD find way to consolidate into one?
my %tag_lists = %{$state->{'tag_lists'}};
# will contain at least _reft list with _reft tag
# goes into xreft/listname/id structure
foreach my $list (keys %tag_lists) { # _reft, TOC, etc
my @tags = @{$tag_lists{$list}}; # tags to check
foreach my $xtag (@tags) {
if ($tag eq $xtag) {
# this tag (with id=) is being used by target
# list $list (e.g., '_reft')
# add (or update) this tag's data into the $list
my $tptr;
$tptr = $state->{'xreft'}->{$list}->{$id};
if (!defined $tptr) {
$state->{'xreft'}->{$list}->{$id} = {};
$tptr = $state->{'xreft'}->{$list}->{$id};
# add new entry or overwrites old one
# perhaps pass > 1 see if $id already exists
# these three should never change on update
$tptr->{'tfn'} = $filename;
$tptr->{'title'} = $title;
$tptr->{'tag'} = $tag;
# if title empty, look for child text
# use this title if no title= on <_ref>
if ($title eq '') {
# heading has child text, add others
# as useful
if ($tag =~ /^h\d$/ ||
$tag eq '_part' ||
$tag eq '_chap') {
$title = _get_child_text(
\@mytext, $el );
# might still be ''
}
$tptr->{'title'} = $title;
}
} # add a new id= to xreft, or update existing
# these may change from pass to pass
$tptr->{'tppn'} = $ppn;
$tptr->{'tfpn'} = $fpn;
$tptr->{'tx'} = $x//0; # sometimes undef
$tptr->{'ty'} = $y;
# done creating or updating an entry
# every link source using this id gets update
# and "changed" flag set for visible text change
for (my $sindex=0;
$sindex < scalar(@{$state->{'xrefs'}});
$sindex++) {
if ($state->{'xrefs'}->[$sindex]->{'id'} eq $id) {
# yes, link source exists. update it and
# set flag if need another pass
my $another_pass = 0;
my $sptr = $state->{'xrefs'}->[$sindex];
if ($sptr->{'title'} eq '[no title given]' &&
$tptr->{'title'} ne '[no title given]') {
$sptr->{'title'} = $tptr->{'title'};
$another_pass = 1;
}
# 'other_pg' determined elsewhere
$state->{'changed_target'}{$id} = 1
if $another_pass;
# other fields in xrefs to update
# from xreft entry
$sptr->{'tx'} = $tptr->{'tx'};
$sptr->{'ty'} = $tptr->{'ty'};
$sptr->{'tag'} = $tptr->{'tag'};
$sptr->{'tfn'} = $tptr->{'tfn'}
if $sptr->{'tfn'} eq '';
$sptr->{'tfpn'} = $tptr->{'tfpn'}
if $sptr->{'tfpn'} eq '';
$sptr->{'tppn'} = $tptr->{'tppn'}
if $sptr->{'tppn'} < 1;
} # link source targeting this id
} # loop sindex through all link sources
} # found a tag of interest in a list
} # check against list of tags
} # search through target tag lists
} # tag with id= see if wanted for target lists
if (defined $mytext[$el]->{'empty_element'}) {
# empty/void tag, no end tag, pop property stack
# as this tag's actions have already been taken
# update bottom margin. display already reset to 'inline'
$vmargin[0] = min($vmargin[0], $properties[-1]->{'margin-bottom'});
$vmargin[1] = max($vmargin[1], $properties[-1]->{'margin-bottom'});
pop @properties;
# should revert any changed font-size
splice(@mytext, $el, 1);
$el--; # end of loop will advance $el
# no text as child of this tag, whatever it does, it has
# to be completely handled in this section
}
# end of handling starting tags <tag>
# ================ </tags> end tags ======================
} else {
# take care of 'end' tags. some end tags need some special
# processing if they do something that isn't just a
# property change. current_prop should be up to date.
$tag = lc(substr($tag, 1)); # discard /
# note that current_prop should be all up to date by the
# time you hit the end tag
# this tag post-processing is BEFORE vertical margins and
# popping of properties stack for this and nested tags
# processing specific to specific end tags ---------------------
if ($tag eq 'ul') {
$list_depth_u--;
} elsif ($tag eq '_sl') {
$list_depth_s--;
} elsif ($tag eq 'ol') {
$list_depth_o--;
# restore any saved start and reversed_ol values
$start = $properties[-2]->{'_start'}; # current start
$reversed_ol = $properties[-2]->{'_reversed_ol'}; # cur flag
} elsif ($tag eq '_marker') {
# bump x position past gap to li start (li is inline)
$x = $start_x + $properties[-1]->{'_left'} +
$marker_width + $marker_gap;
$text->translate($x, $y);
$desired_x = $x;
}
# ready to pick larger of top and bottom margins (block display)
# block display element end (including paragraphs)
# start next material on new line
if ($current_prop->{'display'} eq 'block') {
$need_line = 1;
$start_y = $next_y;
$add_x = $add_y = 0;
# now that need_line, etc. are set, make inline
$current_prop->{'display'} = 'inline';
$vmargin[0] = min($vmargin[0], $properties[-1]->{'margin-bottom'});
$vmargin[1] = max($vmargin[1], $properties[-1]->{'margin-bottom'});
}
# pop properties stack and remove element ----------------------
# last step is to pop the properties stack and remove this
# element, its start tag, and everything in-between. adjust
# $el and loop again.
for (my $first = $el-1; $first>1; $first--) {
# looking for a tag matching $tag
if ($mytext[$first]->{'text'} eq '' &&
$mytext[$first]->{'tag'} eq $tag) {
# found it at $first
my $len = $el - $first + 1;
splice(@mytext, $first, $len);
$el -= $len; # end of loop will advance $el
pop @properties;
# restore current font size
last;
}
}
# this tag post-processing is AFTER vertical margins and
# popping of properties stack for this and nested tags
# (currently none)
if (@mytext == 2) { last; } # have used up all input text!
# only default values and style element are left
next; # next mytext element s/b one after batch just removed
# end of handling end tags </tag>
}
# end of tag processing
# ========================== text to output =================
} else {
# normally text is not empty '', but sometimes such may come
# through. a blank text is still valid
if ($mytext[$el]->{'text'} eq "\n") { next; } # EOL too
if ($mytext[$el]->{'text'} eq '') { next; }
# we should be at a new text entry ("phrase") INK HERE
# we have text to output on the page, using properties at the
# properties stack top. compare against current properties to
# see if need to make any calls (font, color, etc.) to make.
# drop down page by any pending vertical margin spacing
if ($vmargin[0] != 0 || $vmargin[1] != 0) {
if (!$topCol) {
$start_y -= ($vmargin[0]+$vmargin[1]);
}
@vmargin = (0, 0); # reset counters
}
$topCol = 0; # for rest of column do not suppress vertical margin
# after tags processed, and property list (properties[-1]) updated,
# typically at start of a text string (phrase) we will call PDF
# updates such as fillcolor, get_font, etc. and at the same time
# update current_prop to match.
# what properties have changed and need PDF calls to update?
# TBD future: separate slant and italic, optical size
$call_get_font = 0;
if ($properties[-1]->{'font-family'} ne $current_prop->{'font-family'}) {
$call_get_font = 1;
# a font label known to FontManager
$current_prop->{'font-family'} = $properties[-1]->{'font-family'};
}
if ($properties[-1]->{'font-style'} ne $current_prop->{'font-style'}) {
$call_get_font = 1;
# normal or italic (TBD separate slant)
$current_prop->{'font-style'} = $properties[-1]->{'font-style'};
}
if ($properties[-1]->{'font-weight'} ne $current_prop->{'font-weight'}) {
$call_get_font = 1;
# normal or bold (TBD multiple steps, numeric and named)
$current_prop->{'font-weight'} = $properties[-1]->{'font-weight'};
}
# font size
# don't want to trigger font call unless numeric value changed
# current_prop's s/b in points, newval will be in points. if
# properties (latest request) is a relative size (e.g., %),
# what it is relative to is NOT the last font size used
# (current_prop), but carried-along current font size.
my $newval = _size2pt($properties[-1]->{'font-size'},
$properties[-1]->{'_parent-fs'}, 'usage'=>'font-size');
# newval is the latest requested size (in points), while
# current_prop is last one used for output (in points)
if ($newval != $current_prop->{'font-size'}) {
$call_get_font = 1;
$current_prop->{'font-size'} = $newval;
}
# any size as a percentage of font-size will use the current fs
# should be in points by now, might not equal current_prop{font-size}
my $fs = $properties[-1]->{'font-size'};
# uncommon to only change font size without also changing something
# else, so make font selection call at the same time, besides,
# there is very little involved in just returning current font.
if ($call_get_font) {
# TBD future additional options, expanded weight
$text->font($pdf->get_font(
'face' => $current_prop->{'font-family'},
'italic' => ($current_prop->{'font-style'} eq 'normal')? 0: 1,
'bold' => ($current_prop->{'font-weight'} eq 'normal')? 0: 1,
), $fs);
$current_prop->{'font-size'} = $fs;
}
# font-size should be set in current_prop for use by margins, etc.
# don't know if color will be used for text or for graphics draw,
# so set both
if ($properties[-1]->{'color'} ne $current_prop->{'color'}) {
$current_prop->{'color'} = $properties[-1]->{'color'};
$text->fillcolor($current_prop->{'color'});
$text->strokecolor($current_prop->{'color'});
if (defined $grfx && ref($grfx) =~ m/^PDF::Builder::Content/) {
$grfx->fillcolor($current_prop->{'color'});
$grfx->strokecolor($current_prop->{'color'});
}
}
# these properties don't get a PDF::Builder call
# update text-indent, etc. of current_prop, even if we don't
# call a Builder routine to set them in PDF, so we can always use
# current_prop instead of switching between the two. current_prop
# property lengths should always be in pts (no labeled dimensions).
$current_prop->{'text-indent'} = $properties[-1]->{'text-indent'}; # should already be pts
$current_prop->{'text-decoration'} = $properties[-1]->{'text-decoration'};
$current_prop->{'text-align'} = $properties[-1]->{'text-align'};
$current_prop->{'margin-top'} = _size2pt($properties[-1]->{'margin-top'}, $fs, 'usage'=>'margin-top');
# the incremental right margin, and the running total
$current_prop->{'margin-right'} = _size2pt($properties[-1]->{'margin-right'}, $fs, 'usage'=>'margin-right');
$properties[-1]->{'_right'} += $current_prop->{'margin-right'};
$current_prop->{'margin-bottom'} = _size2pt($properties[-1]->{'margin-bottom'}, $fs, 'usage'=>'margin-bottom');
# the incremental left margin, and the running total
$current_prop->{'margin-left'} = _size2pt($properties[-1]->{'margin-left'}, $fs, 'usage'=>'margin-left');
$properties[-1]->{'_left'} += $current_prop->{'margin-left'};
# line-height is expected to be a multiplier to font-size, so
# % or pts value would have to be converted back to ratio TBD
$current_prop->{'line-height'} = $properties[-1]->{'line-height'}; # numeric ratio
$current_prop->{'display'} = $properties[-1]->{'display'};
$current_prop->{'list-style-type'} = $properties[-1]->{'list-style-type'};
$current_prop->{'list-style-position'} = $properties[-1]->{'list-style-position'}
if defined $properties[-1]->{'list-style-position'};
$current_prop->{'_href'} = $properties[-1]->{'_href'};
# current_prop should now be up to date with properties[-1], and
# any Builder calls have been made
# we're ready to roll, and output the actual text itself
#
# fill line from element $el at current x,y until will exceed endx
# then get next baseline
# if this phrase doesn't finish out the line, will start next
# mytext element at the x,y it left off. otherwise, unused portion
# of phrase (remainder) becomes the next element to process.
$phrase = $mytext[$el]->{'text'}; # there should always be a text
#
# $list_marker was set in li tag processing
# note that ol is bold, ul is Symbol (replace macros .disc, etc.).
# content of li is with new left margin. first line ($list_marker
# ne '') text_right of $list_marker at left margin of li text.
# then set $list_marker to '' to cancel out until next li.
$remainder = '';
# for now, all whitespace convert to single blanks
# TBD blank preserve for <code> or <pre> (CSS white-space)
$phrase =~ s/\s+/ /g;
# click areas ------------------------------------------------------
# if 'annot' field (attribute) exists for a text, we want to define
# a rectangle around it for an annotation click area (several
# rectangles, even across multiple columns, are possible if the
# phrase is long enough to split in the middle).
# value = element number in state->xrefs array to update rect
# with [ UL, LR ] values being assembled
# at end (when LR done), push to state->xrefs->[elno]{click}
# (could already have one or more subarrays)
my $click_ele;
if (defined $mytext[$el]->{'annot'}) {
$click_ele = $mytext[$el]->{'annot'};
$click_ele = $state->{'xrefs'}->[$click_ele]{'click'};
# for every chunk of text the phrase gets split into, push
# an element on the 'click' anonymous array, consisting of
# the [sppn, [ULx,ULy, LRx,LRy]]
}
# output text itself -----------------------------------------------
# a phrase may have multiple words. see if entire thing fits, and if
# not, start trimming off right end (split into a new element)
while ($phrase ne '') {
# one of four things to handle:
# 1. entire phrase fits at x -- just write it out
# 2. none of phrase fits at x (all went into remainder) --
# go to next line to check and write (not all may fit)
# 3. phrase split into (shortened) phrase (that fits) and a
# remainder -- write out phrase, remainder to next line to
# check and write (not all may fit)
# 4. phrase consists of just one word, AND it's too long to
# fit on the full line. it must be split somewhere to fit
# the line.
my ($x_click, $y_click, $y_click_bot);
my $full_line = 0;
# this is to force start of a new line at start_y?
# phrase still has content, and there may be remainder.
# don't forget to set the new start_y when need_line=1
if ($need_line) {
# first, set font (current, or something specified)
if ($topCol) { # at top of column, font undefined
$text->font($pdf->get_font('face'=>'current'), $fs);
}
# extents above and below the baseline (so far)?
($asc, $desc, $desc_leading) =
_get_fv_extents($pdf, $font_size,
$properties[-1]->{'line-height'});
$next_y = $start_y - $add_y - $asc + $desc_leading;
# did we go too low? will return -1 (start_x) and
# remainder of input
# don't include leading when seeing if line dips too low
if ($start_y - $add_y - $asc + $desc < $min_y) { last; }
# start_y and next_y are vertical extent of this line
# (so far)
# y is the y value of the baseline (so far)
$y = $start_y - $add_y - $asc;
# how tall is the line? need to set baseline. add_y is
# any paragraph top margin to drop further. note that this
# is just the starting point -- the line could get taller
($start_x,$y, $width) = _get_baseline($y, @outline);
$x = $start_x + $properties[-1]->{'_left'};
$width -= $properties[-1]->{'_left'} + $properties[-1]->{'_right'};
$endx = $x + $width;
# at this point, we have established the next baseline
# (x,y start and width/end x). fill this line.
$x += $add_x; $add_x = 0; # indent
$add_y = 0; # para top margin extra
$need_line = 0;
$full_line = 1;
# was there already a "desired x" value, such as <_move>?
if (defined $desired_x) {
$x = $desired_x;
$desired_x = undef;
}
# stuff to remember if need to shift line down due to
# vertical extents increase
# TBD: may need to change LR corner of last line of an
# annotation click area if content further along line
# moves baseline down
@line_extents = ();
push @line_extents, $start_x; # current baseline's start
push @line_extents, $x; # current baseline
# note that $x advances with each write
push @line_extents, $y;
push @line_extents, $width;
push @line_extents, $endx;
push @line_extents, $next_y;
push @line_extents, $asc; # current vertical extents
push @line_extents, $desc;
push @line_extents, $desc_leading;
# text and graphics contexts and
# where the current line starts in the streams
push @line_extents, $text;
push @line_extents, length($text->{' stream'});
push @line_extents, $grfx;
if (defined $grfx && ref($grfx) =~ m/^PDF::Builder::Content/) {
push @line_extents, length($grfx->{' stream'});
} else {
push @line_extents, 0;
}
push @line_extents, $start_y;
push @line_extents, $min_y;
push @line_extents, \@outline;
push @line_extents, $properties[-1]->{'_left'};
#push @line_extents, $properties[-1]->{'_left_nest'};
push @line_extents, $properties[-1]->{'_right'};
# if starting a line, make sure no leading whitespace
# TBD if pre, don't remove whitespace
$phrase =~ s/^\s+//;
} else {
# cancel desired_x if not used
$desired_x = undef;
}
# have a phrase to attempt to add to output, and an
# x,y to start it at (tentative if start of line)
# x is current user-specified position to align at, and
# if not LJ, will be adjusted so write is CJ or RJ there
my $w = $text->advancewidth($phrase); # will use $w later
my $align = $properties[-1]->{'text-align'};
if ($align eq 'c' || $align eq 'center') {
$x -= $w/2; # back up 1/2 phrase to real starting point
if ($x+$x_adj < $start_x) {
carp "Centered text of width $w: left edge ".($x+$x_adj)." is left of column start $start_x. Results unpredictable.\n";
}
if ($x+$x_adj+$w > $endx) {
carp "Centered text of width $w: right edge ".($x+$x_adj+$w)." is right of column end $endx. Results unpredictable.\n";
}
$text->translate($x+$x_adj, $y+$y_adj);
} elsif ($align eq 'r' || $align eq 'right') {
$x -= $w; # back up by phrase to real starting point
if ($x+$x_adj < $start_x) {
carp "Right-aligned text of width $w: left edge ".($x+$x_adj)." is left of column start $start_x. Results unpredictable.\n";
}
if ($x+$x_adj+$w > $endx) {
carp "Right-aligned text of width $w: right edge ".($x+$x_adj+$w)." is right of column end $endx. Results unpredictable.\n";
}
$text->translate($x+$x_adj, $y+$y_adj);
} else { # align l/left
# no x adjustment for phrase width
$text->translate($x+$x_adj, $y+$y_adj);
}
$align = 'left'; # have set x,y to actual start point
# $x,$y is where we will actually start writing the phrase
# (adjusted per text-align setting)
if ($x + $w <= $endx) {
my $rc;
# no worry, the entire phrase fits (case 1.)
# y (and possibly x) might change if extents change
my $w = $text->advancewidth($phrase);
if ($current_prop->{'text-decoration'} ne 'none') {
# output any requested line strokes, after baseline
# positioned and before baseline adjusted
# supported: underline, line-through, overline
# may be a combination separated by spaces
# inherit current color (strokecolor) setting
my $font = $pdf->get_font('face'=>'current');
my $upem = $font->upem();
my $strokethickness = $font->underlinethickness() || 1;
$strokethickness *= $fs/$upem;
my $stroke_ydist = $font->underlineposition() || 1;
# don't stroke through any trailing whitespace
my $trail = 0; # width of WS
if ($phrase =~ m/(\s+)$/) {
$trail = $text->advancewidth($1);
}
$stroke_ydist *= $fs/$upem;
# TBD consider whether to draw lines in graphics
# context instead (could end up with text under line)
$text->add('ET'); # go into graphics mode
$text->add("$strokethickness w");
# baseline is x,y to x+w,y, ydist is < 0
if ($current_prop->{'text-decoration'} =~ m#underline#) {
# use ydist as-is
$text->add("$x ".($y+$stroke_ydist)." m");
$text->add(($x+$w-$trail)." ".($y+$stroke_ydist)." l");
}
if ($current_prop->{'text-decoration'} =~ m#line-through#) {
# use new ydist at .3fs
$stroke_ydist = 0.3*$fs;
$text->add("$x ".($y+$stroke_ydist)." m");
$text->add(($x+$w-$trail)." ".($y+$stroke_ydist)." l");
}
if ($current_prop->{'text-decoration'} =~ m#overline#) {
# use new ydist at 0.65fs
$stroke_ydist = 0.70*$fs;
$text->add("$x ".($y+$stroke_ydist)." m");
$text->add(($x+$w-$trail)." ".($y+$stroke_ydist)." l");
}
$text->add('S'); # always stroke the line
$text->add('BT'); # back into text mode
# after BT, need to restore position
$text->translate($x,$y);
} # handle text-decoration
# before writing a new phrase with possibly increased
# extents, see if new baseline needed
# extents above and below the baseline (so far)?
my ($n_asc, $n_desc, $n_desc_leading) =
_get_fv_extents($pdf, $current_prop->{'font-size'},
$properties[-1]->{'line-height'});
$line_extents[1] = $x; # current position
($rc, @line_extents) =
_revise_baseline(@line_extents, $n_asc, $n_desc, $n_desc_leading, $w);
($start_x, $x, $y, $width, $endx, $next_y,
$asc, $desc, $desc_leading)
= @line_extents; # only parts which might have changed
# if rc == 0, line successfully moved down page
# if rc == 1, existing line moved down, but need to check if
# still room for $phrase
# if rc == 2, current written line doesn't fit narrower line
# if rc == 3, revised line won't fit in column! (vertically)
# TBD need to check $rc once column width can vary
# if annotation click area, remember x and y
if (defined $click_ele) {
# UL corner, best guess for y value
$x_click = int($x +0.5);
$y_click = int($y + 0.8*$fs +0.5);
$y_click_bot = int($y_click - $leading*$fs +0.5);
}
$text->text($phrase); # have already corrected start point
# if adjusted x and/or y, undo it and zero out
if ($x_adj || $y_adj) {
$text->translate($x, $y);
$x_adj = $y_adj = 0;
}
if ($current_prop->{'_href'} ne '') {
# this text is a link, so need to make an annot. link
# $x,$y is baseline left, $w is width
# $asc, $desc are font ascenders/descenders
# some extra margin to make it easier to select
my $fs = 0.2*$current_prop->{'font-size'};
my $rect = [ $x-$fs, $y-$desc-3*$fs,
$x+$w+$fs, $y+$asc+$fs ];
# TBD what if link wraps around? make two or more?
my $annotation = $page->annotation();
my $href = $current_prop->{'_href'};
# TBD: href=pdf:docpath.pdf#p.x.y.z jump to another PDF
if ($href =~ m/^#/) {
# href starts with # so it's a jump within this doc
my ($pageno, $xpos, $ypos, $zoom);
if ($href =~ m/^#(\d+)$/) {
# #p format (whole page)
$pageno = $1;
$xpos = $ypos = $zoom = undef;
} elsif ($href =~ m/^#(\d+)-(\d+)-(\d+)$/) {
# #p-x-y format (no zoom, at a specific spot)
$pageno = $1;
$xpos = $2;
$ypos = $3;
$zoom = undef;
} elsif ($href =~ m/^#(\d+)-(\d+)-(\d+)-(.+)$/) {
# #p-x-y-z format (zoom, at a specific spot)
$pageno = $1; # integer > 0
$xpos = $2; # number >= 0
$ypos = $3; # number >= 0
$zoom = $4; # number >= 0
if ($zoom <= 0) {
carp "Invalid zoom value $zoom. Using 1";
$zoom = 1;
}
} else {
# bad format
carp "Invalid link format '$href'. Using page 1";
$pageno = 1;
$xpos = $ypos = $zoom = undef;
}
if ($pageno < 1) {
carp "Invalid page number $pageno. Using page 1";
$pageno = 1;
}
if (defined $xpos && $xpos < 0) {
carp "Invalid page x coordinate $xpos. Using x=100";
$xpos = 100;
}
if (defined $ypos && $ypos < 0) {
carp "Invalid page y coordinate $ypos. Using y=300";
$ypos = 300;
}
my $tgt_page = $pdf->open_page($pageno);
if (!defined $tgt_page) {
carp "Invalid page number $pageno. Using page 1";
$pageno = 1;
$tgt_page = $pdf->open_page($pageno);
}
if (!defined $xpos) {
# page only
$annotation->link($tgt_page,
'rect'=>$rect, 'border'=>[0,0,0]);
} else {
# page at a location and zoom factor
$annotation->link($tgt_page,
'rect'=>$rect, 'border'=>[0,0,0],
'xyz'=>[ $xpos,$ypos, $zoom ]);
}
} else {
# webpage (usually HTML) link
$annotation->uri($href,
'rect'=>$rect, 'border'=>[0,0,0]);
}
} # deal with an href
# need to move current x to right end of text just written
# TBD: revise if RTL/bidirectional
$x += $w;
# whether or not the full phrase fit, we need to create the
# annotation click area and the annotation for this line
if (defined $click_ele) {
my $ele = [$ppn, [$x_click,$y_click, $x,$y_click_bot]];
# push this element 'ele' onto the list at click_ele
my @click = @$click_ele; # initially empty
push @click, $ele;
$click_ele = \@click;
$state->{'xrefs'}->[$mytext[$el]->{'annot'}]{'click'} = $click_ele;
# TBD when last chunk of phrase has been output, if
# 'other_pg' used, need to update that text element
# (following </_ref>) as well as set flag that this
# has changed (if true)
}
$full_line = 0;
$need_line = 0;
# change current property display to inline
$current_prop->{'display'} = 'inline';
# next element in mytext (try to fit on same line)
$phrase = $remainder; # may be empty
$remainder = '';
# since will start a new line, trim leading w/s
$phrase =~ s/^\s+//; # might now be empty
if ($phrase ne '') {
# phrase used up, but remainder for next line
$need_line = 1;
$start_y = $next_y;
}
next; # done with phrase loop if phrase empty
# end of handling entire phrase fits
} else {
# existing line plus phrase is too long (overflows line)
# entire phrase does NOT fit (case 2 or 3). start splitting
# up phrase, beginning with stripping space(s) off end
if ($phrase =~ s/(\s+)$//) {
# remove whitespace at end (line will end somewhere
# within phrase, anyway)
$remainder = $1.$remainder;
} else {
# Is line too short to fit even the first word at the
# beginning of the line? force split in word somewhere
# so that it fits.
my $word = $phrase;
$word =~ s/^\s+//; # probably not necessary, but doesn't hurt
$word =~ s/\s+$//;
if ($full_line && index($word, ' ') == -1) {
my ($wordLeft, $wordRight);
# is a single word at the beginning of the line,
# and didn't fit
require PDF::Builder::Content::Hyphenate_basic;
($wordLeft,$wordRight) = PDF::Builder::Content::Hyphenate_basic::splitWord($text, $word, $endx-$x);
if ($wordLeft eq '') {
# failed to split. try desperation move of
# splitting at Non Splitting SPace!
($wordLeft,$wordRight) = PDF::Builder::Content::Hyphenate_basic::splitWord($text, $word, $endx-$x, 'spRB'=>1);
if ($wordLeft eq '') {
# super-desperation move... split to fit
# space! eventually with proper hyphenation
# this probably will never be needed.
($wordLeft,$wordRight) = PDF::Builder::Content::Hyphenate_basic::splitWord($text, $word, $endx-$x, 'spFS'=>1);
}
}
$phrase = $wordLeft;
$remainder = "$wordRight $remainder";
next; # re-try shortened phrase
}
# phrase should end with non-whitespace if here.
# try moving last word to remainder
if ($phrase =~ s/(\S+)$//) {
# remove word at end
$remainder = $1.$remainder;
}
}
# at least part of text will end up on another line.
# find current <p> and add cont=>1 to it to mark
# continuation in case we end up at end of column
for (my $ptag=$el-1; $ptag>1; $ptag--) {
if ($mytext[$ptag]->{'text'} ne '') { next; }
if ($mytext[$ptag]->{'tag'} ne 'p') { next; }
$mytext[$ptag]->{'cont'} = 1;
last;
}
if ($phrase eq '' && $remainder ne '') {
# entire phrase goes to next line
$need_line = 1;
$start_y = $next_y;
$add_x = $add_y = 0;
$phrase = $remainder;
$remainder = '';
}
next;
} # phrase did not fit (else)
# 'next' to here
} # end of while phrase has content loop
# remainder should be '' at this point, phrase may have content
# either ran out of phrase, or ran out of column
if ($phrase eq '') {
# ran out of input text phrase, so process more elements
# but first, remove this text from mytext array so won't be
# accidentally repeated
splice(@mytext, $el, 1);
$el--;
next;
}
# could get here if exited loop due to running out of column,
# in which case, phrase has to be stuffed back into mytext
$mytext[$el]->{'text'} = $phrase;
last;
} # text to output
# =================== done with this element? ==========================
# end of processing this element in mytext, UNLESS it was text (phrase)
# and we ran out of column space!
if ($phrase ne '') {
# we left early, with incomplete text, because we ran out of
# column space. can't process any more elements -- done with column.
# mytext[el] already updated with remaining text
last; # exit mytext loop
} else {
# more elements to go
next;
}
# 'next' to here
} # for $el loop through mytext array over multiple lines
# if get to here, is it because we ran out of mytext (normal loop exit), or
# because we ran out of space in the column (early exit, in middle of a
# text element)?
#
# for whatever reason we're exiting, remove first array element (default
# CSS entries). it is always re-created on entry to column(). leave next
# element (consolidated <style> tags, if any).
shift @mytext;
if ($#mytext == 0) {
# [0] = consolidated styles (default styles was just removed)
# we ran out of input. return next start_y and empty list ref
# first, handle restore = 0, 1, or 2
if ($restore == 0) {
# carry out pending font and color changes
# what properties have changed and need PDF calls to update?
my $call_get_font = 0;
if ($properties[-1]->{'font-family'} ne $current_prop->{'font-family'}) {
$call_get_font = 1;
# a font label known to FontManager
$current_prop->{'font-family'} = $properties[-1]->{'font-family'};
}
if ($properties[-1]->{'font-style'} ne $current_prop->{'font-style'}) {
$call_get_font = 1;
# normal or italic
$current_prop->{'font-style'} = $properties[-1]->{'font-style'};
}
if ($properties[-1]->{'font-weight'} ne $current_prop->{'font-weight'}) {
$call_get_font = 1;
# normal or bold
$current_prop->{'font-weight'} = $properties[-1]->{'font-weight'};
}
# font size
# don't want to trigger font call unless numeric value changed
# current_prop's s/b in points, newval will be in points. if
# properties (latest request) is a relative size (e.g., %),
# what it is relative to is NOT the last font size used
# (current_prop), but carried-along current font size.
my $newval = _size2pt($properties[-1]->{'font-size'},
$properties[-1]->{'_parent-fs'}, 'usage'=>'font-size');
# newval is the latest requested size (in points), while
# current_prop is last one used for output (in points)
if ($newval != $current_prop->{'font-size'}) {
$call_get_font = 1;
$current_prop->{'font-size'} = $newval;
}
# any size as a percentage of font-size will use the current fs
my $fs = $current_prop->{'font-size'};
if ($call_get_font) {
$text->font($pdf->get_font(
'face' => $current_prop->{'font-family'},
'italic' => ($current_prop->{'font-style'} eq 'normal')? 0: 1,
'bold' => ($current_prop->{'font-weight'} eq 'normal')? 0: 1,
), $fs);
}
# font-size should be set in current_prop for use by margins, etc.
# don't know if color will be used for text or for graphics draw,
# so set both
if ($properties[-1]->{'color'} ne $current_prop->{'color'}) {
$current_prop->{'color'} = $properties[-1]->{'color'};
$text->fillcolor($current_prop->{'color'});
$text->strokecolor($current_prop->{'color'});
if (defined $grfx && ref($grfx) =~ m/^PDF::Builder::Content/ ) {
$grfx->fillcolor($current_prop->{'color'});
$grfx->strokecolor($current_prop->{'color'});
}
}
} elsif ($restore == 1) {
# do nothing, leave the font state/colors as-is
} else { # 2
# restore to entry with @entry_state
return (2, $next_y - ($vmargin[0]+$vmargin[1]), []);
}
return (0, $next_y - ($vmargin[0]+$vmargin[1]), []);
} else {
# we ran out of vertical space in the column. return -1 and
# remainder of mytext list (next_y would be inapplicable)
# first, handle restore = 0, 1, or 2
if ($restore == 0 || $restore == 1) {
# do nothing, leave the font state/colors as-is
} else { # 2
# restore to entry with @entry_state
return (3, -1, \@mytext);
}
return (1, -1, \@mytext);
}
} # end of _output_text()
# initialize current property settings to values that will cause updates (PDF
# calls) when the first real properties are determined, and thereafter whenever
# these properties change
sub _init_current_prop {
my $cur_prop = {};
# NOTE that all lengths must be in points (unitless), ratios are
# pure numbers, named things are strings.
$cur_prop->{'font-size'} = -1;
$cur_prop->{'line-height'} = 0; # alias is text-height until release 3.030
$cur_prop->{'text-indent'} = 0;
$cur_prop->{'color'} = 'snork'; # PDF default is black
$cur_prop->{'font-family'} = 'yoMama'; # force a change
$cur_prop->{'font-weight'} = 'abnormal';
$cur_prop->{'font-style'} = 'abnormal';
#$cur_prop->{'font-variant'} = 'abnormal';
$cur_prop->{'margin-top'} = '0';
$cur_prop->{'margin-right'} = '0';
$cur_prop->{'margin-bottom'} = '0';
$cur_prop->{'margin-left'} = '0';
$cur_prop->{'text-align'} = 'left';
#$cur_prop->{'text-transform'} = 'none';
#$cur_prop->{'border'} = 'none'; # NOT inherited
#$cur_prop->{'border-style'} = 'none'; # NOT inherited
#$cur_prop->{'border-width'} = '1pt'; # NOT inherited
#$cur_prop->{'border-color'} = 'inherit'; # NOT inherited
$cur_prop->{'text-decoration'} = 'none';
#$cur_prop->{'text-decoration-skip-ink'}; for underline etc.
$cur_prop->{'display'} = 'block'; # inline, TBD inline-block, none
$cur_prop->{'height'} = '0'; # currently <hr> only, NOT inherited
$cur_prop->{'width'} = '0'; # currently <hr> only, NOT inherited
$cur_prop->{'list-style-type'} = '.u';
$cur_prop->{'list-style-position'} = 'outside';
$cur_prop->{'_marker-before'} = '';
$cur_prop->{'_marker-after'} = '.';
$cur_prop->{'_marker-color'} = '';
$cur_prop->{'_marker-font'} = '';
$cur_prop->{'_marker-size'} = '0';
$cur_prop->{'_marker-style'} = '';
$cur_prop->{'_marker-text'} = '';
$cur_prop->{'_marker-weight'} = '';
$cur_prop->{'_marker-align'} = 'right';
$cur_prop->{'_href'} = '';
return $cur_prop;
} # end of _init_current_prop()
# update a properties hash for a specific selector (all, if not given)
# in all but a few cases, a higher level selector overrides a lower level by
# simply replacing the old content, but in some, property values are
# combined
sub _update_properties {
my ($target, $source, $selector) = @_;
my $tag = '';
if (defined $selector) {
if ($selector =~ m#^tag:(.+)$#) {
$tag = $1;
$selector = undef;
}
}
if (defined $selector) {
if (defined $source->{$selector}) {
foreach (keys %{$source->{$selector}}) {
# $selector e.g., 'u' for underline
# $_ is property name, e.g., 'text-decoration'
# special treatment for text-decoration
if ($_ eq 'text-decoration') {
# 'none' is overwritten, but subsequent values appended
if (defined $target->{$_} && $target->{$_} ne 'none') {
$target->{$_} .= " $source->{$selector}->{$_}";
} else {
$target->{$_} = $source->{$selector}->{$_};
}
} else {
$target->{$_} = $source->{$selector}->{$_};
}
}
}
} else { # selector not defined (use all)
foreach my $tag_sel (keys %$source) { # top-level selectors
if ($tag_sel eq 'text' || $tag_sel eq 'tag') { next; }
if ($tag_sel eq 'cont') { next; } # paragraph continuation flag
if ($tag_sel eq 'body') { next; } # do body selector last
if (ref($source->{$tag_sel}) ne 'HASH') {
# e.g., <a href="..."> the href element is a string, not a
# hashref (ref != HASH), so we put it in directly
$target->{$tag_sel} = $source->{$tag_sel};
} else {
foreach (keys %{$source->{$tag_sel}}) {
$target->{$_} = $source->{$tag_sel}->{$_};
}
}
}
# do body selector last, after others
if (defined $source->{'body'}) {
foreach (keys %{$source->{'body'}}) {
$target->{$_} = $source->{'body'}->{$_};
}
}
}
return;
} # end of _update_properties()
# according to Text::Layout#10, HarfBuzz::Shaper *may* now have per-glyph
# extents. should check some day when HS is supported (but not mandatory)
sub _get_fv_extents {
my ($pdf, $font_size, $leading) = @_;
$leading = 1.0 if $leading <= 0; # actually, a bad value
$leading++ if $leading < 1.0; # might have been given as fractional
my $font = $pdf->get_font('face' => 'current'); # font object realized
# now it's loaded, if it wasn't already
my $ascender = $font->ascender()/1000*$font_size; # positive
my $descender = $font->descender()/1000*$font_size; # negative
# ascender is positive, descender is negative (above/below baseline)
return ($ascender, $descender, $descender-($leading-1.0)*$font_size);
} # end of _get_fv_extents()
# returns a list (array) of x,y coordinates outlining the column defined
# by various options entries. currently only 'rect' is used, to define a
# rectangular outline.
# $grfx is graphics context, non-dummy if 'outline' option given (draw outline)
#
# TBD: what to do if any line too short to use?
sub _get_column_outline {
my ($grfx, $draw_outline, %opts) = @_;
my @outline = ();
# currently only 'rect' supported. TBD: path
if (!defined $opts{'rect'}) {
croak "column: no outline of column area defined";
}
# treat coordinates as absolute, unless 'relative' option given
my $off_x = 0;
my $off_y = 0;
my $scale_x = 1;
my $scale_y = 1;
if (defined $opts{'relative'}) {
my @relative = @{ $opts{'relative'} };
croak "column: invalid number of elements in 'relative' list"
if (@relative < 2 || @relative > 4);
$off_x = $relative[0];
$off_y = $relative[1];
# @relative == 2 use default 1 1 scale factors
if (@relative == 3) { # same scale for x and y
$scale_x = $scale_y = $relative[2];
}
if (@relative == 4) { # different scales for x and y
$scale_x = $relative[2];
$scale_y = $relative[3];
}
}
my @rect = @{$opts{'rect'}}; # if using 'rect' option
push @outline, [$rect[0], $rect[1]]; # UL corner = x,y
# TBD: check x,y reasonable, w,h reasonable
push @outline, [$rect[0]+$rect[2], $rect[1]]; # UR corner + width
push @outline, [$rect[0]+$rect[2], $rect[1]-$rect[3]]; # LR corner - height
push @outline, [$rect[0], $rect[1]-$rect[3]]; # LL corner - width
push @outline, [$rect[0], $rect[1]]; # back to UL corner
# TBD: 'path' option
# treat coordinates as absolute or relative
for (my $i = 0; $i < scalar @outline; $i++) {
$outline[$i][0] = $outline[$i][0]*$scale_x + $off_x;
$outline[$i][1] = $outline[$i][1]*$scale_y + $off_y;
}
# TBD body level background-color fill in outline INK HERE
# if $has_grfx can proceed
# use _change_properties _fcolor background-color
# requested to draw outline (color other than 'none')? INK HERE
if ($draw_outline ne 'none' && defined $grfx && ref($grfx) =~ m/^PDF::Builder::Content/) {
$grfx->strokecolor($draw_outline);
$grfx->linewidth(0.5);
# only rect currently supported
my @flat = ();
for (my $i = 0; $i < scalar @outline; $i++) {
push @flat, $outline[$i][0];
push @flat, $outline[$i][1];
}
$grfx->poly(@flat);
$grfx->stroke();
}
return @outline;
} # end of _get_column_outline()
sub _get_col_extents {
my (@outline) = @_;
my ($minx, $miny, $maxx, $maxy);
# for rect, all pairs are x,y. once introduce splines/arcs, need more
for (my $i = 0; $i < scalar @outline; $i++) {
if ($i == 0) {
$minx = $maxx = $outline[$i][0];
$miny = $maxy = $outline[$i][1];
} else {
$minx = min($minx, $outline[$i][0]);
$miny = min($miny, $outline[$i][1]);
$maxx = max($maxx, $outline[$i][0]);
$maxy = max($maxy, $outline[$i][1]);
}
}
return ($minx, $miny, $maxx, $maxy);
} # end of _get_col_extents()
# get the next baseline from column outline @outline
# the first argument is the y value of the baseline
# we've already checked that there is room in this column, so y is good
# returns on-page x,y, and width of baseline
# currently expect outline to be UL UR LR LL UL coordinates.
# TBD: arbitrary shape with line at start_y clipped by outline (if multiple
# lines result, pick longest or first one)
sub _get_baseline {
my ($start_y, @outline) = @_;
my ($x,$y, $width);
$x = $outline[0][0];
$y = $start_y;
$width = $outline[1][0] - $x;
# note that this is the baseline, so it is possible that some
# descenders may exceed the limit, in a non-rectangular outline!
return ($x,$y, $width);
} # end of _get_baseline()
# returns array of hashes with prepared text. input could be
# 'pre' markup: must be an array (list) of hashes, returned unchanged.
# 'none' markup: empty lines separate paragraphs, array of texts permitted,
# paragraphs may not span array elements.
# 'md1' markup: empty lines separate paragraphs, array of texts permitted,
# paragraphs may span array elements, content is converted to HTML
# per Text::Markdown, one array element at a time.
# 'md2' markup: similar to md1, but using Text::MultiMarkdown TBD
# 'html' markup: single text string OR array of texts permitted (consolidated
# into one text), containing HTML markup.
#
# each element is a hash containing the text and all attributes (HTML or MD
# has been processed).
sub _break_text {
my ($text, $markup, %opts) = @_;
my $page_numbers = 0;
$page_numbers = $opts{'page_numbers'} if defined $opts{'page_numbers'};
my @array = ();
if ($markup eq 'pre') {
# should already be in final format (such as continuing a column)
return @$text;
} elsif ($markup eq 'none') {
# split up on blank lines into paragraphs and wrap with p and /p tags
if (ref($text) eq '') {
# is a single string (scalar)
@array = _none_hash($text, %opts);
} elsif (ref($text) eq 'ARRAY') {
# array ref, elements should be text
for (my $i = 0; $i < scalar(@$text); $i++) {
@array = (@array, _none_hash($text->[$i], %opts));
}
}
# dummy style element at array element [0]
my $style;
$style->{'tag'} = 'style';
$style->{'text'} = '';
unshift @array, $style;
} elsif ($markup eq 'md1') {
# process into HTML, then feed to HTML processing to make hash
# note that blank-separated lines already turned into paragraphs
if (ref($text) eq '') {
# is a single string (scalar)
@array = _md1_hash($text, %opts);
} elsif (ref($text) eq 'ARRAY') {
# array ref, elements should be text
@array = _md1_hash(join("\n", @$text), %opts);
}
# ### no MultiMarkdown until br, code, pre tags supported
# ### update Column.pl sample, README.md, Column_doc.pm
# ### update TextMultiMarkdown min version in build routines
# } elsif ($markup eq 'md2') {
# # process into HTML, then feed to HTML processing to make hash
# # note that blank-separated lines already turned into paragraphs
# if (ref($text) eq '') {
# # is a single string (scalar)
# @array = _md2_hash($text, %opts);
#
# } elsif (ref($text) eq 'ARRAY') {
# # array ref, elements should be text
# @array = _md2_hash(join("\n", @$text), %opts);
# }
} else { # should be 'html'
if (ref($text) eq '') {
# is a single string (scalar)
@array = _html_hash($page_numbers, $text, %opts);
} elsif (ref($text) eq 'ARRAY') {
# array ref, elements should be text
# consolidate into one string.
@array = _html_hash($page_numbers, join("\n", @$text), %opts);
}
}
return @array;
} # end of _break_text()
# convert unformatted string to array of hashes, splitting up on blank lines.
# return with only markup as paragraphs
# note that you can NOT span a paragraph across array elements
sub _none_hash {
my ($text, %opts) = @_;
my @array = ();
my $in_para = 0;
my $line = '';
chomp($text); # don't want empty last element due to trailing \n
foreach (split /\n/, $text) {
# should be no \n's, but adjacent non-empty lines need to be joined
if ($_ =~ /^\s*$/) {
# empty/blank line. end paragraph if one in progress
if ($in_para) {
push @array, {'tag' => '', 'text' => $line};
push @array, {'text' => "", 'tag' => '/p'};
$in_para = 0;
$line = '';
}
# not in a paragraph, just ignore this entry
} else {
# content in this line. start paragraph if necessary
if ($in_para) {
# accumulate content into line
$line .= " $_";
} else {
# start paragraph, content starts with this text
push @array, {'text' => "", 'tag' => 'p'};
$in_para = 1;
$line = $_;
}
}
} # end of loop through line(s) in paragraph
# out of input.
# if still within a paragraph, need to properly close it
if ($in_para) {
push @array, {'tag' => '', 'text' => $line};
push @array, {'text' => "", 'tag' => '/p'};
$in_para = 0;
$line = '';
}
return @array;
} # end of _none_hash()
# convert md1 string to html, returning array of hashes
# TBD `content` wraps in <code> (OK), but fenced ``` wraps in <p><code> ?!
# may need to preprocess ``` to wrap in <pre> or postprocess add <pre>
# <p><code> -> <p><pre><code>
sub _md1_hash {
my ($text, %opts) = @_;
my $page_numbers = 0;
$page_numbers = $opts{'page_numbers'} if defined $opts{'page_numbers'};
my @array;
my ($html, $rc);
$rc = eval {
require Text::Markdown;
1;
};
if (!defined $rc) { $rc = 0; } # else is 1
if ($rc) {
# installed, but not up to date?
if (version->parse("v$Text::Markdown::VERSION")->numify() <
version->parse("v$TextMarkdown")->numify()) { $rc = 0; }
}
if ($rc) {
# MD converter appears to be installed, so use it
$html = Text::Markdown::markdown($text);
} else {
# leave as MD, will cause a chain of problems
warn "Text::Markdown not installed, can't process Markdown";
$html = $text;
}
# need to fix something in Text::Markdown -- custom HTML tags are
# disabled by changing < to <. change them back!
$html =~ s/<_ref /<_ref /g;
$html =~ s/<_reft /<_reft /g;
$html =~ s/<_nameddest /<_nameddest /g;
$html =~ s/<_sl /<_sl /g;
$html =~ s/<_move /<_move /g;
$html =~ s/<_marker /<_marker /g;
# probably could just do it with s/<_/<_/ but the list is short
# blank lines within a list tend to create paragraphs in list items
$html =~ s/<li><p>/<li>/g;
$html =~ s#</p></li>#</li>#g;
# standard Markdown ~~ line-through (strike-out) not recognized
my $did_one = 1;
while ($did_one) {
$did_one = 0;
if ($html =~ s#~~([^~])#<del>$1#) {
# just one at a time. replace ~~ by <del>
$did_one = 1;
}
# should be another, replace ~~ by </del>
$html =~ s#~~([^~])#</del>$1#;
}
# standard Markdown === by itself not recognized as a horizontal rule
$html =~ s#<p>===</p>#<hr>#g;
# dummy (or real) style element will be inserted at array element [0]
# by _html_hash()
# blank-line separated paragraphs already wrapped in <p> </p>
@array = _html_hash($page_numbers, $html, %opts);
return @array;
} # end of _md1_hash()
# convert md2 string to html, returning array of hashes
#sub _md2_hash {
# my ($text, %opts) = @_;
# my $page_numbers = 0;
# $page_numbers = $opts{'page_numbers'} if defined $opts{'page_numbers'};
#
# my @array;
# my ($html, $rc);
# $rc = eval {
# require Text::MultiMarkdown;
# 1;
# };
# if (!defined $rc) { $rc = 0; } # else is 1
# if ($rc) {
# # installed, but not up to date?
# if (version->parse("v$Text::MultiMarkdown::VERSION")->numify() <
# version->parse("v$TextMultiMarkdown")->numify()) { $rc = 0; }
# }
#
# my $heading_ids = 0; # default no automatic id generation for hX
# if (defined $opts{'heading_ids'}) { $heading_ids = $opts{'heading_ids'}; }
#
# if ($rc) {
# # MD converter appears to be installed, so use it
# $html = Text::MultiMarkdown->new(
# 'heading_ids' => $heading_ids,
# 'img_ids' => 0,
# 'empty_element_suffix' => '>',
# )->markdown($text);
# } else {
# # leave as MD, will cause a chain of problems
# warn "Text::MultiMarkdown not installed, can't process Markdown";
# $html = $text;
# }
#
# # need to fix something in Text::Markdown -- custom HTML tags are
# # disabled by changing < to <. change them back!
# $html =~ s/<_ref /<_ref /g;
# $html =~ s/<_reft /<_reft /g;
# $html =~ s/<_nameddest /<_nameddest /g;
# $html =~ s/<_sl /<_sl /g;
# $html =~ s/<_move /<_move /g;
# $html =~ s/<_marker /<_marker /g;
# # probably could just do it with s/<_/<_/ but the list is short
#
# # blank lines within a list tend to create paragraphs in list items
# $html =~ s/<li><p>/<li>/g;
# $html =~ s#</p></li>#</li>#g;
#
# # standard Markdown ~~ line-through (strike-out) not recognized
# my $did_one = 1;
# while ($did_one) {
# $did_one = 0;
# if ($html =~ s#~~([^~])#<del>$1#) {
# # just one at a time. replace ~~ by <del>
# $did_one = 1;
# }
# # should be another, replace ~~ by </del>
# $html =~ s#~~([^~])#</del>$1#;
# }
#
# # standard Markdown === by itself not recognized as a horizontal rule
# $html =~ s#<p>===</p>#<hr>#g;
#
# # dummy (or real) style element will be inserted at array element [0]
# # by _html_hash()
#
# # blank-line separated paragraphs already wrapped in <p> </p>
# @array = _html_hash($page_numbers, $html, %opts);
#
# return @array;
#} # end of _md2_hash()
# convert html string to array of hashes. this is for both 'html' markup and
# the final step of 'md1' or 'md2' markup.
# returns array (list) of tags and text, and as a side effect, element [0] is
# consolidated <style> tags (may be empty hash)
sub _html_hash {
my ($page_numbers, $text, %opts) = @_;
my $style = {}; # <style> hashref to return
my @array; # array of body tags and text to return
my ($rc);
# process 'substitute' stuff here. %opts needs to be passed in!
if (defined $opts{'substitute'}) {
# array of substitutions to make
foreach my $macro_list (@{$opts{'substitute'}}) {
# 4 element array: macro name (including any delimiters, such as ||)
# HTML code to insert before the macro
# anything to replace the macro name (could be the
# macro name itself if you want it unchanged)
# HTML code to insert after the macro
# $text is updated, perhaps multiple times
# $macro_list is anonymous array [ macro, before, rep, after ]
my $macro = $macro_list->[0];
my $sub = $macro_list->[1].$macro_list->[2].$macro_list->[3];
$text =~ s#$macro#$sub#g;
}
}
$rc = eval {
require HTML::TreeBuilder;
1;
};
if (!defined $rc) { $rc = 0; } # else is 1
if ($rc) {
# installed, but not up to date?
if (version->parse("v$HTML::TreeBuilder::VERSION")->numify() <
version->parse("v$HTMLTreeBldr")->numify()) { $rc = 0; }
}
if ($rc) {
# HTML converter appears to be installed, so use it
$HTML::Tagset::isList{'_sl'} = 1; # add new list parent
push @HTML::Tagset::p_closure_barriers, '_sl';
$HTML::Tagset::emptyElement{'_reft'} = 1; # don't add closing tag
$HTML::Tagset::emptyElement{'_nameddest'} = 1; # don't add closing tag
$HTML::Tagset::isPhraseMarkup{'_ref'} = 1;
$HTML::Tagset::isPhraseMarkup{'_reft'} = 1;
$HTML::Tagset::isPhraseMarkup{'_nameddest'} = 1;
my $tree = HTML::TreeBuilder->new();
$tree->ignore_unknown(0); # don't discard non-HTML recognized tags
$tree->no_space_compacting(1); # preserve spaces
$tree->warn(1); # warn if syntax error found
$tree->p_strict(1); # auto-close paragraph on new block element
$tree->implicit_body_p_tag(1); # loose text gets wrapped in <p>
$tree->parse_content($text);
# see if there is a <head>, and if so, if any <style> tags within it
my $head = $tree->{'_head'}; # a hash
if (defined $head and defined $head->{'_content'}) {
my @headList = @{ $head->{'_content'} }; # array of strings and tags
@array = _walkTree(0, @headList);
# pull out one or more style tags and build $styles hash
for (my $el = 0; $el < @array; $el++) {
my $style_text = $array[$el]->{'text'};
if ($style_text ne '') {
# possible style content. style tag immediately before?
if (defined $array[$el-1]->{'tag'} &&
$array[$el-1]->{'tag'} eq 'style') {
$style = _process_style_tag($style, $style_text);
}
}
}
} # $style is either empty hash or has style content
# there should always be a body of some sort
my $body = $tree->{'_body'}; # a hash
my @bodyList = @{ $body->{'_content'} }; # array of strings and tags
@array = _walkTree(0, @bodyList);
# pull out one or more style tags and add to $styles hash
for (my $el = 0; $el < @array; $el++) {
my $style_text = $array[$el]->{'text'};
if ($style_text ne '') {
# possible style content. style tag immediately before?
if (defined $array[$el-1]->{'tag'} &&
$array[$el-1]->{'tag'} eq 'style') {
$style = _process_style_tag($style, $style_text);
# remove <style> from body (array list)
splice(@array, $el-1, 3);
}
}
} # $style is either empty hash or has style content
} else {
# leave as original HTML, will cause a chain of problems
warn "HTML::TreeBuilder not installed, can't process HTML";
push @array, {'tag' => '', 'text' => $text};
}
# does call include a style initialization (opt in column() call)?
# merge into any consolidated <style> tags for user styling in [1]
if (defined $opts{'style'}) {
# $style could be empty hash ptr at this point
$style = _process_style_tag($style, $opts{'style'});
}
# always first element tag=style containing the hash, even if it's empty
# array[0] is default CSS, array[1] is consolidated <style> tags
$style->{'tag'} = 'style';
$style->{'text'} = '';
unshift @array, $style; # [0] default CSS added later
# HTML::TreeBuilder does some undesirable things with custom tags
# it doesn't understand. clean them up.
@array = _HTB_cleanup($page_numbers, $opts{'debug'}, @array);
return @array;
} # end of _html_hash()
# clean up some things HTML::TreeBuilder does when it sees unknown tag.
# this is done at creation of the tag/content array, so no need to worry
# about 'pre' input format and the like.
sub _HTB_cleanup {
my ($page_numbers, $debug, @mytext) = @_;
my @current_list = ('empty');
# loop through all elements, looking for specific patterns
# start at [1], so defaults and styles skipped
for (my $el=1; $el < @mytext; $el++) {
if (ref($mytext[$el]) ne 'HASH') { next; }
if ($mytext[$el]->{'tag'} eq '') { next; }
my $tag = lc($mytext[$el]->{'tag'});
$mytext[$el]->{'tag'} = $tag; # lc the tag
if (!defined $tag) { next; }
#if ($tag =~ m#^/#) { next; } # ignore end tags?
if ($tag eq 'li') {
# dealing with <_marker> is a special case, driven by need to
# ensure that all <li> tags have a <_marker>[text]</_marker>
# just before them, and is not a shortcoming of HTML::TreeBuilder
#
# if user did not explicitly give a <_marker> just before <li>,
# insert one to "even up" with any in the source.
# $el element ($tag) s/b at 'li' at this point
# MUST check if HTML::TreeBuilder (or user) added their own
# /_marker tag! and whether explicit text given!
#
# 1. <_marker><li> add text='' and </_marker>
# 2. <_marker></_marker><li> add text='' in between
# 3. <_marker>text</_marker><li> no change (text may be '')
# use this user-provided marker text; do not replace
# 4. <li> add <_marker>text=''</_marker>
#
# Note that HTML::TreeBuilder seems to already track that a list
# (ul) or (ol) is the parent of a li
if ($mytext[$el-1]->{'tag'} eq '/_marker') {
# case 2 or 3, assume there is <_marker> tag
if ($mytext[$el-2]->{'tag'} eq '') {
# case 3, no change to make unless current parent is _sl
# AND text is not ''
if ($current_list[-1] eq 's') {
$mytext[$el-2]->{'text'} = '';
}
} else {
# case 2, add empty text tag between
splice(@mytext, $el-1, 0, {'tag'=>'', 'text'=>''});
$el++;
}
} elsif ($mytext[$el-1]->{'tag'} eq '_marker') {
# case 1
splice(@mytext, $el++, 0, {'tag'=>'', 'text'=>''});
splice(@mytext, $el++, 0, {'tag'=>'/_marker', 'text'=>''});
} else {
# case 4
# we haven't added or expanded a <_marker> here yet
splice(@mytext, $el++, 0, {'tag'=>'_marker', 'text'=>''});
splice(@mytext, $el++, 0, {'tag'=>'', 'text'=>''});
splice(@mytext, $el++, 0, {'tag'=>'/_marker', 'text'=>''});
}
# $el should still point to <li> element, which should now have
# three elements in front of it: <_marker>(empty)</_marker>
# for ul, ol if user gives marker with explicit text, don't replace
# for _sl, text should be '', and marker is mostly ignored
# if user added a non-'' _marker text for _sl, need to remove
} elsif ($tag eq 'ul') {
push @current_list, 'u';
} elsif ($tag eq 'ol') {
push @current_list, 'o';
} elsif ($tag eq '_sl') {
push @current_list, 's';
} elsif ($tag eq '/_sl' || $tag eq '/ol' || $tag eq '/ul') {
pop @current_list;
# already added _sl to list of allowed list parents
} elsif ($tag eq '_ref') {
# should be followed by empty text and then /_ref tag,
# add if either missing. fill in text content with any title=
# attribute in _ref
# tgtid= is mandatory
if (!defined $mytext[$el]->{'tgtid'}) {
carp "Warning! No 'tgtid' defined for a <_ref> tag, no link.";
$mytext[$el]->{'tgtid'} = '';
}
# if tgtid is '#', check if following content is ^\d+-?. if
# not, remove # (is a regular id)
my $tgtid = $mytext[$el]->{'tgtid'};
if ($tgtid =~ m/^#[^#]/) {
# starts with a single '#'
if ($tgtid =~ m/^#\d+-?/) {
# it's a physical page number link, leave it alone
} else {
# it's #id, so strip off leading #
$mytext[$el]->{'tgtid'} = substr($tgtid, 1);
}
}
my $text = $mytext[$el]->{'title'} // '[no title given]';
$text =~ s/\n/ /sg; # any embedded line ends turn to spaces
# most likely, the /_ref has been put AFTER the following text,
# resulting in el=_ref, el+1=random text, >el+1=/_ref
# >el+1 loose end tag will be deleted
if ($mytext[$el+1]->{'tag'} eq '/_ref') {
# <_ref></_ref> insert child text with title
splice(@mytext, ++$el, 0, {'tag'=>'', 'text'=>$text});
$el++;
} elsif ($mytext[$el+1]->{'tag'} eq '' &&
$mytext[$el+1]->{'text'} ne '') {
# # <_ref><other text></_ref> insert text=$text and /_ref
# # giving <_ref><title text></_ref><other text>
# splice(@mytext, ++$el, 0, {'tag'=>'', 'text'=>$text});
# splice(@mytext, ++$el, 0, {'tag'=>'/_ref', 'text'=>''});
# # superfluous /_ref will be deleted
$el+=2;
} elsif ($mytext[$el+1]->{'tag'} eq '' &&
$mytext[$el+1]->{'text'} eq '') {
# <_ref><empty text></_ref> update text with title text
$mytext[++$el]->{'text'} = $text;
# is following /_ref missing?
if ($mytext[++$el]->{'tag'} ne '/_ref') {
splice(@mytext, $el, 0, {'tag'=>'/_ref', 'text'=>''});
}
} else {
# just <_ref>. add text and end tag
splice(@mytext, ++$el, 0, {'tag'=>'', 'text'=>$text});
splice(@mytext, ++$el, 0, {'tag'=>'/_ref', 'text'=>''});
}
# $el should be pointing to /_ref tag
if ($page_numbers != 0 &&
$mytext[$el]->{'tgtid'} !~ /#[^#]/) {
# insert a <text> after </_ref> to hold " on page $",
# " on facing page", etc. TBD page $
# do NOT insert for Named Destination (single # in tgtid)
splice(@mytext, ++$el, 0, {'tag'=>'', 'text'=>" on page \$"});
}
} elsif ($tag eq '/_ref') {
# TreeBuilder often puts end tag after wrong text
#splice(@mytext, $el--, 1);
} elsif ($tag eq '_reft') {
# leave title in place for <_reft>, but delete any text and </_reft>
if ($mytext[$el+1]->{'tag'} eq '' &&
$mytext[$el+2]->{'tag'} eq '/_reft') {
splice(@mytext, $el+1, 2);
} elsif ($mytext[$el+1]->{'tag'} eq '/_reft') {
splice(@mytext, $el+1, 1);
}
} elsif ($tag eq '/_reft') {
# TreeBuilder often puts end tag after wrong text
splice(@mytext, $el--, 1);
} elsif ($tag eq '_nameddest') {
# delete any text and </_nameddest>
if ($mytext[$el+1]->{'tag'} eq '' &&
$mytext[$el+2]->{'tag'} eq '/_nameddest') {
splice(@mytext, $el+1, 2);
} elsif ($mytext[$el+1]->{'tag'} eq '/_nameddest') {
splice(@mytext, $el+1, 1);
}
if (defined $debug && $debug == 1) {
# insert tags to write a blue | bar at beginning of text
# $el should point to _nameddest tag itself
splice(@mytext, $el++, 0, {'tag'=>'span', 'text'=>'',
'style'=>'color: #0000FF; font-weight: bold;'});
splice(@mytext, $el++, 0, {'tag'=>'', 'text'=>'|'});
splice(@mytext, $el++, 0, {'tag'=>'/span', 'text'=>''});
# still pointing at _nameddest tag
}
} elsif ($tag eq '/_nameddest') {
# TreeBuilder often puts end tag after wrong text
splice(@mytext, $el--, 1);
} elsif ($tag eq '/_move') {
# TreeBuilder often puts end tag after wrong text
splice(@mytext, $el--, 1);
} elsif ($tag eq 'a') {
# if a URL, leave as-is. otherwise convert a /a to _ref /_ref
if ($mytext[$el]->{'href'} =~ m#^[a-z0-9]+://#i) {
# protocol:// likely a URL
} else {
# xref link: convert tag
# 1. a tag convert to _ref
$mytext[$el]->{'tag'} = '_ref';
# 1a. need to check if <a href></a> need to insert text?
if ($mytext[$el+1]->{'tag'} ne '') {
# yep, missing child text
splice(@mytext, $el+1, 0, { 'tag'=>'', 'text'=>'' });
}
# 2. /a tag convert to /_ref (next /a seen, does not nest)
for (my $i=$el+1; $i<@mytext; $i++) {
if ($mytext[$i]->{'tag'} eq '/a') {
$mytext[$i]->{'tag'} = '/_ref';
last;
}
}
# 3. href -> tgtid attribute
$mytext[$el]->{'tgtid'} = delete $mytext[$el]->{'href'};
# 4. child text -> title, id, fit attributes
# NOTE: any markup tags get removed, is plain text
my $newtitle = _get_special_info(\@mytext, $el, '{^', '}');
my $newfit = _get_special_info(\@mytext, $el, '{%', '}');
my $newid = _get_special_info(\@mytext, $el, '{#', '}');
if ($newtitle eq '') {
$newtitle = _get_child_text(\@mytext, $el);
}
if (!defined $mytext[$el]->{'title'}) {
$mytext[$el]->{'title'} = $newtitle;
}
# is child (title) text still empty after all this?
if ($mytext[$el+1]->{'text'} eq '') {
$mytext[$el+1]->{'text'} = $mytext[$el]->{'title'};
}
# 5. fit info -> fit attribute (if none exists)
if (defined $mytext[$el]->{'fit'}) {
# already exists, so only remove inline stuff
} else {
if ($newfit ne '') {
$mytext[$el]->{'fit'} = $newfit;
}
}
# 6. id info -> id attribute (if none exists)
if (defined $mytext[$el]->{'id'}) {
# already exists, so only remove inline stuff
} else {
if ($newid ne '') {
$mytext[$el]->{'id'} = $newid;
}
}
# 7. child text is empty? replace by title text
if ($mytext[$el+1]->{'text'} eq '' &&
defined $mytext[$el]->{'title'}) {
$mytext[$el+1]->{'text'} = $mytext[$el]->{'title'};
}
}
}
# any child text (incl. link title) with {#id}? pull out into id=
# this is needed for Markdown (may define, for headings only). not
# necessarily supported by Text::Markdown, or yet by Builder.
# child text in: hX, a, span, p, li, i/em, b/strong, del, sub/sup, mark,
# blockquote, dd/dd, code, pre, img (alt text or title text), th,td
if ($mytext[$el]->{'tag'} eq 'h1' ||
$mytext[$el]->{'tag'} eq 'h2' ||
$mytext[$el]->{'tag'} eq 'h3' ||
$mytext[$el]->{'tag'} eq 'h4' ||
$mytext[$el]->{'tag'} eq 'h5' ||
$mytext[$el]->{'tag'} eq 'h6' ||
$mytext[$el]->{'tag'} eq 'a' ||
$mytext[$el]->{'tag'} eq 'span' ||
$mytext[$el]->{'tag'} eq 'p' ||
$mytext[$el]->{'tag'} eq 'li' ||
$mytext[$el]->{'tag'} eq 'i' ||
$mytext[$el]->{'tag'} eq 'em' ||
$mytext[$el]->{'tag'} eq 'b' ||
$mytext[$el]->{'tag'} eq 'strong' ||
$mytext[$el]->{'tag'} eq 'del' ||
$mytext[$el]->{'tag'} eq 'sub' ||
$mytext[$el]->{'tag'} eq 'sup' ||
$mytext[$el]->{'tag'} eq 'mark' ||
$mytext[$el]->{'tag'} eq 'blockquote' ||
$mytext[$el]->{'tag'} eq 'dt' ||
$mytext[$el]->{'tag'} eq 'dd' ||
$mytext[$el]->{'tag'} eq 'code' ||
$mytext[$el]->{'tag'} eq 'pre' ||
$mytext[$el]->{'tag'} eq 'img' ||
$mytext[$el]->{'tag'} eq 'th' ||
$mytext[$el]->{'tag'} eq 'td') {
my $newid = _get_special_info(\@mytext, $el, '{#', '}');
if ($newid ne '' && !defined $mytext[$el]->{'id'}) {
# do not replace existing id=
$mytext[$el]->{'id'} = $newid;
}
}
# if _get_special_info() was used to extract an id {#id}, title
# {^title}, or fit {%fit}; it should have NOT left a blank child
# text string, though it may be empty
# if a tag has id=, assume it's a link target
# insert tags to write a red | bar at beginning of link text
# $el should point to tag itself
if (defined $mytext[$el]->{'id'} && defined $debug && $debug == 1) {
splice(@mytext, ++$el, 0, {'tag'=>'span', 'text'=>'',
'style'=>'color: #FF0000; font-weight: bold;'});
splice(@mytext, ++$el, 0, {'tag'=>'', 'text'=>'|'});
splice(@mytext, ++$el, 0, {'tag'=>'/span', 'text'=>''});
# still pointing at original tag
}
# 'next' to here
} # for loop through all tags
return @mytext;
} # end of _HTB_cleanup()
# given the text between <style> and </style>, and an existing $style
# hashref, update $style and return it
sub _process_style_tag {
my ($style, $text) = @_;
# expect sets of selector { property: value; ... }
# break up into selector => { property => value, ... }
# replace or add to existing $style
# note that a selector may be a tagName, a .className, or an #idName
$text =~ s/\n/ /sg; # replace end-of-lines with spaces
while ($text ne '') {
my $selector;
if ($text =~ s/^\s+//) { # remove leading whitespace
if ($text eq '') { last; }
}
if ($text =~ s/([^\s]+)//) { # extract selector
$selector = $1;
}
if ($text =~ s/^\s*{//) { # remove whitespace up through {
if ($text eq '') { last; }
}
# one or more property-name: value; sets (; might be missing on last)
# go into %prop_val. we don't expect to see any } within a property
# value string.
if ($text =~ s/([^}]+)//) {
$style->{$selector} = _process_style_string({}, $1);
}
if ($text =~ s/^}\s*//) { # remove closing } and whitespace
if ($text eq '') { last; }
}
# 'next' to here
} # end while loop
return $style;
} # end of _process_style_tag()
# decompose a style string into property-value pairs. used for both <style>
# tags and style= attributes.
sub _process_style_string {
my ($style, $text) = @_;
# split up at ;'s. don't expect to see any ; within value strings
my @sets = split /;/, $text;
# split up at :'s. don't expect to see any : within value strings
foreach (@sets) {
my ($property_name, $value) = split /:/, $_;
if (!defined $property_name || !defined $value) { last; }
# trim off leading and trailing whitespace from both
$property_name =~ s/^\s+//;
$property_name =~ s/\s+$//;
$value =~ s/^\s+//;
$value =~ s/\s+$//;
# trim off any single or double quotes around value string
if ($value =~ s/^['"]//) {
$value =~ s/['"]$//;
}
$style->{$property_name} = $value;
}
return $style;
} # end of _process_style_string()
# given a list of tags and content and attributes, return a list of hashes.
# new array element at start, at each tag, and each _content.
sub _walkTree {
my ($depth, @bodyList) = @_;
my ($tag, $element, $no_content);
my $bLSize = scalar(@bodyList);
# $depth not really used here, but might come in handy at some point
my @array = ();
for (my $elIdx=0; $elIdx<$bLSize; $elIdx++) {
$element = $bodyList[$elIdx];
# an element may be a simple text string, but most are hashes that
# contain a _tag and _content array and any tag attributes. _tag and
# any attributes go into an entry with text='', while any _content
# goes into one entry with text='string' and usually no attributes.
# if the _tag takes an end tag , it gets its own dummy entry.
if ($element =~ m/^HTML::Element=HASH/) {
# $element should be anonymous hash
$tag = $element->{'_tag'};
push @array, {'tag' => $tag, 'text' => ''};
# look for attributes for tag, also see if no child content
$no_content = 0; # has content (children) until proven otherwise
my @tag_attr = keys %$element;
# VOID elements (br, hr, img, area, base, col, embed, input,
# link, meta, source, track, wbr) should NOT have /> to mark
# as "self-closing", but it's harmless and much HTML code will
# have them marked as "self-closing" even though it really
# isn't! So be prepared to handle such dummy attributes, as
# per RT 143038.
if ($tag eq 'br' || $tag eq 'hr' ||
$tag eq 'img' || $tag eq 'area' || $tag eq 'base' ||
$tag eq 'col' || $tag eq 'embed' || $tag eq 'input' ||
$tag eq 'link' || $tag eq 'meta' || $tag eq 'source' ||
$tag eq 'track' || $tag eq 'wbr' ||
$tag eq 'defaults' || $tag eq 'style') {
# self-closing or VOID with unnecessary /, there is no
# child data/elements for this tag. and, we can ignore
# this 'attribute' of /.
# defaults and style are specially treated as a VOID tags
$no_content = 1;
}
foreach my $key (@tag_attr) {
# has an (unnecessary) self-closing / ?
if ($element->{$key} eq '/') { next; }
# 'key' is more of an attribute within a tag (element)
if ($key =~ m/^_/) { next; } # built-in attribute
# this tag has one or more attributes to add to it
# add tag attribute (e.g., src= for <img>) to hash
$array[-1]->{$key} = $element->{$key};
}
if (!$no_content && defined $element->{'_content'}) {
my @content = @{ $element->{'_content'} };
# content array elements are either text segments or
# tag subelements
foreach (@content) {
if ($_ =~ m/^HTML::Element=HASH/) {
# HASH child of this _content
# recursively handle a tag within _content
@array = (@array, _walkTree($depth+1, $_));
} else {
# _content text, shouldn't be any attributes
push @array, {'tag' => '', 'text' => $_};
}
}
} else {
# no content for this tag
}
# at end of a tag ... if has content, output end tag
if (!$no_content) {
push @array, {'tag' => "/$tag", 'text' => ''};
}
$no_content = 0;
} else {
# SCALAR (string) element
push @array, {'tag' => '', 'text' => $element};
}
# 'next' to here
} # loop through _content at this level ($elIdx)
return @array;
} # end of _walkTree()
# convert a size (length) or font size into points
# TBD another parm to indicate how to treat 'no unit' case?
# currently assume points (CSS considers only bare 0 to be valid)
# length = string (or pure number) of length in CSS units
# if number, is returned as points
# font_size = current font size (points) for use with em, en, ex, % units
# option parent_size = parent dimension (points) to use for % instead of font size
# option usage = label for what is being converted to points
sub _size2pt {
my ($length, $font_size, %opts) = @_;
# length is requested size (or font size), possibly with a unit
# if undefined, use '0'
$length = '0' if !defined $length;
$length = ''.$length; # ensure is a string (may be unitless number of points)
# font_size is current_prop font-size (pts),
# in case relative to font size (such as %). must be number > 0
my $parent_size = $font_size;
if (defined $opts{'parent_size'}) {
# must be a number (points). this way, font size still available
# for em, en, ex, but parent container size used for other things
$parent_size = $opts{'parent_size'};
}
my $usage = 'unknown';
$usage = $opts{'usage'} if defined $opts{'usage'};
my $number = 0;
my $unit = '';
# split into number and unit
if ($length =~ m/^(-?\d+\.?\d*)(.*)$/) {
$number = $1; # [-] nnn.nn, nnn., or nnn format
$unit = $2; # may be empty
} elsif ($length =~ m/^(-?\.\d+)(.*)$/) {
$number = $1; # [-] .nnn format
$unit = $2; # may be empty
} else {
carp "Unable to find number in '$length', _size2pt returning 0";
return 0;
}
# font_size should be in points (bare number)
if ($unit eq '') {
# if is already a pure number, just return it
# except for 0, that's not legal CSS, is an extension
return $number;
} elsif ($unit eq 'pt') {
# if the unit is 'pt', strip off the unit and return the number
return $number;
} elsif ($unit eq '%') {
# if the unit is '%', strip off, /100, multiply by current parent/font size
return $number/100 * $parent_size;
} elsif ($unit eq 'em') {
# 1 em = 100% font size
return $font_size;
} elsif ($unit eq 'en' || $unit eq 'ex') {
# 1 en = 1 ex = 50% font size
# TBD get true ex size from font information
return $font_size/2;
} elsif ($unit eq 'in') {
# 1 inch = 72pt
return 72*$number;
} elsif ($unit eq 'cm') {
# 1 cm = 28.35pt
return 28.35*$number;
} elsif ($unit eq 'mm') {
# 1 cm = 2.835pt
return 2.835*$number;
} elsif ($unit eq 'px') {
# assume 78px to the inch TBD actual value available anywhere?
return 72/78*$number;
} else {
carp "Unknown unit '$unit' in '$length', _size2pt() assumes 'pt'";
return $number;
}
return 0; # should not get to here
} # end of _size2pt()
# create ordered or unordered list item marker
# for ordered, returns $prefix.formatted_value.$suffix.blank
# for unordered, returns string .disc, .circle, .square, or .box
# (.box is nonstandard marker)
#
# TBD for ol, there are many other formats: cjk-decimal, decimal-leading-zero,
# lower-greek, upper-greek?, lower-latin = lower-alpha, upper-latin =
# upper-alpha, arabic-indic, -moz-arabic-indic, armenian, [-moz-]bengali,
# cambodian (khmer), [-moz-]cjk-earthly-branch, [-moz-]cjk-heavenly-stem,
# cjk-ideographic, [-moz-]devanagari, ethiopi-numeric, georgian,
# [-moz-]gujarati, [-moz-]gurmukhi, hebrew, hiragana, hiragana-iroha,
# japanese-formal, japanese-informal, [-moz-]kannada, katakana,
# katakana-iroha, korean-hangul-formal, korean-hanja-formal,
# korean-hanja-informal, [-moz-]lao, lower-armenian, upper-armenian,
# [-moz-]malayalam, mongolian, [-moz-]myanmar, [-moz-]oriya,
# [-moz-]persian, simp-chinese-formal, simp-chinese-informal, [-moz-]tamil,
# [-moz-]telugu, [-moz-]thai, tibetan, trad-chinese-formal,
# trad-chinese-informal, disclosure-open, disclosure-closed
# TBD for ol, some browser-specific formats: -moz-ethiopic-halehame,
# -moz-ethiopic-halehame-am, [-moz-]ethiopic-halehame-ti-et, [-moz-]hangul,
# [-moz-]hangul-consonant, [-moz-]urdu
# TBD for ul, ability to select images and possibly other characters
sub _marker {
my ($type, $depth_u, $depth_o, $depth_s, $value, $prefix, $suffix) = @_;
# type = list-style-type,
# depth_u = 1, 2,... ul nesting level,
# depth_o = 1, 2,... ol nesting level,
# depth_s = 1, 2,... _sl nesting level,
# (following for ordered list only):
# value = counter (start)
# prefix = text before formatted value
# default ''
# suffix = text after formatted value
# default '.'
if (!defined $suffix) { $suffix = '.'; }
if (!defined $prefix) { $prefix = ''; }
my $output = '';
# CAUTION: <ol type= and <li type = will be aAiI1, not CSS property values!
if ($type eq 'a') {
$type = 'lower-alpha';
} elsif ($type eq 'A') {
$type = 'upper-alpha';
} elsif ($type eq 'i') {
$type = 'lower-roman';
} elsif ($type eq 'I') {
$type = 'upper-roman';
} elsif ($type eq '1') {
$type = 'decimal';
}
# ordered lists
if ($type eq 'decimal' || $type eq 'arabic') {
$output = "$prefix$value$suffix";
} elsif ($type eq 'upper-roman' || $type eq 'lower-roman') {
# TBD support overbar (1000x) for Roman numerals. what is exact format?
while ($value >= 1000) { $output .= 'M'; $value -= 1000; }
if ($value >= 900) { $output .= 'CM'; $value -= 900; }
if ($value >= 500) { $output .= 'D'; $value -= 500; }
if ($value >= 400) { $output .= 'CD'; $value -= 500; }
while ($value >= 100) { $output .= 'C'; $value -= 100; }
if ($value >= 90) { $output .= 'XC'; $value -= 90; }
if ($value >= 50) { $output .= 'L'; $value -= 50; }
if ($value >= 40) { $output .= 'XL'; $value -= 40; }
while ($value >= 10) { $output .= 'X'; $value -= 10; }
if ($value == 9) { $output .= 'IX'; $value -= 9; }
if ($value >= 5) { $output .= 'V'; $value -= 5; }
if ($value == 4) { $output .= 'IV'; $value -= 4; }
while ($value >= 1) { $output .= 'I'; $value -= 1; }
if ($type eq 'lower-roman') { $output = lc($output); }
$output = "$prefix$output$suffix";
} elsif ($type eq 'upper-alpha' || $type eq 'lower-alpha') {
my $n;
while ($value) {
$n = ($value - 1)%26; # least significant letter digit 0..25
$output = chr(ord('A') + $n) . $output;
$value -= ($n+1);
$value /= 26;
}
if ($type eq 'lower-alpha') { $output = lc($output); }
$output = "$prefix$output$suffix";
# there are many more ordered list formats that could be supported here
# unordered lists
} elsif ($type eq 'disc') {
$output = '.disc';
} elsif ($type eq 'circle') {
$output = '.circle';
} elsif ($type eq 'square') {
$output = '.square';
} elsif ($type eq 'box') { # non-standard
$output = '.box';
} elsif ($type eq '.u') { # default for unordered list at this depth
# unlikely to exceed depth of 4, but be ready for it...
# TBD what is official policy on depth exceeding 3? is it all .square
# or is it supposed to rotate?
my $depth = $depth_u+$depth_o+$depth_s;
if ($depth%4 == 1) {
$output = '.disc';
} elsif ($depth%4 == 2) {
$output = '.circle';
} elsif ($depth%4 == 3) {
$output = '.square';
} elsif ($depth%4 == 0) {
$output = '.box';
}
} elsif ($type eq '.o') { # default for ordered list at this depth
$output = "$prefix$value$suffix"; # decimal
# potentially many other unordered list marker systems, but need to find
# out if there's anything official
} elsif ($type eq 'none') {
$output = '.none';
} else {
# unknown. use disc
$output = '.disc';
}
return $output;
} # end of _marker()
# stuff to remember if need to shift line down due to extent increase
# @line_extents array:
# $start_x # fixed start of current baseline
# $x # current baseline offset to write at
# note that $x changes with each write
# $y
# $width
# $endx
# $next_y # where next line will start (may move down)
# $asc # current vertical extents
# $desc
# $desc_leading
# $text # text context (won't change)
# length($text->{' stream'}) # where the current line starts in the stream
# # (won't change)
# $grfx # graphis content, might be undef (won't change)
# length($grfx->{' stream'}) # where the current line starts in the stream
# # (won't change)
# $start_y # very top of this line (won't change)
# $min_y # lowest allowable inked value (won't change)
# $outline # array ref to outline (won't change)
# $left_margin to shorten line (won't change)
# $left_margin_nest to shorten line on nested list (won't change)
# $right_margin to shorten line (won't change)
# we do the asc/desc externally, as how to get them depends on whether it's
# a font change, an image or equation, or some other kind of inline object
# $asc = new ascender (does it exceed the old one?)
# $desc = new descender (does it exceed the old one?)
# $desc_leading = new descender with leading (does it exceed the old one?)
# $text_w = width of text ($phrase) to be written
# returns $rc = 0: all OK, line fits with no change to available space
# 1: OK, but available space reduced, so need to recheck
# 2: problem -- existing line (already written) won't fit in
# shorter line, much less space for new text
# 3: problem -- line now runs off bottom of column
# @line_extents, with some entries revised
sub _revise_baseline {
my ($o_start_x, $o_x, $o_y, $o_width, $o_endx, $o_next_y, $o_asc, $o_desc,
$o_desc_leading, $text, $line_start_offset,
$grfx, $line_start_offsetg, $start_y, $min_y,
$outline, $margin_left,
$margin_right, $asc, $desc, $desc_leading, $text_w) = @_;
my $rc = 0; # everything OK so far
# items which may change (remembering initial/old values)
my $start_x = $o_start_x; # line's original starting x
my $x = $o_x; # current x position
my $y = $o_y;
my $width = $o_width;
my $endx = $o_endx;
my $next_y = $o_next_y;
# may change, but supplied separately
# $asc = $o_asc;
# $desc = $o_desc;
# $desc_leading = $o_desc_leading;
my $need_revise = 0;
# determine whether we need to revise baseline due to extent increases
if ($asc > $o_asc) {
$need_revise = 1;
} else {
$asc = $o_asc;
}
if ($desc < $o_desc) { # desc and desc_leading are negative values
$need_revise = 1;
} else {
$desc = $o_desc;
}
if ($desc_leading < $o_desc_leading) {
$need_revise = 1;
} else {
$desc_leading = $o_desc_leading;
}
if ($need_revise) {
# in middle of line, add_x and add_y are 0
# start_y is unchanged, but asc, desc may have increased
$next_y = $start_y - $asc + $desc_leading;
# did we go too low? will return -1 (start_x) and
# remainder of input
# don't include leading when seeing if line dips too low
if ($start_y - $asc + $desc < $min_y) {
$rc = 3; # ran out of column (vertically) = we overflow column
# off bottom if we go ahead and write any of new text
# TBD instead just end line here (early),
# go to next column for taller text we want to print
# however, could then end up with a very short line!
} else {
# start_y and next_y are vertical extent of this line (revised)
# y is the y value of the baseline (so far). lower it a bit.
$y -= $asc - $o_asc;
# start_x is baseline start (so far), x is current write position
# how tall is the line? need to set baseline.
($start_x,$y, $width) = _get_baseline($y, @$outline);
# $x should be unchanged at this point (might be beyond new end)
$width -= $margin_left + $margin_right; # available on new line
$endx = $start_x + $width;
# we don't know the nature of the new material attempting to add,
# so can't resolve insufficient space issues here
# $x should already account for margin_left
if ($x > $endx) {
# if current (already written) line can't fit (due to much
# shorter line), rc = 2
$rc = 2;
} elsif ($x + $text_w > $endx) {
# if adding new text will overflow line, rc = 1
$rc = 1;
} else { # should have room to write new text
$rc = 0;
# revise (move in x,y) any existing text in this line (Tm cmd),
# INCLUDING this text chunk's Tm if still in Tpending buffer.
$text->_Tpending();
my $i = $line_start_offset;
my $delta_x = $start_x - $o_start_x;
my $delta_y = $y - $o_y;
while(1) {
$i = index($text->{' stream'}, ' Tm', $i+3);
if ($i == -1) { last; }
# $i is the position of a Tm command in the stream. the two
# words before it are x and y position to write at.
# $j is $i back up by two spaces
my $j = rindex($text->{' stream'}, ' ', $i-1);
$j = rindex($text->{' stream'}, ' ', $j-1) + 1;
# $j points to first char of x, $i to one after last y char
my $str1 = substr($text->{' stream'}, 0, $j);
my $str2 = substr($text->{' stream'}, $i);
my $old_string = substr($text->{' stream'}, $j, $i-$j);
$old_string =~ m/^([^ ]+) ([^ ]+)$/;
my $old_x = $1;
my $old_y = $2;
$old_x += $delta_x;
$old_y += $delta_y;
$text->{' stream'} = $str1."$old_x $old_y".$str2;
# no need to change line_start_offset, but $i has to be
# adjusted to account for possible change in resulting
# position of Tm
$i += length("$old_x $old_y") - ($i - $j);
} # end while(1) loop adjusting Tm's on this line
# AFTER the Tm statement may come one or more strokes for
# underline, strike-through, and/or overline
$i = $line_start_offset;
# $delta_x, $delta_y same as before
while (1) {
$i = index($text->{' stream'}, ' l S', $i+4);
if ($i == -1) { last; }
# $i is the position of a lS command in the stream. the five
# words before it are x and y positions to write at.
# (x y m x' y l S is full command to modify)
# $j is $i back up by five spaces
my $j = rindex($text->{' stream'}, ' ', $i-1);
$j = rindex($text->{' stream'}, ' ', $j-1);
$j = rindex($text->{' stream'}, ' ', $j-1);
$j = rindex($text->{' stream'}, ' ', $j-1);
$j = rindex($text->{' stream'}, ' ', $j-1);
# $j points to first char of x, $i to one after last y char
my $str1 = substr($text->{' stream'}, 0, $j);
my $str2 = substr($text->{' stream'}, $i);
my $old_string = substr($text->{' stream'}, $j, $i-$j);
$old_string =~ m/^ ([^ ]+) ([^ ]+) m ([^ ]+) ([^ ]+)$/;
my $old_x1 = $1;
my $old_y1 = $2;
my $old_x2 = $3;
my $old_y2 = $4;
$old_x1 += $delta_x;
$old_y1 += $delta_y;
$old_x2 += $delta_x;
$old_y2 += $delta_y;
$text->{' stream'} = $str1." $old_x1 $old_y1 m $old_x2 $old_y2".$str2;
# no need to change line_start_offset, but $i has to be
# adjusted to account for possible change in resulting
# position of lS
$i += length(" $old_x1 $old_y1 m $old_x2 $old_y2") - ($i - $j);
} # end while(1) loop adjusting line stroke positions
}
}
}
return ($rc, $start_x, $x, $y, $width, $endx, $next_y,
$asc, $desc, $desc_leading,
$text, $line_start_offset, $grfx, $line_start_offsetg,
$start_y, $min_y, $outline,
$margin_left, $margin_right);
} # end of _revise_baseline()
# just something to pause during debugging
sub _pause {
print STDERR "====> Press Enter key to continue...";
my $input = <>;
return;
}
=head4 init_state()
See L<PDF::Builder> for code and L<PDF::Builder::Content::Column_docs>
for documentation.
=cut
=head4 pass_start_state()
See L<PDF::Builder> for code and L<PDF::Builder::Content::Column_docs>
for documentation.
=head4 pass_end_state()
See L<PDF::Builder::Content::Column_docs> for documentation.
=cut
sub pass_end_state {
my ($self, $pass_count, $max_passes, $pdf, $state, %opts) = @_;
# $state = ref to %state structure
my $rc = scalar(keys %{$state->{'changed_target'}});
# length of changed_target key list
# are we either clear to finish, or at max number of passes? if so,
# output all annotations. each page should have its complete text already,
# as well as a record of the annotations in %state
if (!$rc || $pass_count == $max_passes) {
# where to put UL corner of target window relative to target text
my $delta_x = 20; # 20pt to LEFT
my $delta_y = 20;
if (defined $opts{'deltas'} && ref($opts{'deltas'}) eq 'ARRAY') {
my @deltas = @{ $opts{'deltas'} };
if (@deltas == 2) {
$delta_x = $deltas[0];
$delta_y = $deltas[1];
}
}
my @media_size = $pdf->mediabox(); # [0] min x, [3] max y
# go through list of annotations to create at '_ref' tag links
my $cur_src_page = 0; # minimize openings of source page. min valid 1
my $cur_tgt_page = 0; # minimize openings of target page. min valid 1
my ($src_page, $tgt_page); # opened page objects
my $link_border;
if (defined $opts{'debug'} && $opts{'debug'} == 1) {
# debug: draw border around link text
$link_border = [ 0, 0, 1 ];
} else {
# production: no border around link text
$link_border = [ 0, 0, 0 ];
}
for (my $source=0; $source<@{$state->{'xrefs'}}; $source++) {
my $sptr = $state->{'xrefs'}->[$source];
# source filename of target link (final name and position!)
my $tfn = $sptr->{'tfn'};
# target's physical page number
my $tppn = $sptr->{'tppn'};
# source's physical page number
my $sppn = $sptr->{'sppn'};
# target's formatted page number is not of interest here (link
# text already output, if includes fpn)
#my $tfpn = $sptr->{'tfpn'};
# target's tag that produced the entry is not of interest here
#my $ttag = $sptr->{'tag'};
# title is not of interest here (link text already output)
#my $title = $sptr->{'title'};
# other_pg is not of interest here (link text already output)
#my $other_pg = $sptr->{'other_pg'};
# target's x and y coordinates (for fit entry)
my $tx = $sptr->{'tx'};
my $ty = $sptr->{'ty'};
# target id/ND/etc. information and fit
my $tid = $sptr->{'id'};
my $fit = $sptr->{'fit'};
# if fit includes two % fields, replace by tx and ty
# (for xyz fit: 'xyz,%x,%y,null')
my $val = max(int($tx-$delta_x),$media_size[0]);
$fit =~ s/%x/$val/;
$val = min(int($ty+$delta_y),$media_size[3]);
$fit =~ s/%y/$val/;
# replace any 'undef' by 'null' in $fit
$fit =~ s/undef/null/g;
# list of pairs of source physical page number and annot rectangle
# coordinates, to place link at. usually one per link, but
# sometimes 2 or more due to wrapping
my @links = @{ $sptr->{'click'} };
for (my $click=0;
$click<@links; # most often, 1
$click++) {
# usually only one click area to place an annotation in, but
# could spread over two or more lines, and even into the
# next column (or page). annotation click area to be placed
# in page object $src_page at coordinates $rect
my @next_click_area = @{ $links[$click] };
my $sppn = $next_click_area[0];
if ($sppn != $cur_src_page) {
$src_page = $pdf->openpage($sppn);
$cur_src_page = $sppn;
}
# click area corners [ULx,y, LRx,y]
my $rect = $next_click_area[1]; # leave as pointer
my $annot = $src_page->annotation();
# three flavors of 'tid':
if ($tid =~ /^#[^#]/) {
# physical page number target, may be internal or external
# reuse $tppn since explicitly giving
$tppn = substr($tid, 1);
# have target file (if ext) and physical page number
$fit = 'fit' if $fit eq ''; # default show whole page
if ($tfn eq '') {
# internal link to page object at $tx,$ty fit
if ($tppn != $cur_tgt_page) {
$tgt_page = $pdf->openpage($tppn);
$cur_tgt_page = $tppn;
}
$annot->goto($tgt_page,
(split /,/, $fit),
'rect'=>$rect, 'border'=>$link_border);
} else {
# external link to physical page
$annot->pdf($tfn, $tppn,
(split /,/, $fit),
'rect'=>$rect, 'border'=>$link_border);
}
} elsif ($tid =~ /^##/) {
# Named Destination given (ignore 'fit' if given)
# external if filepath not ''
my $nd = substr($tid, 1);
if ($tfn eq '') {
# internal link to named destination
$annot->goto($nd,
'rect'=>$rect, 'border'=>$link_border);
} else {
# external link to named destination
$annot->pdf($tfn, $nd,
'rect'=>$rect, 'border'=>$link_border);
}
} else {
# id defined elsewhere, at $tgt_page from target
if ($fit eq '') {
# default fit is xyz x-$delta_x,y+$delta_y,undef
# x,y from location of target on page
$fit = "xyz,".max(int($tx)-$delta_x,$media_size[0]).",".
min(int($ty)+$delta_y,$media_size[3]).",null";
}
# internal link to page object at $tx,$ty fit
# skip if Named Destination instead of a phys page no
if ($tppn =~ m/^\d+$/ && $tppn != $cur_tgt_page) {
$tgt_page = $pdf->openpage($tppn);
$cur_tgt_page = $tppn;
}
$annot->goto($tgt_page,
(split /,/, $fit),
'rect'=>$rect, 'border'=>$link_border);
}
} # have gone through one or more click areas to create for this
# one link
} # done looping through all the requested annotations in xrefs
# output any named destinations defined
my $ptr = $state->{'nameddest'};
foreach my $name (keys %$ptr) {
my $fit = $ptr->{$name}{'fit'};
my $ppn = $ptr->{$name}{'ppn'};
my $x = $ptr->{$name}{'x'};
my $y = $ptr->{$name}{'y'};
# if no fit given, set to xyz,x-$delta_x,y+$delta_y,undef
if ($fit eq '') {
$fit = "xyz,".max(int($x)-$delta_x,$media_size[0]).",".
min(int($y)+$delta_y,$media_size[3]).",null";
}
# if $x and $y in fit, replace with integer values
my $val = max(int($x)-$delta_x,$media_size[0]);
$fit =~ s/\$x/$val/;
$val = min(int($y)+$delta_y,$media_size[3]);
$fit =~ s/\$y/$val/;
my @fits = ();
@fits = split /,/, $fit;
for (my $i=0; $i<@fits; $i++) {
# if the user specified a fit with 'undef' (string) parms
if ($fits[$i] eq 'undef') { $fits[$i] = 'null'; }
}
my $dest = PDF::Builder::NamedDestination->new($pdf);
my $page = $pdf->openpage($ppn);
$dest->goto($page, @fits);
$pdf->named_destination('Dests', $name, $dest);
}
} # end of outputting annotations and named destinations
return $rc;
}
# list target ids in state holder that are still changing
=head4 unstable_state()
See L<PDF::Builder::Content::Column_docs> for documentation
=cut
sub unstable_state {
my ($self, $state) = @_;
# $state = ref to %state structure
my @list = sort(keys %{$state->{'changed_target'}});
# would prefer target ids to be returned in order encountered, but
# since no idea what order hash keys will be in, might as well sort
# in alphabetical order
return @list; # hopefully empty at some point
}
# mytext array at element $el, extract full child text of this element
# may be sub tags and their own child text, all to be returned
#
# actually, all tags have already been removed and the overall text will
# now be a series of text and tags and their children (arbitrarily deep)
# e.g. <h2 id=target>This is <i>italic</i> text</h2> would be
# tag=>'h2'
# id=>'target'
# tag=>''
# text=>'This is '
# tag=>'i'
# tag=>''
# text=>'italic'
# tag=>'/i'
# tag=>''
# text=>' text'
# tag=>'/h2'
# desired output: 'This is italic text'
#
# the big problem is to know what element to stop at (the end tag to
# $el element, not necessarily the next /tag, in case there's another 'tag'
# embedded within the child text)
# TBD: consider also copying tags (markup) within child text, to appear
# formatted in title (per _ref, and global, flag to flatten)
sub _get_child_text {
my ($mytext, $el) = @_;
my $output = '';
my @tags = ($mytext->[$el]->{'tag'});
for (my $elx=$el+1; ; $elx++) {
# found end of this tag we seek child text from?
if ($mytext->[$elx]->{'tag'} eq "/$tags[0]" &&
scalar(@tags)==1) { last; }
# found some text in it? add to output
if ($mytext->[$elx]->{'tag'} eq '') {
$output .= $mytext->[$elx]->{'text'};
next;
}
# an end tag? pop stack (assume properly nested!)
if ($mytext->[$elx]->{'tag'} =~ /^\//) {
pop @tags;
next;
}
# must be another tag. push it on tag stack
push @tags, $mytext->[$elx]->{'tag'};
}
# also convert line ends to blanks
$output =~ s/\s+/ /sg;
return $output;
} # end _get_child_text()
# similar to _get_child_text(), but goes through looking for special section
# AND trims out removed text from where it was found
#
# open text in a paragraph shouldn't have any special text, but
# we need to look at tag attributes (title= ), heading text, link
# child text, etc.
sub _get_special_info {
my ($mytext, $el, $pattern, $endchar) = @_;
my $newtext = '';
my ($start, $end);
my @tags = ($mytext->[$el]->{'tag'});
for (my $elx=$el+1; $elx<@$mytext; $elx++) {
# found end of this tag we seek child text from?
if (@tags == 1 && $mytext->[$elx]->{'tag'} eq "/$tags[0]") { last; }
# found some desired text in it? extract to output
if ($mytext->[$elx]->{'tag'} eq '') {
# assume no tags within text
my $text = $mytext->[$elx]->{'text'};
$start = index($text, $pattern);
if ($start > -1) {
# starting pattern found within text string
$end = index($text, $endchar, $start+length($pattern));
if ($end > -1) {
# ending pattern found within text string, after starting
$newtext = substr($text, $start+length($pattern),
$end-$start-length($pattern));
# now remove entire thing plus up to one space
$end += length($endchar)-1;
my $space_before = 0;
if ($start>0 && substr($text, $start-1, 1) eq ' ') {
$space_before = 1;
}
my $space_after = 0;
if ($end < length($text)-1 &&
substr($text, $end+1, 1) eq ' ') {
$space_after = 1;
}
if ($start == 0) {
# at far left
if ($space_after) { $end++; }
$text = substr($text, $end+1);
} elsif ($end == length($text)-1) {
# at far right
if ($space_before) { $start--; }
$text = substr($text, 0, $start);
} elsif ($space_before && $space_after) {
# in middle with one space to delete at either end
$text = substr($text, 0, --$start) .
substr($text, $end+1);
} else {
# in middle with no space after or no space after,
# so preserve adjoining space
$text = substr($text, 0, $start) .
substr($text, $end+1);
}
}
}
$mytext->[$elx]->{'text'} = $text; # may be now empty
next; # should be only occurence, but still need to clean up
}
# an end tag? pop stack (assume properly nested!)
if ($mytext->[$elx]->{'tag'} =~ /^\//) {
pop @tags;
next;
}
# must be another tag. push it on tag stack
push @tags, $mytext->[$elx]->{'tag'};
}
# trim enclosure and leading and trailing whitespace off it
$newtext =~ s/^$pattern\s+//;
$newtext =~ s/\s+$endchar$//;
return $newtext;
} # end _get_special_info()
# --------------------- end of column() section -----------------------------
1;
|