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
|
(* cpdf command line tools *)
let demo = false
let agpl = true
let major_version = 2
let minor_version = 8
let minor_minor_version = 1
let version_date = "(28th March 2025)"
open Pdfutil
open Pdfio
let combine_with_spaces strs =
String.trim
(fold_left (fun x y -> x ^ (if x <> "" then " " else "") ^ y) "" strs)
let tempfiles = ref []
let exit n =
begin try iter Sys.remove !tempfiles with _ -> exit n end;
exit n
let null () = ()
let initial_file_size = ref 0
let empty = Pdf.empty ()
(* Wrap up the file reading functions to exit with code 1 when an encryption
problem occurs. This happens when object streams are in an encrypted document
and so it can't be read without the right password... The existing error
handling only dealt with the case where the document couldn't be decrypted once
it had been loaded. *)
let pdfread_pdf_of_input ?revision a b c =
try Pdfread.pdf_of_input ?revision a b c with
Pdf.PDFError s when String.length s >=10 && String.sub s 0 10 = "Encryption" ->
raise (Cpdferror.SoftError "Bad owner or user password when reading document")
let pdfread_pdf_of_channel_lazy ?revision ?source b c d =
try Pdfread.pdf_of_channel_lazy ?revision ?source b c d with
Pdf.PDFError s when String.length s >=10 && String.sub s 0 10 = "Encryption" ->
raise (Cpdferror.SoftError "Bad owner or user password when reading document")
let pdfread_pdf_of_file ?revision a b c =
try Pdfread.pdf_of_file ?revision a b c with
Pdf.PDFError s when String.length s >=10 && String.sub s 0 10 = "Encryption" ->
raise (Cpdferror.SoftError "Bad owner or user password when reading document")
let optstring = function
| "" -> None
| x -> Some x
let _ =
set_binary_mode_in stdin true;
set_binary_mode_out stdout true
let stay_on_error = ref false
exception StayOnError
(* Fatal error reporting. *)
let error s =
Pdfe.log (s ^ "\nUse -help for help.\n");
if not !stay_on_error then exit 2 else raise StayOnError
let soft_error s =
Pdfe.log (Printf.sprintf "%s\n" s);
if not !stay_on_error then exit 1 else raise StayOnError
let parse_pagespec pdf spec =
try Cpdfpagespec.parse_pagespec pdf spec with
Failure x -> error x
(* We allow an operation such as ScaleToFit on a range such as 'portrait' to be silently null to allow, for example:
cpdf -scale-to-fit a4portrait in.pdf portrait AND -scale-to-fit a4landscape landscape -o out.pdf
*)
let parse_pagespec_allow_empty pdf spec =
try Cpdfpagespec.parse_pagespec pdf spec with
Pdf.PDFError ("Page range specifies no pages") -> []
(* Operations. *)
type op =
| CopyFont of string
| CountPages
| Version
| Encrypt
| Decrypt
| StampOn of string
| StampUnder of string
| CombinePages of string
| TwoUp
| TwoUpStack
| Impose of bool
| RemoveBookmarks
| AddBookmarks of string
| AddText of string
| AddRectangle
| RemoveText
| Draft
| PadBefore
| PadAfter
| PadEvery of int
| PadMultiple of int
| PadMultipleBefore of int
| Shift
| ShiftBoxes
| Scale
| ScaleToFit
| Stretch
| CenterToFit
| ScaleContents of float
| AttachFile of string list
| RemoveAttachedFiles
| ListAttachedFiles
| DumpAttachedFiles
| RemoveAnnotations
| ListAnnotations
| CopyAnnotations of string
| SetAnnotations of string
| Merge
| Split
| SplitOnBookmarks of int
| SplitMax of int
| Spray
| Clean
| Info
| PageInfo
| Metadata
| SetMetadata of string
| RemoveMetadata
| Fonts
| RemoveFonts
| Compress
| Decompress
| Crop
| Trim
| Bleed
| Art
| RemoveCrop
| RemoveArt
| RemoveTrim
| RemoveBleed
| CopyBox
| MediaBox
| HardBox of string
| Rotate of int
| Rotateby of int
| RotateContents of float
| Upright
| VFlip
| HFlip
| ThinLines of float
| SetAuthor of string
| SetTitle of string
| SetSubject of string
| SetKeywords of string
| SetCreate of string
| SetModify of string
| SetCreator of string
| SetProducer of string
| SetTrapped
| SetUntrapped
| SetVersion of int
| ListBookmarks
| SetPageLayout of string
| SetPageMode of string
| SetNonFullScreenPageMode of string
| HideToolbar of bool
| HideMenubar of bool
| HideWindowUI of bool
| FitWindow of bool
| CenterWindow of bool
| DisplayDocTitle of bool
| Presentation
| ChangeId
| RemoveId
| CopyId of string
| BlackText
| BlackLines
| BlackFills
| ExtractImages
| ListImages
| ImageResolution of float
| MissingFonts
| ExtractFontFile of string
| ExtractText
| OpenAtPage of string
| OpenAtPageFit of string
| OpenAtPageCustom of string
| AddPageLabels
| RemovePageLabels
| PrintPageLabels
| RemoveDictEntry of string
| ReplaceDictEntry of string
| PrintDictEntry of string
| ListSpotColours
| RemoveClipping
| SetMetadataDate of string
| CreateMetadata
| EmbedMissingFonts
| BookmarksOpenToLevel of int
| CreatePDF
| RemoveAllText
| ShowBoxes
| TrimMarks
| Prepend of string
| Postpend of string
| OutputJSON
| OCGCoalesce
| OCGList
| OCGRename
| OCGOrderAll
| StampAsXObject of string
| PrintFontEncoding of string
| TableOfContents
| Typeset of string
| TextWidth of string
| Draw
| Composition of bool
| Chop of int * int
| ChopHV of bool * float
| ProcessImages
| ExtractStream of string
| ReplaceStream of string
| PrintObj of string
| ReplaceObj of string * string
| RemoveObj of string
| Verify of string
| MarkAs of Cpdfua.subformat
| RemoveMark of Cpdfua.subformat
| PrintStructTree
| ExtractStructTree
| ReplaceStructTree of string
| RemoveStructTree
| MarkAsArtifact
| SetLanguage of string
| Redact
| Rasterize
| OutputImage
let string_of_op = function
| PrintFontEncoding _ -> "PrintFontEncoding"
| PrintDictEntry _ -> "PrintDictEntry"
| Impose _ -> "Impose"
| CopyFont _ -> "CopyFont"
| CountPages -> "CountPages"
| Version -> "Version"
| Encrypt -> "Encrypt"
| Decrypt -> "Decrypt"
| StampOn _ -> "StampOn"
| StampUnder _ -> "StampUnder"
| CombinePages _ -> "CombinePages"
| TwoUp -> "TwoUp"
| TwoUpStack -> "TwoUpStack"
| RemoveBookmarks -> "RemoveBookmarks"
| AddBookmarks _ -> "AddBookmarks"
| AddText _ -> "AddText"
| AddRectangle -> "AddRectangle"
| RemoveText -> "RemoveText"
| Draft -> "Draft"
| PadBefore -> "PadBefore"
| PadAfter -> "PadAfter"
| PadEvery _ -> "PadEvery"
| PadMultiple _ -> "PadMultiple"
| PadMultipleBefore _ -> "PadMultipleBefore"
| Shift -> "Shift"
| ShiftBoxes -> "ShiftBoxes"
| Scale -> "Scale"
| ScaleToFit -> "ScaleToFit"
| Stretch -> "Stretch"
| CenterToFit -> "CenterToFit"
| ScaleContents _ -> "ScaleContents"
| AttachFile _ -> "AttachFile"
| RemoveAttachedFiles -> "RemoveAttachedFiles"
| ListAttachedFiles -> "ListAttachedFiles"
| DumpAttachedFiles -> "DumpAttachedFiles"
| RemoveAnnotations -> "RemoveAnnotations"
| ListAnnotations -> "ListAnnotations"
| CopyAnnotations _ -> "CopyAnnotations"
| SetAnnotations _ -> "SetAnnotations"
| Merge -> "Merge"
| Split -> "Split"
| SplitOnBookmarks _ -> "SplitOnBookmarks"
| SplitMax _ -> "SplitMax"
| Spray -> "Spray"
| Clean -> "Clean"
| Info -> "Info"
| PageInfo -> "PageInfo"
| Metadata -> "Metadata"
| SetMetadata _ -> "SetMetadata"
| RemoveMetadata -> "RemoveMetadata"
| Fonts -> "Fonts"
| RemoveFonts -> "RemoveFonts"
| Compress -> "Compress"
| Decompress -> "Decompress"
| Crop -> "Crop"
| RemoveCrop -> "RemoveCrop"
| CopyBox -> "CopyBox"
| MediaBox -> "MediaBox"
| HardBox _ -> "HardBox"
| Rotate _ -> "Rotate"
| Rotateby _ -> "Rotateby"
| RotateContents _ -> "RotateContents"
| Upright -> "Upright"
| VFlip -> "VFlip"
| HFlip -> "HFlip"
| ThinLines _ -> "ThinLines"
| SetAuthor _ -> "SetAuthor"
| SetTitle _ -> "SetTitle"
| SetSubject _ -> "SetSubject"
| SetKeywords _ -> "SetKeywords"
| SetCreate _ -> "SetCreate"
| SetModify _ -> "SetModify"
| SetCreator _ -> "SetCreator"
| SetProducer _ -> "SetProducer"
| SetTrapped -> "SetTrapped"
| SetUntrapped -> "SetUntrapped"
| SetVersion _ -> "SetVersion"
| ListBookmarks -> "ListBookmarks"
| SetPageLayout _ -> "SetPageLayout"
| SetPageMode _ -> "SetPageMode"
| SetNonFullScreenPageMode _ -> "SetNonFullScreenPageMode"
| HideToolbar _ -> "HideToolbar"
| HideMenubar _ -> "HideMenubar"
| HideWindowUI _ -> "HideWindowUI"
| FitWindow _ -> "FitWindow"
| CenterWindow _ -> "CenterWindow"
| DisplayDocTitle _ -> "DisplayDocTitle"
| Presentation -> "Presentation"
| ChangeId -> "ChangeId"
| RemoveId -> "RemoveId"
| CopyId _ -> "CopyId"
| BlackText -> "BlackText"
| BlackLines -> "BlackLines"
| BlackFills -> "BlackFills"
| ExtractImages -> "ExtractImages"
| ListImages -> "ListImages"
| ImageResolution _ -> "ImageResolution"
| MissingFonts -> "MissingFonts"
| ExtractFontFile _ -> "ExtractFontFile"
| ExtractText -> "ExtractText"
| OpenAtPage _ -> "OpenAtPage"
| OpenAtPageFit _ -> "OpenAtPageFit"
| OpenAtPageCustom _ -> "OpenAtPageCustom"
| AddPageLabels -> "AddPageLabels"
| RemovePageLabels -> "RemovePageLabels"
| PrintPageLabels -> "PrintPageLabels"
| RemoveDictEntry _ -> "RemoveDictEntry"
| ReplaceDictEntry _ -> "ReplaceDictEntry"
| ListSpotColours -> "ListSpotColours"
| RemoveClipping -> "RemoveClipping"
| Trim -> "Trim"
| Art -> "Art"
| Bleed -> "Bleed"
| RemoveArt -> "RemoveArt"
| RemoveTrim -> "RemoveTrim"
| RemoveBleed -> "RemoveBleed"
| SetMetadataDate _ -> "SetMetadataDate"
| CreateMetadata -> "CreateMetadata"
| EmbedMissingFonts -> "EmbedMissingFonts"
| BookmarksOpenToLevel _ -> "BookmarksOpenToLevel"
| CreatePDF -> "CreatePDF"
| RemoveAllText -> "RemoveAllText"
| ShowBoxes -> "ShowBoxes"
| TrimMarks -> "TrimMarks"
| Prepend _ -> "Prepend"
| Postpend _ -> "Postpend"
| OutputJSON -> "OutputJSON"
| OCGCoalesce -> "OCGCoalesce"
| OCGList -> "OCGList"
| OCGRename -> "OCGRename"
| OCGOrderAll -> "OCGOrderAll"
| StampAsXObject _ -> "StampAsXObject"
| TableOfContents -> "TableOfContents"
| Typeset _ -> "Typeset"
| TextWidth _ -> "TextWidth"
| Draw -> "Draw"
| Composition _ -> "Composition"
| Chop _ -> "Chop"
| ChopHV _ -> "ChopHV"
| ProcessImages -> "ProcessImages"
| ExtractStream _ -> "ExtractStream"
| ReplaceStream _ -> "ReplaceStream"
| PrintObj _ -> "PrintObj"
| ReplaceObj _ -> "ReplaceObj"
| Verify _ -> "Verify"
| MarkAs _ -> "MarkAs"
| RemoveMark _ -> "RemoveMark"
| PrintStructTree -> "PrintStructTree"
| ExtractStructTree -> "ExtractStructTree"
| ReplaceStructTree _ -> "ReplaceStructTree"
| RemoveStructTree -> "RemoveStructTree"
| MarkAsArtifact -> "MarkAsArtifact"
| SetLanguage _ -> "SetLanguage"
| Redact -> "Redact"
| Rasterize -> "Rasterize"
| OutputImage -> "OutputImage"
| RemoveObj _ -> "RemoveObj"
(* Inputs: filename, pagespec. *)
type input_kind =
| AlreadyInMemory of Pdf.t * string
| InFile of string
| StdIn
let string_of_input_kind = function
| AlreadyInMemory (_, s) -> s
| InFile s -> s
| StdIn -> "Stdin"
type input =
input_kind * string * string * string * bool ref * int option
(* input kind, range, user_pw, owner_pw, was_decrypted_with_owner, revision *)
type output_method =
| NoOutputSpecified
| Stdout
| File of string
(* Outputs are also added here, in case -spray is in use. *)
let spray_outputs = ref []
(* A list of PDFs to be output, if no output method was specified. *)
let output_pdfs : Pdf.t list ref = ref []
let standard_namespace = "http://iso.org/pdf/ssn"
let pdf2_namespace = "http://iso.org/pdf2/ssn"
type font =
| StandardFont of Pdftext.standard_font
| EmbeddedFont of string
| OtherFont of string
type args =
{mutable op : op option;
mutable preserve_objstm : bool;
mutable create_objstm : bool;
mutable out : output_method;
mutable inputs : input list;
mutable chunksize : int;
mutable linearize : bool;
mutable keeplinearize : bool;
mutable rectangle : string;
mutable coord : string;
mutable duration : float option;
mutable transition : string option;
mutable horizontal : bool;
mutable inward : bool;
mutable direction : int;
mutable effect_duration : float;
mutable font : font;
mutable fontname : string;
mutable fontencoding : Pdftext.encoding;
mutable fontsize : float;
mutable embedstd14 : string option;
mutable color : Cpdfaddtext.colour;
mutable opacity : float;
mutable position : Cpdfposition.position;
mutable underneath : bool;
mutable linespacing : float;
mutable midline : bool;
mutable topline : bool;
mutable justification : Cpdfaddtext.justification;
mutable bates : int;
mutable batespad : int option;
mutable prerotate : bool;
mutable relative_to_cropbox : bool;
mutable keepversion : bool;
mutable bycolumns : bool;
mutable pagerotation : int;
mutable crypt_method : string;
mutable owner : string;
mutable user : string;
mutable no_edit : bool;
mutable no_print : bool;
mutable no_copy : bool;
mutable no_annot : bool;
mutable no_forms : bool;
mutable no_extract : bool;
mutable no_assemble : bool;
mutable no_hq_print : bool;
mutable debug : bool;
mutable debugcrypt : bool;
mutable debugforce : bool;
mutable boxes : bool;
mutable encrypt_metadata : bool;
mutable retain_numbering : bool;
mutable process_struct_trees : bool;
mutable remove_duplicate_fonts : bool;
mutable remove_duplicate_streams : bool;
mutable encoding : Cpdfmetadata.encoding;
mutable scale : float;
mutable copyfontpage : int;
mutable copyfontname : string option;
mutable fast : bool;
mutable dashrange : string;
mutable outline : bool;
mutable linewidth : float;
mutable path_to_ghostscript : string;
mutable path_to_im : string;
mutable path_to_p2p : string;
mutable path_to_jbig2enc : string;
mutable frombox : string option;
mutable tobox : string option;
mutable mediabox_if_missing : bool;
mutable topage : string option;
mutable scale_stamp_to_fit : bool;
mutable labelstyle : Pdfpagelabels.labelstyle;
mutable labelprefix : string option;
mutable labelstartval : int;
mutable labelsprogress : bool;
mutable squeeze : bool;
mutable squeeze_recompress : bool;
mutable squeeze_pagedata: bool;
mutable original_filename : string;
mutable was_encrypted : bool;
mutable cpdflin : string option;
mutable recrypt : bool;
mutable was_decrypted_with_owner : bool;
mutable creator : string option;
mutable producer : string option;
mutable extract_text_font_size : float option;
mutable padwith : string option;
mutable alsosetxml : bool;
mutable justsetxml : bool;
mutable gs_malformed : bool;
mutable gs_quiet : bool;
mutable merge_add_bookmarks : bool;
mutable merge_add_bookmarks_use_titles : bool;
mutable createpdf_pages : int;
mutable createpdf_pagesize : Pdfpaper.t;
mutable removeonly : string option;
mutable jsonparsecontentstreams : bool;
mutable jsonnostreamdata : bool;
mutable jsondecompressstreams : bool;
mutable jsoncleanstrings : bool;
mutable ocgrenamefrom : string;
mutable ocgrenameto : string;
mutable dedup : bool;
mutable dedup_per_page : bool;
mutable collate : int;
mutable impose_columns : bool;
mutable impose_rtl : bool;
mutable impose_btt : bool;
mutable impose_center : bool;
mutable impose_margin : float;
mutable impose_spacing : float;
mutable impose_linewidth : float;
mutable format_json : bool;
mutable replace_dict_entry_value : Pdf.pdfobject;
mutable dict_entry_search : Pdf.pdfobject option;
mutable toc_title : string;
mutable toc_bookmark : bool;
mutable idir_only_pdfs : bool;
mutable no_warn_rotate : bool;
mutable jpegquality : float;
mutable jpegqualitylossless : float;
mutable jpegtojpegscale : float;
mutable jpegtojpegdpi : float;
mutable onebppmethod : string;
mutable pixel_threshold : int;
mutable length_threshold : int;
mutable percentage_threshold : float;
mutable dpi_threshold : float;
mutable resample_factor : float;
mutable resample_interpolate : bool;
mutable jbig2_lossy_threshold : float;
mutable extract_stream_decompress : bool;
mutable verify_single : string option;
mutable draw_struct_tree : bool;
mutable subformat : Cpdfua.subformat option;
mutable indent : float option;
mutable title : string option;
mutable rast_device : string;
mutable rast_res : float;
mutable rast_annots : bool;
mutable rast_antialias : bool;
mutable rast_jpeg_quality : int;
mutable rast_downsample : bool;
mutable replace_stream_with : string;
mutable output_unit : Pdfunits.t;
mutable dot_leader : bool;
mutable preserve_actions : bool}
let args =
{op = None;
preserve_objstm = true;
create_objstm = false;
out = NoOutputSpecified;
inputs = [];
chunksize = 1;
linearize = false;
keeplinearize = false;
rectangle = "0 0 0 0";
coord = "0 0";
duration = None;
transition = None;
horizontal = true;
inward = true;
direction = 0;
effect_duration = 1.;
font = StandardFont Pdftext.TimesRoman;
fontname = "Times-Roman";
fontsize = 12.;
fontencoding = Pdftext.WinAnsiEncoding;
color = Cpdfaddtext.RGB (0., 0., 0.);
opacity = 1.;
position = Cpdfposition.TopLeft (100., 100.);
underneath = false;
linespacing = 1.;
midline = false;
topline = false;
justification = Cpdfaddtext.LeftJustify;
bates = 0;
batespad = None;
prerotate = false;
relative_to_cropbox = false;
keepversion = false;
bycolumns = false;
pagerotation = 0;
crypt_method = "";
owner = "";
user = "";
no_edit = false;
no_print = false;
no_copy = false;
no_annot = false;
no_forms = false;
no_extract = false;
no_assemble = false;
no_hq_print = false;
debug = false;
debugcrypt = false;
debugforce = false;
boxes = false;
encrypt_metadata = true;
retain_numbering = false;
process_struct_trees = false;
remove_duplicate_fonts = false;
remove_duplicate_streams = false;
encoding = Cpdfmetadata.Stripped;
scale = 1.;
copyfontpage = 1;
copyfontname = None;
fast = false;
dashrange = "all";
outline = false;
linewidth = 1.0;
path_to_ghostscript = "";
path_to_im = "";
path_to_p2p = "";
path_to_jbig2enc = "";
frombox = None;
tobox = None;
mediabox_if_missing = false;
topage = None;
scale_stamp_to_fit = false;
labelstyle = Pdfpagelabels.DecimalArabic;
labelprefix = None;
labelstartval = 1;
labelsprogress = false;
squeeze = false;
squeeze_recompress = true;
squeeze_pagedata = true;
original_filename = "";
was_encrypted = false;
cpdflin = None;
recrypt = false;
was_decrypted_with_owner = false;
producer = None;
creator = None;
embedstd14 = None;
extract_text_font_size = None;
padwith = None;
alsosetxml = false;
justsetxml = false;
gs_malformed = false;
gs_quiet = false;
merge_add_bookmarks = false;
merge_add_bookmarks_use_titles = false;
createpdf_pages = 1;
createpdf_pagesize = Pdfpaper.a4;
removeonly = None;
jsonparsecontentstreams = false;
jsonnostreamdata = false;
jsondecompressstreams = false;
jsoncleanstrings = false;
ocgrenamefrom = "";
ocgrenameto = "";
dedup = false;
dedup_per_page = false;
collate = 0;
impose_columns = false;
impose_rtl = false;
impose_btt = false;
impose_center = false;
impose_margin = 0.;
impose_spacing = 0.;
impose_linewidth = 0.;
format_json = false;
replace_dict_entry_value = Pdf.Null;
dict_entry_search = None;
toc_title = "Table of Contents";
toc_bookmark = true;
idir_only_pdfs = false;
no_warn_rotate = false;
jpegquality = 100.;
jpegqualitylossless = 101.;
jpegtojpegscale = 100.;
jpegtojpegdpi = 0.;
onebppmethod = "";
pixel_threshold = 25;
length_threshold = 100;
percentage_threshold = 99.;
dpi_threshold = 0.;
resample_factor = 101.;
resample_interpolate = false;
jbig2_lossy_threshold = 0.85;
extract_stream_decompress = false;
verify_single = None;
draw_struct_tree = false;
subformat = None;
indent = None;
title = None;
rast_device = "png16m";
rast_res = 144.;
rast_annots = false;
rast_antialias = true;
rast_jpeg_quality = 75;
rast_downsample = false;
replace_stream_with = "";
output_unit = Pdfunits.PdfPoint;
dot_leader = false;
preserve_actions = false}
(* Do not reset original_filename or cpdflin or was_encrypted or
was_decrypted_with_owner or recrypt or producer or creator or path_to_* or
gs_malformed or gs_quiet or no-warn-rotate, since we want these to work
across ANDs. Or squeeze options: a little odd, but we want it to happen on
eventual output. Or -debug-force (from v2.6). *)
let reset_arguments () =
args.op <- None;
args.preserve_objstm <- true;
args.create_objstm <- false;
args.out <- NoOutputSpecified;
args.inputs <- [];
args.chunksize <- 1;
args.linearize <- false;
args.keeplinearize <- false;
args.rectangle <- "0 0 0 0";
args.coord <- "0 0";
args.duration <- None;
args.transition <- None;
args.horizontal <- true;
args.inward <- true;
args.direction <- 0;
args.effect_duration <- 1.;
args.font <- StandardFont Pdftext.TimesRoman;
args.fontname <- "Times-Roman";
args.fontsize <- 12.;
args.fontencoding <- Pdftext.WinAnsiEncoding;
args.color <- Cpdfaddtext.RGB (0., 0., 0.);
args.opacity <- 1.;
args.position <- Cpdfposition.TopLeft (100., 100.);
args.underneath <- false;
args.linespacing <- 1.;
args.midline <- false;
args.topline <- false;
args.justification <- Cpdfaddtext.LeftJustify;
args.bates <- 0;
args.batespad <- None;
args.prerotate <- false;
args.relative_to_cropbox <- false;
args.keepversion <- false;
args.bycolumns <- false;
args.pagerotation <- 0;
args.crypt_method <- "";
args.owner <- "";
args.user <- "";
args.no_edit <- false;
args.no_print <- false;
args.no_copy <- false;
args.no_annot <- false;
args.no_forms <- false;
args.no_extract <- false;
args.no_assemble <- false;
args.no_hq_print <- false;
args.debug <- false;
args.debugcrypt <- false;
args.boxes <- false;
args.encrypt_metadata <- true;
args.retain_numbering <- false;
args.process_struct_trees <- false;
args.remove_duplicate_fonts <- false;
args.remove_duplicate_streams <- false;
args.encoding <- Cpdfmetadata.Stripped;
args.scale <- 1.;
args.copyfontpage <- 1;
args.copyfontname <- None;
args.fast <- false;
args.dashrange <- "all";
args.outline <- false;
args.linewidth <- 1.0;
args.frombox <- None;
args.tobox <- None;
args.mediabox_if_missing <- false;
args.topage <- None;
args.scale_stamp_to_fit <- false;
args.labelstyle <- Pdfpagelabels.DecimalArabic;
args.labelprefix <- None;
args.labelstartval <- 1;
args.labelsprogress <- false;
args.embedstd14 <- None;
args.extract_text_font_size <- None;
args.padwith <- None;
args.alsosetxml <- false;
args.justsetxml <- false;
args.merge_add_bookmarks <- false;
args.merge_add_bookmarks_use_titles <- false;
args.createpdf_pages <- 1;
args.createpdf_pagesize <- Pdfpaper.a4;
args.removeonly <- None;
args.jsonparsecontentstreams <- false;
args.jsonnostreamdata <- false;
args.jsondecompressstreams <- false;
args.jsoncleanstrings <- false;
args.ocgrenamefrom <- "";
args.ocgrenameto <- "";
args.dedup <- false;
args.dedup_per_page <- false;
args.collate <- 0;
args.impose_columns <- false;
args.impose_rtl <- false;
args.impose_btt <- false;
args.impose_center <- false;
args.impose_margin <- 0.;
args.impose_spacing <- 0.;
args.impose_linewidth <- 0.;
args.format_json <- false;
args.replace_dict_entry_value <- Pdf.Null;
args.dict_entry_search <- None;
args.toc_title <- "Table of Contents";
args.toc_bookmark <- true;
args.idir_only_pdfs <- false;
args.jpegquality <- 100.;
args.jpegqualitylossless <- 101.;
args.onebppmethod <- "";
args.pixel_threshold <- 25;
args.length_threshold <- 100;
args.percentage_threshold <- 99.;
args.dpi_threshold <- 0.;
args.resample_factor <- 101.;
args.resample_interpolate <- false;
args.jbig2_lossy_threshold <- 0.85;
args.extract_stream_decompress <- false;
clear Cpdfdrawcontrol.fontpack_initialised;
args.verify_single <- None;
args.draw_struct_tree <- false;
args.subformat <- None;
args.indent <- None;
args.title <- None;
args.rast_device <- "png16m";
args.rast_res <- 144.;
args.rast_annots <- false;
args.rast_antialias <- true;
args.rast_jpeg_quality <- 75;
args.rast_downsample <- false;
args.replace_stream_with <- "";
args.output_unit <- Pdfunits.PdfPoint;
args.dot_leader <- false;
args.preserve_actions <- false
(* Prefer a) the one given with -cpdflin b) a local cpdflin, c) otherwise assume
installed at a system place *)
let find_cpdflin provided =
match provided with
Some x -> x
| None ->
let dotslash = match Sys.os_type with "Win32" -> "" | _ -> "./" in
if Sys.file_exists "cpdflin" then (dotslash ^ "cpdflin") else
if Sys.file_exists "cpdflin.exe" then (dotslash ^ "cpdflin.exe") else
match Sys.os_type with
"Win32" -> "cpdflin.exe"
| _ -> "cpdflin"
(* Call cpdflin, given the (temp) input name, the output name, and the location
of the cpdflin binary. Returns the exit code. *)
let call_cpdflin cpdflin temp output best_password =
let command =
Filename.quote_command cpdflin
["--linearize"; ("--password=" ^ best_password); temp; output]
in
match Sys.os_type with
"Win32" ->
(* On windows, don't use LD_LIBRARY_PATH - it will happen automatically *)
if args.debug then Pdfe.log (command ^ "\n");
Sys.command command
| _ ->
(* On other platforms, if -cpdflin was provided, or cpdflin was in the
current folder, set up LD_LIBRARY_PATH: *)
match cpdflin with
"cpdflin" ->
if args.debug then Pdfe.log (command ^ "\n");
Sys.command command
| _ ->
let command =
"DYLD_FALLBACK_LIBRARY_PATH=" ^ Filename.quote (Filename.dirname cpdflin) ^ " " ^
"LD_LIBRARY_PATH=" ^ Filename.quote (Filename.dirname cpdflin) ^ " " ^
command
in
if args.debug then Pdfe.log (command ^ "\n");
Sys.command command
let get_pagespec () =
match args.inputs with
| (_, ps, _, _, _, _)::_ -> ps
| _ -> error "No range specified for input, or specified too late."
let string_of_permission = function
| Pdfcrypt.NoEdit -> "No edit"
| Pdfcrypt.NoPrint -> "No print"
| Pdfcrypt.NoCopy -> "No copy"
| Pdfcrypt.NoAnnot -> "No annotate"
| Pdfcrypt.NoForms -> "No edit forms"
| Pdfcrypt.NoExtract -> "No extract"
| Pdfcrypt.NoAssemble -> "No assemble"
| Pdfcrypt.NoHqPrint -> "No high-quality print"
let getpermissions pdf =
fold_left
(fun x y -> if x = "" then x ^ y else x ^ ", " ^ y)
""
(map string_of_permission (Pdfread.permissions pdf))
let banlist_of_args () =
let l = ref [] in
if args.no_edit then l =| Pdfcrypt.NoEdit;
if args.no_print then l =| Pdfcrypt.NoPrint;
if args.no_copy then l =| Pdfcrypt.NoCopy;
if args.no_annot then l =| Pdfcrypt.NoAnnot;
if args.no_forms then l =| Pdfcrypt.NoForms;
if args.no_extract then l =| Pdfcrypt.NoExtract;
if args.no_assemble then l =| Pdfcrypt.NoAssemble;
if args.no_hq_print then l =| Pdfcrypt.NoHqPrint;
!l
(* If a file is encrypted, decrypt it using the owner password or, if not
present, the user password. If the user password is used, the operation to be
performed is checked to see if it's allowable under the permissions regime. *)
(* The bans. Each function has a list of bans. If any of these is present in the
bans list in the input file, the operation cannot proceed. Other operations
cannot proceed at all without owner password. *)
let banned banlist = function
| Fonts | Info | Metadata | PageInfo | CountPages
| ListAttachedFiles | ListAnnotations
| ListBookmarks | ImageResolution _ | ListImages | MissingFonts
| PrintPageLabels | Clean | Compress | Decompress
| ChangeId | CopyId _ | ListSpotColours | Version
| DumpAttachedFiles | RemoveMetadata | EmbedMissingFonts | BookmarksOpenToLevel _ | CreatePDF
| SetPageMode _ | SetNonFullScreenPageMode _ | HideToolbar _ | HideMenubar _ | HideWindowUI _
| FitWindow _ | CenterWindow _ | DisplayDocTitle _
| RemoveId | OpenAtPageFit _ | OpenAtPage _ | OpenAtPageCustom _ | SetPageLayout _
| ShowBoxes | TrimMarks | CreateMetadata | SetMetadataDate _ | SetVersion _
| SetAuthor _|SetTitle _|SetSubject _|SetKeywords _|SetCreate _
| SetModify _|SetCreator _|SetProducer _|RemoveDictEntry _ | ReplaceDictEntry _ | PrintDictEntry _ | SetMetadata _
| ExtractText | ExtractImages | ExtractFontFile _
| AddPageLabels | RemovePageLabels | OutputJSON | OCGCoalesce
| OCGRename | OCGList | OCGOrderAll | PrintFontEncoding _ | TableOfContents | Typeset _ | Composition _
| TextWidth _ | SetAnnotations _ | CopyAnnotations _ | ExtractStream _ | ReplaceStream _ | PrintObj _ | ReplaceObj _ | RemoveObj _
| Verify _ | MarkAs _ | RemoveMark _ | ExtractStructTree | ReplaceStructTree _ | SetLanguage _
| PrintStructTree | Rasterize | OutputImage | RemoveStructTree | MarkAsArtifact
-> false (* Always allowed *)
(* Combine pages is not allowed because we would not know where to get the
-recrypt from -- the first or second file? *)
| Decrypt | Encrypt | CombinePages _ -> true (* Never allowed *)
| AddBookmarks _ | PadBefore | PadAfter | PadEvery _ | PadMultiple _ | PadMultipleBefore _
| Merge | Split | SplitOnBookmarks _ | SplitMax _ | Spray | RotateContents _ | Rotate _
| Rotateby _ | Upright | VFlip | HFlip | Impose _ | Chop _ | ChopHV _ | Redact ->
mem Pdfcrypt.NoAssemble banlist
| TwoUp | TwoUpStack | RemoveBookmarks | AddRectangle | RemoveText|
Draft | Shift | ShiftBoxes | Scale | ScaleToFit|Stretch|CenterToFit|RemoveAttachedFiles|
RemoveAnnotations|RemoveFonts|Crop|RemoveCrop|Trim|RemoveTrim|Bleed|RemoveBleed|Art|RemoveArt|
CopyBox|MediaBox|HardBox _|SetTrapped|SetUntrapped|Presentation|
BlackText|BlackLines|BlackFills|CopyFont _|StampOn _|StampUnder _|StampAsXObject _|
AddText _|ScaleContents _|AttachFile _| ThinLines _ | RemoveClipping | RemoveAllText
| Prepend _ | Postpend _ | Draw | ProcessImages ->
mem Pdfcrypt.NoEdit banlist
let operation_allowed pdf banlist op =
args.debugforce ||
match op with
| None ->
if args.debugcrypt then Printf.printf "operation is None, so allowed!\n";
true (* Merge *) (* changed to allow it *)
| Some op ->
if args.debugcrypt then Printf.printf "operation_allowed: op = %s\n" (string_of_op op);
if args.debugcrypt then Printf.printf "Permissions: %s\n" (getpermissions pdf);
not (banned banlist op)
let decrypt_if_necessary (_, _, user_pw, owner_pw, was_dec_with_owner, _) op pdf =
if args.debugcrypt then
begin match op with
None -> flprint "decrypt_if_necessary: op = None\n"
| Some x -> Printf.printf "decrypt_if_necessary: op = %s\n" (string_of_op x)
end;
if not (Pdfcrypt.is_encrypted pdf) then pdf else
match op with Some (CombinePages _) ->
(* This is a hack because we don't have support for recryption on combine
* pages. This is prevented by permissions above, but in the case that the
* owner password is blank (e.g christmas_tree_lights.pdf), we would end
* up here. *)
soft_error "Combine pages: both files must be unencrypted for this operation, or add -decrypt-force"
| _ ->
match Pdfcrypt.decrypt_pdf_owner owner_pw pdf with
| Some pdf ->
args.was_decrypted_with_owner <- true;
was_dec_with_owner := true;
if args.debugcrypt then Printf.printf "Managed to decrypt with owner password\n";
pdf
| _ ->
if args.debugcrypt then Printf.printf "Couldn't decrypt with owner password %s\n" owner_pw;
match
if args.debugcrypt then Printf.printf "call decrypt_pdf user\n";
let r = Pdfcrypt.decrypt_pdf user_pw pdf in
if args.debugcrypt then Printf.printf "returned from decrypt_pdf\n";
r
with
| Some pdf, permissions ->
if args.debugcrypt then Printf.printf "Managed to decrypt with user password\n";
if operation_allowed pdf permissions op
then pdf
else soft_error "User password cannot give permission for this operation. Supply owner or add -decrypt-force."
| _ ->
if args.debugcrypt then Printf.printf "Failed to decrypt with user password: raising soft_error";
soft_error "Failed to decrypt file: wrong password?"
(* Output Page Count *)
let output_page_count pdf =
Printf.printf "%i\n" ((if args.fast then Pdfpage.endpage_fast else Pdfpage.endpage) pdf)
let detect_duplicate_op op =
match args.op with
None | Some Shift -> ()
| _ ->
Pdfe.log (Printf.sprintf "Operation %s already specified, so cannot specify operation %s.\nUse AND from Chapter 1 of the manual to chain commands together.\n"
(string_of_op (unopt args.op)) (string_of_op op));
exit 1
let setop op () =
detect_duplicate_op op;
args.op <- Some op
let setout name =
args.out <- File name;
spray_outputs := name::!spray_outputs
let setchunk c =
if c > 0
then args.chunksize <- c
else error "invalid chunk size"
let fixdashes s =
let bufferdashes chars =
let buf = ref [] in
iter
(function '-' -> buf =@ [' '; '-'; ' '] | x -> buf =| x)
chars;
rev !buf
in
let chars = explode s in
implode (bufferdashes chars)
let set_input_image f s =
try
let fh = open_in_bin s in
let pdf = Cpdfimage.image_of_input ?subformat:args.subformat ?title:args.title ~process_struct_tree:args.process_struct_trees f (Pdfio.input_of_channel fh) in
begin try close_in fh with _ -> () end;
args.original_filename <- s;
args.create_objstm <- true;
args.inputs <- (AlreadyInMemory (pdf, s), "all", "", "", ref false, None)::args.inputs
with
Sys_error _ -> error "Image file not found"
let jbig2_global = ref None
let set_input_png s = set_input_image (fun () -> Cpdfimage.obj_of_png_data) s
let set_input_jpeg s = set_input_image (fun () -> Cpdfimage.obj_of_jpeg_data) s
let set_input_jpeg2000 s = set_input_image (fun () -> Cpdfimage.obj_of_jpeg2000_data) s
let set_input_jbig2 s =
set_input_image
(fun () -> Cpdfimage.obj_of_jbig2_data ?global:!jbig2_global) s;
args.remove_duplicate_streams <- true
let encrypt_to_collect = ref 0
let setmethod s =
detect_duplicate_op Encrypt;
if args.op = None then args.op <- Some Encrypt; (* Could be additional to -split *)
match s with
| "40bit" | "128bit" | "AES" | "AES256" | "AES256ISO" -> args.crypt_method <- s
| _ -> error ("Unsupported encryption method " ^ s)
let anon_fun s =
try
match !encrypt_to_collect with
| 3 -> setmethod s; decr encrypt_to_collect
| 2 -> args.owner <- s; decr encrypt_to_collect
| 1 -> args.user <- s; decr encrypt_to_collect
| 0 ->
let before, after = cleavewhile (neq '=') (explode s) in
begin match implode before with
| "user" ->
begin match args.inputs with
| [] -> ()
| (a, b, _, e, f, g)::more ->
args.inputs <- (a, b, implode (tl after), e, f, g)::more
end
| "owner" ->
begin match args.inputs with
| [] -> ()
| (a, b, d, _, f, g)::more ->
args.inputs <- (a, b, d, implode (tl after), f, g)::more
end
| _ -> raise Not_found
end
| _ -> assert false
with
Not_found ->
try
ignore (String.index s '.');
begin match rev (explode s) with
| a::b::c::d::e::'.'::r when implode (map Char.uppercase_ascii [e; d; c; b; a]) = "JBIG2" -> set_input_jbig2 s
| a::b::c::d::'.'::r when implode (map Char.uppercase_ascii [d; c; b; a]) = "JPEG" -> set_input_jpeg s
| a::b::c::'.'::r when implode (map Char.uppercase_ascii [c; b; a]) = "JPG" -> set_input_jpeg s
| a::b::c::'.'::r when implode (map Char.uppercase_ascii [c; b; a]) = "JP2" -> set_input_jpeg2000 s
| a::b::c::'.'::r when implode (map Char.uppercase_ascii [c; b; a]) = "JPX" -> set_input_jpeg2000 s
| a::b::c::'.'::r when implode (map Char.uppercase_ascii [c; b; a]) = "JPF" -> set_input_jpeg2000 s
| a::b::c::'.'::r when implode (map Char.uppercase_ascii [c; b; a]) = "PNG" -> set_input_png s
| _ -> args.inputs <- (InFile s, "all", "", "", ref false, None)::args.inputs
end;
args.original_filename <- s
with
Not_found ->
match args.inputs with
| [] ->
Pdfe.log (Printf.sprintf "Warning: '%s' ignored\n" s)
| (a, _, d, e, f, g)::t ->
args.inputs <- (a, fixdashes s, d, e, f, g)::t
(* If a password begins with a dash, we allow -pw=<password> too *)
let setdashpassword = anon_fun
(* Setting operations *)
let setcrop s =
setop Crop ();
args.rectangle <- s
let settrim s =
setop Trim ();
args.rectangle <- s
let setbleed s =
setop Bleed ();
args.rectangle <- s
let setart s =
setop Art ();
args.rectangle <- s
let setmediabox s =
setop MediaBox ();
args.rectangle <- s
let setrectangle s =
setop AddRectangle ();
args.coord <- s
let setrotate i =
if i = 0 || i = 90 || i = 180 || i = 270
then setop (Rotate i) ()
else error "bad rotation"
let setrotateby i =
if i = 0 || i = 90 || i = 180 || i = 270
then setop (Rotateby i) ()
else error "bad rotation"
let hidetoolbar b =
try setop (HideToolbar (bool_of_string b)) () with
_ -> failwith "HideToolBar: must use true or false"
let hidemenubar b =
try setop (HideMenubar (bool_of_string b)) () with
_ -> failwith "HideMenuBar: must use true or false"
let hidewindowui b =
try setop (HideWindowUI (bool_of_string b)) () with
_ -> failwith "HideWindowUI: must use true or false"
let fitwindow b =
try setop (FitWindow (bool_of_string b)) () with
_ -> failwith "FitWindow: must use true or false"
let centerwindow b =
try setop (CenterWindow (bool_of_string b)) () with
_ -> failwith "CenterWindow: must use true or false"
let displaydoctitle b =
try setop (DisplayDocTitle (bool_of_string b)) () with
_ -> failwith "DisplayDocTitle: must use true or false"
let read_file_size s =
let read_int s' =
try int_of_string (implode (rev s')) with
_ -> error (Printf.sprintf "Could not read file size specification %s" s)
in
match rev (explode (String.uppercase_ascii s)) with
| 'B'::'I'::'G'::s -> 1024 * 1024 * 1024 * read_int s
| 'B'::'G'::s -> 1000 * 1000 * 1000 * read_int s
| 'B'::'I'::'M'::s -> 1024 * 1024 * read_int s
| 'B'::'M'::s -> 1000 * 1000 * read_int s
| 'B'::'I'::'K'::s -> 1024 * read_int s
| 'B'::'K'::s -> 1000 * read_int s
| s -> read_int s
let setsplitmax i = setop (SplitMax (read_file_size i)) ()
let setstdout () = args.out <- Stdout
let setstdin () = args.inputs <- [StdIn, "all", "", "", ref false, None]
let settrans s = args.transition <- Some s
let setduration f = args.duration <- Some f
let setvertical () = args.horizontal <- false
let setoutward () = args.inward <- false
let setdirection i =
args.direction <-
match i with
| 0 | 90 | 180 | 270 | 315 -> i
| _ -> error "Bad direction"
let seteffectduration f = args.effect_duration <- f
let setcopyid s = setop (CopyId s) ()
let setthinlines s = setop (ThinLines (Cpdfcoord.parse_single_number empty s)) ()
let setcopyannotations s = setop (CopyAnnotations s) ()
let setsetannotations s = setop (SetAnnotations s) ()
let setshift s =
setop Shift ();
args.coord <- s
let setshiftboxes s =
setop ShiftBoxes ();
args.coord <- s
let setscale s =
setop Scale ();
args.coord <- s
let setscaletofit s =
setop ScaleToFit ();
args.coord <- s
let setstretch s =
setop Stretch ();
args.coord <- s
let setcentertofit s =
setop CenterToFit ();
args.coord <- s
let setattachfile s =
match args.op with
| Some (AttachFile t) ->
args.op <- Some (AttachFile (s::t))
| None ->
setop (AttachFile [s]) ()
| Some _ -> detect_duplicate_op (AttachFile [s])
let setextracttextfontsize f =
args.extract_text_font_size <- Some f
let setfontsize s =
let f = Cpdfcoord.parse_single_number (Pdf.empty ()) s in
if f > 0. then args.fontsize <- f else error "Negative font size specified"
let setlinewidth s =
let f = Cpdfcoord.parse_single_number (Pdf.empty ()) s in
if f > 0. then args.linewidth <- f else error "Negative line width specified"
let setimposemargin s =
let f = Cpdfcoord.parse_single_number (Pdf.empty ()) s in
args.impose_margin <- f
let setimposelinewidth s =
let f = Cpdfcoord.parse_single_number (Pdf.empty ()) s in
if f > 0. then args.impose_linewidth <- f else error "Negative impose line width specified"
let setimposespacing s =
let f = Cpdfcoord.parse_single_number (Pdf.empty ()) s in
args.impose_spacing <- f
let setleading s =
let f = Cpdfcoord.parse_single_number (Pdf.empty ()) s in
Cpdfdrawcontrol.addop (Cpdfdraw.Leading f)
let setcharspace s =
let f = Cpdfcoord.parse_single_number (Pdf.empty ()) s in
Cpdfdrawcontrol.addop (Cpdfdraw.CharSpace f)
let setwordspace s =
let f = Cpdfcoord.parse_single_number (Pdf.empty ()) s in
Cpdfdrawcontrol.addop (Cpdfdraw.WordSpace f)
let setrise s =
let f = Cpdfcoord.parse_single_number (Pdf.empty ()) s in
Cpdfdrawcontrol.addop (Cpdfdraw.Rise f)
let setaddtext s =
setop (AddText s) ()
let setcolor s =
args.color <- Cpdfdrawcontrol.parse_colour s
let setopacity o =
args.opacity <- o
let setaddbookmarks s =
setop (AddBookmarks s) ()
let setaddbookmarksjson s =
setop (AddBookmarks s) ();
args.format_json <- true
let setlistfontsjson () =
setop Fonts ();
args.format_json <- true
let setinfojson () =
setop Info ();
args.format_json <- true
let setpageinfojson () =
setop PageInfo ();
args.format_json <- true
let setprintpagelabelsjson () =
setop PrintPageLabels ();
args.format_json <- true
let setlistbookmarksjson () =
setop ListBookmarks ();
args.format_json <- true
let setlistannotationsjson () =
setop ListAnnotations ();
args.format_json <- true
let setstampon f =
setop (StampOn f) ();
(* Due to an earlier bad decision (default position), we have this nasty hack *)
if args.position = Cpdfposition.TopLeft (100., 100.) then args.position <- Cpdfposition.BottomLeft (0., 0.)
let setstampunder f =
setop (StampUnder f) ();
if args.position = Cpdfposition.TopLeft (100., 100.) then args.position <- Cpdfposition.BottomLeft (0., 0.)
let setstampasxobject f =
setop (StampAsXObject f) ()
let setcombinepages f =
setop (CombinePages f) ()
let setposcenter s =
let x, y = Cpdfcoord.parse_coordinate empty s in
args.position <- Cpdfposition.PosCentre (x, y)
let setposleft s =
let x, y = Cpdfcoord.parse_coordinate empty s in
args.position <- Cpdfposition.PosLeft (x, y)
let setposright s =
let x, y = Cpdfcoord.parse_coordinate empty s in
args.position <- Cpdfposition.PosRight (x, y)
let settop n =
args.position <- Cpdfposition.Top (Cpdfcoord.parse_single_number empty n);
args.justification <- Cpdfaddtext.CentreJustify
let settopleft n =
let coord =
match Cpdfcoord.parse_coordinate empty n with
| (a, b) -> Cpdfposition.TopLeft (a, b)
| exception _ ->
let x = Cpdfcoord.parse_single_number empty n in
Cpdfposition.TopLeft (x, x)
in
args.position <- coord;
args.justification <- Cpdfaddtext.LeftJustify
let settopright n =
let coord =
match Cpdfcoord.parse_coordinate empty n with
| (a, b) -> Cpdfposition.TopRight (a, b)
| exception _ ->
let x = Cpdfcoord.parse_single_number empty n in
Cpdfposition.TopRight (x, x)
in
args.position <- coord;
args.justification <- Cpdfaddtext.RightJustify
let setleft n =
args.position <- Cpdfposition.Left (Cpdfcoord.parse_single_number empty n);
args.justification <- Cpdfaddtext.LeftJustify
let setbottomleft n =
let coord =
match Cpdfcoord.parse_coordinate empty n with
| (a, b) -> Cpdfposition.BottomLeft (a, b)
| exception _ ->
let x = Cpdfcoord.parse_single_number empty n in
Cpdfposition.BottomLeft (x, x)
in
args.position <- coord;
args.justification <- Cpdfaddtext.LeftJustify
let setbottom n =
args.position <- Cpdfposition.Bottom (Cpdfcoord.parse_single_number empty n);
args.justification <- Cpdfaddtext.CentreJustify
let setbottomright n =
let coord =
match Cpdfcoord.parse_coordinate empty n with
| (a, b) -> Cpdfposition.BottomRight (a, b)
| exception _ ->
let x = Cpdfcoord.parse_single_number empty n in
Cpdfposition.BottomRight (x, x)
in
args.position <- coord;
args.justification <- Cpdfaddtext.RightJustify
let setright n =
args.position <- Cpdfposition.Right (Cpdfcoord.parse_single_number empty n);
args.justification <- Cpdfaddtext.RightJustify
let setdiagonal n =
args.position <- Cpdfposition.Diagonal;
args.justification <- Cpdfaddtext.CentreJustify
let setreversediagonal n =
args.position <- Cpdfposition.ReverseDiagonal;
args.justification <- Cpdfaddtext.CentreJustify
let setcenter n =
args.position <- Cpdfposition.Centre;
args.justification <- Cpdfaddtext.CentreJustify
(* Calculate -bates automatically so that n is applied to the first page in the range *)
let setbatesrange n =
let first_page =
let range = Cpdfpagespec.parse_pagespec_without_pdf (get_pagespec ()) in
fold_left min max_int range
in
args.bates <- n + 1 - first_page
let set_input s =
args.original_filename <- s;
args.inputs <- (InFile s, "all", "", "", ref false, None)::args.inputs
let set_json_input s =
args.original_filename <- s;
args.create_objstm <- true;
let fh = open_in_bin s in
let pdf = Cpdfjson.of_input (Pdfio.input_of_channel fh) in
close_in fh;
args.inputs <- (AlreadyInMemory (pdf, s), "all", "", "", ref false, None)::args.inputs
let set_input_dir s =
let names = sort compare (leafnames_of_dir s) in
let names =
if args.idir_only_pdfs then
option_map
(fun x ->
if String.length x > 4 && String.lowercase_ascii (String.sub x (String.length x - 4) 4) = ".pdf"
then Some x else None)
names
else
names
in
args.inputs <-
(rev
(map
(fun n -> (InFile (s ^ Filename.dir_sep ^ n), "all", "", "", ref false, None)) names))
@ args.inputs
let setdebug () =
set Pdfread.read_debug;
set Pdfwrite.write_debug;
set Pdfcrypt.crypt_debug;
set Pdfops.debug;
args.debug <- true
let setboxes () =
args.boxes <- true
let set_no_encrypt_metadata () =
args.encrypt_metadata <- false
let set_retain_numbering () =
args.retain_numbering <- true
let set_remove_duplicate_fonts () =
args.remove_duplicate_fonts <- true
let setencoding enc () =
args.encoding <- enc
let setscaletofitscale f =
args.scale <- f
let setscalecontents f =
detect_duplicate_op (ScaleContents f);
args.op <- Some (ScaleContents f);
args.position <- Cpdfposition.Diagonal (* Will be center *)
let setsqueeze () =
args.squeeze <- true;
args.create_objstm <- true
let setcreatoraswego s =
args.creator <- Some s
let setproduceraswego s =
args.producer <- Some s
let setprepend s =
args.op <- Some (Prepend s)
let setpostpend s =
args.op <- Some (Postpend s)
(* Parsing the control file *)
let rec getuntilendquote prev = function
| [] -> implode (rev prev), []
| '"'::t -> implode (rev prev), t
| '\\'::'"'::t -> getuntilendquote ('"'::prev) t
| h::t -> getuntilendquote (h::prev) t
let rec getarg prev = function
| [] -> implode (rev prev), []
| h::t ->
if Pdf.is_whitespace h
then implode (rev prev), t
else getarg (h::prev) t
let rec parse_chars args = function
| [] -> rev args
| h::more when Pdf.is_whitespace h ->
parse_chars args more
| '"'::more ->
let this, rest = getuntilendquote [] more in
parse_chars (this::args) rest
| h::t ->
let this, rest = getarg [] (h::t) in
parse_chars (this::args) rest
let parse_control_file name =
(parse_chars []
(charlist_of_bytes (Pdfio.bytes_of_input_channel (open_in_bin name))))
let parse_control_file_json name =
try
match Cpdfyojson.Safe.from_file name with
| `List ls -> map (function `String s -> s | _ -> raise Exit) ls
| _ -> raise Exit
with
Exit -> error "Syntax error in JSON control file."
let setencryptcollect () =
encrypt_to_collect := 3
let setcopyfont s =
detect_duplicate_op (CopyFont s);
args.op <- Some (CopyFont s)
let setfontpage i =
args.copyfontpage <- i
let setcopyfontname s =
args.copyfontname <- Some s
let setpadevery i =
detect_duplicate_op (PadEvery i);
if i > 0 then
args.op <- Some (PadEvery i)
else
error "PadEvery: must be > 0"
let setpadwith filename =
args.padwith <- Some filename
let setpadmultiple i =
detect_duplicate_op (PadMultiple i);
args.op <- Some (PadMultiple i)
let setpadmultiplebefore i =
detect_duplicate_op (PadMultipleBefore i);
args.op <- Some (PadMultipleBefore i)
let setfast () =
args.fast <- true
(* Explicitly add a range. Parse it and replace the top input file with the range. *)
let setrange spec =
args.dashrange <- spec;
match args.inputs with
(x, _, c, d, e, f)::more ->
args.inputs <- (x, spec, c, d, e, f) :: more
| x -> ()
let setrevision n =
match args.inputs with
(a, b, c, d, e, _)::more ->
args.inputs <- (a, b, c, d, e, Some n) :: more
| [] ->
Pdfe.log "Warning. -revision ignored. Put it after the filename.\n"
let setimageresolution f =
detect_duplicate_op (ImageResolution f);
args.op <- Some (ImageResolution f)
let setimpath p =
args.path_to_im <- p
let setjbig2encpath p =
args.path_to_jbig2enc <- p
let setp2ppath p =
args.path_to_p2p <- p
let setfrombox s =
detect_duplicate_op CopyBox;
args.op <- Some CopyBox;
args.frombox <- Some s
let settobox s =
args.tobox <- Some s
let setmediaboxifmissing () =
args.mediabox_if_missing <- true
let settopage s =
args.topage <- Some s
let setstdinuser u =
match args.inputs with
| (StdIn, x, _, o, f, g)::t -> args.inputs <- (StdIn, x, u, o, f, g)::t
| _ -> error "-stdin-user: must follow -stdin"
let setstdinowner o =
match args.inputs with
| (StdIn, x, u, _, f, g)::t -> args.inputs <- (StdIn, x, u, o, f, g)::t
| _ -> error "-stdin-owner: must follow -stdin"
let setopenatpage n =
detect_duplicate_op (OpenAtPage n);
args.op <- Some (OpenAtPage n)
let setopenatpagefit n =
detect_duplicate_op (OpenAtPageFit n);
args.op <- Some (OpenAtPageFit n)
let setopenatpagecustom n =
detect_duplicate_op (OpenAtPageCustom n);
args.op <- Some (OpenAtPageCustom n)
let setlabelstyle s =
let style =
match s with
| "DecimalArabic" -> Pdfpagelabels.DecimalArabic
| "UppercaseRoman" -> Pdfpagelabels.UppercaseRoman
| "LowercaseRoman" -> Pdfpagelabels.LowercaseRoman
| "UppercaseLetters" -> Pdfpagelabels.UppercaseLetters
| "LowercaseLetters" -> Pdfpagelabels.LowercaseLetters
| "NoLabelPrefixOnly" -> Pdfpagelabels.NoLabelPrefixOnly
| _ -> error "Unknown label style"
in
args.labelstyle <- style
let setlabelprefix s =
args.labelprefix <- Some s
let setlabelstartval i =
args.labelstartval <- i
let setlabelsprogress () =
args.labelsprogress <- true
let setcpdflin s =
args.cpdflin <- Some s
let setrecrypt () =
args.recrypt <- true
let setremovedictentry s =
detect_duplicate_op (RemoveDictEntry s);
args.op <- Some (RemoveDictEntry s)
let logto = ref None
let setsqueezelogto s =
logto := Some s
let setstayonerror () =
set stay_on_error
let setembedstd14 s =
args.embedstd14 <- Some s
let _ =
Cpdfdrawcontrol.setembedstd14 := (fun b dir -> if b then args.embedstd14 <- Some dir else args.embedstd14 <- None)
let sethardbox box =
detect_duplicate_op (HardBox box);
args.op <- Some (HardBox box)
let setalsosetxml () =
args.alsosetxml <- true
let setjustsetxml () =
args.justsetxml <- true
let setsetmetadatadate d =
detect_duplicate_op (SetMetadataDate d);
args.op <- Some (SetMetadataDate d)
let setgsmalformed () =
args.gs_malformed <- true
let setmergeaddbookmarks () =
args.merge_add_bookmarks <- true
let setmergeaddbookmarksusetitles () =
args.merge_add_bookmarks_use_titles <- true
let setbookmarksopentolevel l =
detect_duplicate_op (BookmarksOpenToLevel l);
args.op <- Some (BookmarksOpenToLevel l)
let setcreatepdfpages i =
args.createpdf_pages <- i
let setcreatepdfpapersize s =
args.createpdf_pagesize <-
let w, h = Cpdfcoord.parse_coordinate (Pdf.empty ()) s in
Pdfpaper.make Pdfunits.PdfPoint w h
let setimpose s =
setop (Impose true) ();
args.coord <- s
let setimposexy s =
setop (Impose false) ();
args.coord <- s
let setchop s =
let x, y = Cpdfcoord.parse_coordinate empty s in
setop (Chop (int_of_float x, int_of_float y)) ()
let setchopv x =
setop (ChopHV (false, Cpdfcoord.parse_single_number (Pdf.empty ()) x)) ()
let setchoph y =
setop (ChopHV (true, Cpdfcoord.parse_single_number (Pdf.empty ()) y)) ()
let setreplacedictentry s =
setop (ReplaceDictEntry s) ()
let setprintdictentry s =
setop (PrintDictEntry s) ()
let pdf_or_json s =
match explode s with
| 'P'::'D'::'F'::r -> Pdfread.parse_single_object (implode r)
| _ -> Cpdfjson.object_of_json (Cpdfyojson.Safe.from_string s)
let setreplacedictentryvalue s =
try
let pdfobj = pdf_or_json s in
args.replace_dict_entry_value <- pdfobj
with
e -> error (Printf.sprintf "Failed to parse replacement value: %s\n" (Printexc.to_string e))
let setdictentrysearch s =
try
let pdfobj = pdf_or_json s in
args.dict_entry_search <- Some pdfobj
with
e -> error (Printf.sprintf "Failed to parse search term: %s\n" (Printexc.to_string e))
let setprintfontencoding s =
setop (PrintFontEncoding s) ()
let settypeset s =
setop (Typeset s) ()
let setsubformat s =
args.subformat <- Some (Cpdfua.subformat_of_string s)
let settableofcontentstitle s =
args.toc_title <- s
let settocnobookmark () =
args.toc_bookmark <- false
let setidironlypdfs () =
args.idir_only_pdfs <- true
let setnowarnrotate () =
args.no_warn_rotate <- true
let whingemalformed () =
Pdfe.log "Command line must be of exactly the form\ncpdf <infile> -gs <path> -gs-malformed-force -o <outfile>\n";
exit 1
let addop o =
begin match o with Cpdfdraw.FontPack _ -> set Cpdfdrawcontrol.fontpack_initialised | _ -> () end;
begin match args.op with Some Draw -> () | _ -> error "Need to be in drawing mode for this." end;
Cpdfdrawcontrol.addop o
let embed_font_inner font =
match font with
| StandardFont f ->
(* Printf.printf "embed_font: StandardFont\n";*)
begin match args.embedstd14 with
| Some dirname ->
begin try
let fontfile, fontname = Cpdfembed.load_substitute dirname f in
Cpdfembed.EmbedInfo {fontfile; fontname; encoding = args.fontencoding}
with
e -> error (Printf.sprintf "Can't load font for embedding: %s\n" (Printexc.to_string e))
end
| None ->
PreMadeFontPack (Cpdfembed.fontpack_of_standardfont (Pdftext.StandardFont (f, args.fontencoding)))
end
| OtherFont f ->
ExistingNamedFont
| EmbeddedFont name ->
(*Printf.printf "embed_font: TTF\n";*)
try
let fontname, font = Hashtbl.find Cpdfdrawcontrol.ttfs name in
args.fontname <- fontname;
font
with
Not_found -> error (Printf.sprintf "Font %s not found" name)
let embed_font () = embed_font_inner args.font
let _ = Cpdfdrawcontrol.embed_font := embed_font
let _ = Cpdfdrawcontrol.setdrawing := (fun () -> args.op <- Some Draw)
let setfont f =
(*Printf.printf "Cpdfcommand.setfont: |%s|\n%!" f;*)
try
let fontname, _ = Hashtbl.find Cpdfdrawcontrol.ttfs f in
args.font <- EmbeddedFont f;
args.fontname <- fontname
with
Not_found ->
let convert f = (* convert from written PDF representation to internal PDF string e.g # sequences *)
match Pdfread.lex_name (Pdfio.input_of_string f) with Pdfgenlex.LexName s -> s | _ -> assert false
in
args.font <-
begin match Pdftext.standard_font_of_name ("/" ^ f) with
| Some x -> StandardFont x
| None ->
if f <> "" && hd (explode f) <> '/' then error "Font not found";
OtherFont (convert f)
end;
args.fontname <-
begin match Pdftext.standard_font_of_name ("/" ^ f) with
| Some x -> f
| None -> convert f
end;
(* If drawing, add the font pack as an op. *)
begin match args.op with Some Draw -> addop (Cpdfdraw.FontPack (f, embed_font (), null_hash ())) | _ -> () end
let loadttf n =
(*Printf.printf "loadttf: %s\n" n;*)
let name, filename =
match String.split_on_char '=' n with
| [name; filename] -> name, filename
| _ -> error "loadttf: bad file specification. Should be <name>=<filename>"
in
try
let fontfile = Pdfio.bytes_of_string (contents_of_file filename) in
let fontname = Filename.remove_extension (Filename.basename filename) in
Hashtbl.replace
Cpdfdrawcontrol.ttfs
name
(fontname, Cpdfembed.EmbedInfo {fontfile; fontname; encoding = args.fontencoding});
(* If drawing, add the font pack as an op. *)
begin match args.op with
Some Draw -> addop (Cpdfdraw.FontPack (fontname, embed_font_inner (EmbeddedFont name), null_hash ())) | _ -> () end
with
_ -> error "addtff: could not load TTF"
let () = Cpdfdrawcontrol.loadttf := loadttf
let setstderrtostdout () =
Pdfe.logger := (fun s -> print_string s; flush stdout)
let settextwidth s =
args.op <- Some (TextWidth s)
let setdraw () =
args.op <- Some Draw
let setdrawstructtree () =
args.draw_struct_tree <- true
let setextractfontfile s =
args.op <- Some (ExtractFontFile s)
let () = Cpdfdrawcontrol.getfontname := fun () -> args.fontname
let () = Cpdfdrawcontrol.getfontsize := fun () -> args.fontsize
let () = Cpdfdrawcontrol.setfontname := setfont
let () = Cpdfdrawcontrol.setfontsize := fun s -> args.fontsize <- s
let () = Cpdfdrawcontrol.getindent := fun () -> args.indent
let setlistimagesjson () =
setop ListImages ();
args.format_json <- true
let set_jbig2_global f =
jbig2_global := Some (Pdfio.bytes_of_string (contents_of_file f))
let clear_jbig2_global () =
jbig2_global := None
let setjpegquality q =
args.jpegquality <- q
let setjpegqualitylossless q =
args.jpegqualitylossless <- q
let setjpegtojpegscale q =
args.jpegtojpegscale <- q
let setjpegtojpegdpi q =
args.jpegtojpegdpi <- q
let set1bppmethod m =
args.onebppmethod <- m
let setpixelthreshold i =
args.pixel_threshold <- i
let setlengththreshold i =
args.length_threshold <- i
let setpercentagethreshold i =
args.percentage_threshold <- i
let setdpithreshold i =
args.dpi_threshold <- i
let setlosslessresample i =
args.resample_factor <- i
let setlosslessresampledpi i =
args.resample_factor <- -.i
let setresampleinterpolate () =
args.resample_interpolate <- true
let setjbig2_lossy_threshold f =
args.jbig2_lossy_threshold <- f
let setprocessimagesinfo () =
set Cpdfimage.debug_image_processing
let setextractstream s =
args.op <- Some (ExtractStream s)
let setextractstreamdecomp s =
args.op <- Some (ExtractStream s);
args.extract_stream_decompress <- true
let setprintobj s =
args.op <- Some (PrintObj s)
let setprintobjjson s =
args.format_json <- true;
args.op <- Some (PrintObj s)
let setreplaceobj s =
match String.split_on_char '=' s with
| [a; b] -> args.op <- Some (ReplaceObj (a, b))
| _ -> error "replace_obj: bad specification"
let expand_namespace = function
| "PDF" -> standard_namespace
| "PDF2" -> pdf2_namespace
| x -> x
let setreadableops () =
Pdfops.whitespace := "\n";
Pdfops.always_add_whitespace := true;
Pdfops.write_comments := true
let addeltinfo s =
match String.split_on_char '=' s with
| h::t ->
let pdfobj = pdf_or_json (String.concat "" t) in
Cpdfdrawcontrol.eltinfo h pdfobj
| [] -> error "addeltinfo: bad format"
let specs =
[("-version",
Arg.Unit (setop Version),
" Print the cpdf version number");
("-o",
Arg.String setout,
" Set the output file, if appropriate");
("-i",
Arg.String set_input,
" Add an input file");
("-png",
Arg.String set_input_png,
" Load from a PNG file, converting to PDF");
("-jpeg",
Arg.String set_input_jpeg,
" Load from a JPEG file, converting to PDF");
("-jpeg2000",
Arg.String set_input_jpeg2000,
" Load from a JPEG2000 file, converting to PDF");
("-jbig2",
Arg.String set_input_jbig2,
" Load from a JBIG2 fragment, converting to PDF");
("-jbig2-global",
Arg.String set_jbig2_global,
" Load a JBIG2 global stream");
("-jbig2-global-clear",
Arg.Unit clear_jbig2_global,
" Forget any JBIG2 global stream");
("-idir",
Arg.String set_input_dir,
" Add a directory of files");
("-idir-only-pdfs",
Arg.Unit setidironlypdfs,
" Have -idir ignore files not ending in .pdf");
("-pw",
Arg.String setdashpassword,
" Supply a password explicitly -pw=<password>");
("-stdin",
Arg.Unit setstdin,
" Read input from standard input");
("-stdin-owner",
Arg.String setstdinowner,
" Owner password for -stdin");
("-stdin-user",
Arg.String setstdinuser,
" User password for -stdin");
("-stdout",
Arg.Unit setstdout,
" Send result to standard output");
("-error-on-malformed",
Arg.Set Pdfread.error_on_malformed,
" Do not try to read malformed files");
("-range",
Arg.String setrange,
" Explicitly add a range");
("-collate",
Arg.Unit (fun () -> args.collate <- 1),
" Collate ranges when merging");
("-collate-n",
Arg.Int (fun n -> args.collate <- n),
" Collate ranges in multiples when merging");
("-revision",
Arg.Int setrevision,
"");
("-change-id",
Arg.Unit (setop ChangeId),
" Change the file's /ID tag");
("-no-preserve-objstm",
Arg.Unit (fun () -> args.preserve_objstm <- false),
" Don't preserve object streams");
("-create-objstm",
Arg.Unit (fun () -> args.create_objstm <- true),
" Create object streams anew");
("-keep-version",
Arg.Unit (fun () -> args.keepversion <- true),
" Don't change the version number");
("-l",
Arg.Unit (fun () -> args.linearize <- true),
" Linearize output file");
("-keep-l",
Arg.Unit (fun () -> args.keeplinearize <- true),
" Linearize if the input file was linearized");
("-cpdflin",
Arg.String setcpdflin,
" Set location of 'cpdflin'");
("-recrypt",
Arg.Unit setrecrypt,
" Keep this file's encryption when writing");
("-raw",
Arg.Unit (setencoding Cpdfmetadata.Raw),
" Do not process text");
("-stripped",
Arg.Unit (setencoding Cpdfmetadata.Stripped),
" Process text by simple stripping to ASCII");
("-utf8",
Arg.Unit (setencoding Cpdfmetadata.UTF8),
" Process text by conversion to UTF8 Unicode");
("-fast",
Arg.Unit setfast,
" Speed over correctness with malformed documents");
("-args",
Arg.Unit (fun () -> ()),
" Get arguments from a file.");
("-args-json",
Arg.Unit (fun () -> ()),
" Get arguments from a JSON file.");
("-merge",
Arg.Unit (setop Merge),
" Merge a number of files into one");
("-retain-numbering",
Arg.Unit set_retain_numbering,
" Don't renumber pages when merging");
("-merge-add-bookmarks",
Arg.Unit setmergeaddbookmarks,
" Add bookmarks for each file to merged file");
("-merge-add-bookmarks-use-titles",
Arg.Unit setmergeaddbookmarksusetitles,
" Use title of document rather than filename");
("-process-struct-trees",
Arg.Unit (fun () -> args.process_struct_trees <- true),
" Process structure trees");
("-remove-duplicate-fonts",
Arg.Unit set_remove_duplicate_fonts,
" Remove duplicate fonts when merging");
("-split",
Arg.Unit (setop Split),
" Split a file into individual pages");
("-chunk",
Arg.Int setchunk,
" Set chunk size for -split (default 1)");
("-split-bookmarks",
Arg.Int (fun i -> setop (SplitOnBookmarks i) ()),
" Split a file at bookmarks at a given level");
("-split-max",
Arg.String setsplitmax,
" Split a file to files of a given size");
("-spray",
Arg.Unit (setop Spray),
" Split a file by alternating pages");
("-scale-page",
Arg.String setscale,
" -scale-page \"sx sy\" scales by (sx, sy)");
("-scale-to-fit",
Arg.String setscaletofit,
" -scale-to-fit \"x y\" scales to page size (x, y)");
("-stretch",
Arg.String setstretch,
" -stretch \"x y\" scales without preserving aspect ratio");
("-center-to-fit",
Arg.String setcentertofit,
" -center-to-fit \"x y\" centers pages on page size (x, y)");
("-scale-contents",
Arg.Float setscalecontents,
" Scale contents by the given factor");
("-scale-to-fit-scale",
Arg.Float setscaletofitscale,
" -scale-to-fit-scale (1.0 = 100%)");
("-shift",
Arg.String setshift,
" -shift \"dx dy\" shifts the chosen pages");
("-shift-boxes",
Arg.String setshiftboxes,
" -shift-boxes \"dx dy\" shifts boxes on the chosen pages");
("-rotate",
Arg.Int setrotate,
" Set rotation of pages to 0, 90, 180, 270");
("-rotateby",
Arg.Int setrotateby,
" Rotate pages by 90, 180 or 270 degrees");
("-rotate-contents",
Arg.Float (fun f -> setop (RotateContents f) ()),
" Rotate contents of pages");
("-upright",
Arg.Unit (setop Upright),
" Make pages upright");
("-prerotate",
Arg.Unit (fun () -> args.prerotate <- true),
" Calls -upright on pages before modifying them, if required");
("-no-warn-rotate",
Arg.Unit setnowarnrotate,
" Do not warn on pages of PDFs which are not upright");
("-hflip",
Arg.Unit (setop HFlip),
" Flip pages horizontally");
("-vflip",
Arg.Unit (setop VFlip),
" Flip pages vertically");
("-crop",
Arg.String setcrop,
" Crop specified pages (synonym for -cropbox)");
("-cropbox",
Arg.String setcrop,
" Crop specified pages");
("-artbox",
Arg.String setart,
" Set art box for specified pages");
("-bleedbox",
Arg.String setbleed,
" Set bleed box for specified pages");
("-trimbox",
Arg.String settrim,
" Set trim box for specified pages");
("-hard-box",
Arg.String sethardbox,
" Hard crop specified pages to the given box");
("-show-boxes",
Arg.Unit (setop ShowBoxes),
" Show boxes by adding rectangles to pages");
("-trim-marks",
Arg.Unit (setop TrimMarks),
" Add trim marks");
("-remove-crop",
Arg.Unit (setop RemoveCrop),
" Remove cropping on specified pages");
("-remove-cropbox",
Arg.Unit (setop RemoveCrop),
" Synonym for -remove-crop");
("-remove-trimbox",
Arg.Unit (setop RemoveTrim),
" Remove trim box on specified pages");
("-remove-bleedbox",
Arg.Unit (setop RemoveBleed),
" Remove bleed box on specified pages");
("-remove-artbox",
Arg.Unit (setop RemoveArt),
" Remove art box on specified pages");
("-frombox", Arg.String setfrombox, " Set box to copy from");
("-tobox", Arg.String settobox, " Set box to copy to");
("-mediabox-if-missing",
Arg.Unit setmediaboxifmissing,
" If copy from box missing, substitute media box");
("-mediabox",
Arg.String setmediabox,
" Set media box on specified pages");
("-encrypt",
Arg.Unit setencryptcollect,
" Encrypt a document");
("-decrypt",
Arg.Unit (setop Decrypt),
" Decrypt a file");
("-decrypt-force",
Arg.Unit (fun () -> args.debugforce <- true),
" Decrypt a file even without password");
("-no-edit", Arg.Unit (fun () -> args.no_edit <- true) , " No edits");
("-no-print", Arg.Unit (fun () -> args.no_print <- true), " No printing");
("-no-copy", Arg.Unit (fun () -> args.no_copy <- true), " No copying");
("-no-annot", Arg.Unit (fun () -> args.no_annot <- true), " No annotations");
("-no-forms", Arg.Unit (fun () -> args.no_forms <- true), " No forms");
("-no-extract", Arg.Unit (fun () -> args.no_extract <- true), " No extracting");
("-no-assemble", Arg.Unit (fun () -> args.no_assemble <- true), " No assembling");
("-no-hq-print", Arg.Unit (fun () -> args.no_hq_print <- true), " No high quality printing");
("-no-encrypt-metadata",
Arg.Unit set_no_encrypt_metadata,
" Don't encrypt metadata (AES only)");
("-decompress",
Arg.Unit (setop Decompress),
" Decompress");
("-compress",
Arg.Unit (setop Compress),
" Compress streams, leaving metadata alone");
("-remove-duplicate-streams",
Arg.Unit (fun () -> args.remove_duplicate_streams <- true),
"");
("-list-bookmarks",
Arg.Unit (setop ListBookmarks),
" List Bookmarks");
("-list-bookmarks-json",
Arg.Unit setlistbookmarksjson,
" List Bookmarks in JSON format");
("-preserve-actions",
Arg.Unit (fun () -> args.preserve_actions <- true),
" Preserve actions when listing bookmarks");
("-remove-bookmarks",
Arg.Unit (setop RemoveBookmarks),
" Remove bookmarks from a file");
("-add-bookmarks",
Arg.String setaddbookmarks,
" Add bookmarks from the given file");
("-add-bookmarks-json",
Arg.String setaddbookmarksjson,
" Add bookmarks from the given file in JSON format");
("-bookmarks-open-to-level",
Arg.Int setbookmarksopentolevel,
" Open bookmarks to this level (0 = all closed)");
("-presentation",
Arg.Unit (setop Presentation),
" Make a presentation");
("-trans",
Arg.String settrans,
" Set the transition method for -presentation");
("-duration",
Arg.Float setduration,
" Set the display duration for -presentation");
("-vertical",
Arg.Unit setvertical,
" Set dimension for Split and Blinds styles");
("-outward",
Arg.Unit setoutward,
" Set direction for Split and Box styles");
("-direction",
Arg.Int setdirection,
" Set direction for Wipe and Glitter styles");
("-effect-duration",
Arg.Float seteffectduration,
" Set the effect duration in seconds");
("-stamp-on",
Arg.String setstampon,
" Stamp a file on some pages of another");
("-stamp-under",
Arg.String setstampunder,
" Stamp a file under some pages of another");
("-scale-stamp-to-fit",
Arg.Unit (fun () -> args.scale_stamp_to_fit <- true),
" Scale the stamp to fit the page");
("-combine-pages",
Arg.String setcombinepages,
" Combine two files by merging individual pages");
("-add-text",
Arg.String setaddtext,
" Superimpose text on the given range of pages");
("-remove-text",
Arg.Unit (setop RemoveText),
" Remove text previously added by cpdf");
("-add-rectangle",
Arg.String setrectangle,
" Add a rectangle to the page");
("-bates",
Arg.Int (fun n -> args.bates <- n),
" Set the base bates number");
("-bates-at-range",
Arg.Int setbatesrange,
" Set the base bates number at first page in range");
("-bates-pad-to",
Arg.Int (fun n -> args.batespad <- Some n),
" Pad the bates number with leading zeroes to width");
("-font",
Arg.String setfont,
" Set the font");
("-font-size",
Arg.String setfontsize,
" Set the font size");
("-load-ttf",
Arg.String loadttf,
" Use a TrueType font");
("-embed-std14",
Arg.String setembedstd14,
" Embed standard 14 fonts");
("-color",
Arg.String setcolor,
" Set the color");
("-opacity",
Arg.Float setopacity,
" Set the text opacity");
("-outline",
Arg.Unit (fun () -> args.outline <- true),
" Use outline mode for text");
("-linewidth",
Arg.String setlinewidth,
" Set line width for outline text");
("-pos-center",
Arg.String setposcenter,
" Set position relative to center of baseline");
("-pos-left",
Arg.String setposleft,
" Set position relative to left of baseline");
("-pos-right",
Arg.String setposright,
" Set position relative to right of baseline");
("-top",
Arg.String settop,
" Set position relative to center top of page");
("-topleft",
Arg.String settopleft,
" Set position relative to top left of page");
("-topright",
Arg.String settopright,
" Set position relative to top right of page");
("-left",
Arg.String setleft,
" Set position relative to center left of page");
("-bottomleft",
Arg.String setbottomleft,
" Set position relative to bottom left of page");
("-bottom",
Arg.String setbottom,
" Set position relative to center bottom of page");
("-bottomright",
Arg.String setbottomright,
" Set position relative to bottom right of page");
("-right",
Arg.String setright,
" Set position relative to center right of page");
("-diagonal",
Arg.Unit setdiagonal,
" Place text diagonally across page");
("-reverse-diagonal",
Arg.Unit setreversediagonal,
" Place text diagonally across page from top left");
("-center",
Arg.Unit setcenter,
" Place text in the center of the page");
("-justify-left",
Arg.Unit (fun () -> args.justification <- Cpdfaddtext.LeftJustify),
" Justify multiline text left");
("-justify-right",
Arg.Unit (fun () -> args.justification <- Cpdfaddtext.RightJustify),
" Justify multiline text right");
("-justify-center",
Arg.Unit (fun () -> args.justification <- Cpdfaddtext.CentreJustify),
" Justify multiline text center");
("-underneath",
Arg.Unit (fun () -> args.underneath <- true),
" Text stamp is underneath content");
("-line-spacing",
Arg.Float (fun f -> args.linespacing <- f),
" Line spacing (1 is normal)");
("-midline",
Arg.Unit (fun () -> args.midline <- true),
" Adjust text to midline rather than baseline");
("-topline",
Arg.Unit (fun () -> args.topline <- true),
" Adjust text to topline rather than baseline");
("-relative-to-cropbox",
Arg.Unit (fun () -> args.relative_to_cropbox <- true),
" Add text relative to Crop Box not Media Box");
("-embed-missing-fonts",
Arg.Unit (setop EmbedMissingFonts),
" Embed missing fonts by calling gs");
("-twoup",
Arg.Unit (setop TwoUp),
" Put 2 pages onto one");
("-twoup-stack",
Arg.Unit (setop TwoUpStack),
" Stack 2 pages onto one twice the size");
("-impose",
Arg.String setimpose,
" Impose onto given page size");
("-impose-xy",
Arg.String setimposexy,
" Impose x by y (zero means unlimited)");
("-impose-columns",
Arg.Unit (fun () -> args.impose_columns <- true),
" Impose in columns rather than rows");
("-impose-rtl",
Arg.Unit (fun () -> args.impose_rtl <- true),
" Impose right-to-left");
("-impose-btt",
Arg.Unit (fun () -> args.impose_btt <- true),
" Impose bottom-to-top");
("-impose-margin",
Arg.String setimposemargin,
" Add margin around whole imposed page");
("-impose-spacing",
Arg.String setimposespacing,
" Add spacing around each imposed page");
("-impose-linewidth",
Arg.String setimposelinewidth,
" Imposition divider line width (0=none)");
("-chop",
Arg.String setchop,
" Chop x by y");
("-chop-h",
Arg.String setchoph,
" Chop horizontally");
("-chop-v",
Arg.String setchopv,
" Chop horizontally");
("-chop-columns",
Arg.Unit (fun () -> args.impose_columns <- true),
" Chop in columns rather than rows");
("-chop-rtl",
Arg.Unit (fun () -> args.impose_rtl <- true),
" Chop right-to-left");
("-chop-btt",
Arg.Unit (fun () -> args.impose_btt <- true),
" Chop bottom-to-top");
("-pad-before",
Arg.Unit (setop PadBefore),
" Add a blank page before the given pages");
("-pad-after",
Arg.Unit (setop PadAfter),
" Add a blank page after the given pages");
("-pad-every",
Arg.Int setpadevery,
" Add a blank page after every n pages");
("-pad-with",
Arg.String setpadwith,
" Use a given PDF instead of a blank page");
("-pad-multiple",
Arg.Int setpadmultiple,
" Pad the document to a multiple of n pages");
("-pad-multiple-before",
Arg.Int setpadmultiplebefore,
" Pad the document at beginning to a multiple of n pages");
("-list-annotations",
Arg.Unit (setop ListAnnotations),
" List annotations");
("-list-annotations-json",
Arg.Unit setlistannotationsjson,
" List annotations in JSON format");
("-copy-annotations",
Arg.String setcopyannotations,
" Copy annotations from given file");
("-remove-annotations",
Arg.Unit (setop RemoveAnnotations),
" Remove annotations");
("-set-annotations",
Arg.String setsetannotations,
" Set annotations from JSON file");
("-list-fonts",
Arg.Unit (setop Fonts),
" Output font list");
("-list-fonts-json",
Arg.Unit setlistfontsjson,
" Output font list in JSON format");
("-info",
Arg.Unit (setop Info),
" Output file information");
("-info-json",
Arg.Unit setinfojson,
" Output file information in JSON format");
("-page-info",
Arg.Unit (setop PageInfo),
" Output page information");
("-page-info-json",
Arg.Unit setpageinfojson,
" Output page information in JSON format");
("-set-author",
Arg.String (fun s -> setop (SetAuthor s) ()),
" Set Author");
("-set-title",
Arg.String (fun s -> setop (SetTitle s) ()),
" Set Title");
("-set-subject",
Arg.String (fun s -> setop (SetSubject s) ()),
" Set Subject");
("-set-keywords",
Arg.String (fun s -> setop (SetKeywords s) ()),
" Set Keywords");
("-set-create",
Arg.String (fun s -> setop (SetCreate s) ()),
" Set Creation date");
("-set-modify",
Arg.String (fun s -> setop (SetModify s) ()),
" Set Modification date");
("-set-creator",
Arg.String (fun s -> setop (SetCreator s) ()),
" Set Creator");
("-set-producer",
Arg.String (fun s -> setop (SetProducer s) ()),
" Set Producer");
("-set-trapped",
Arg.Unit (setop SetTrapped),
" Mark as trapped");
("-set-untrapped",
Arg.Unit (setop SetUntrapped),
" Mark as not trapped");
("-also-set-xmp",
Arg.Unit setalsosetxml,
" Also set XMP metadata");
("-just-set-xmp",
Arg.Unit setjustsetxml,
" Just set XMP metadata, not old-fashioned metadata");
("-create-metadata",
Arg.Unit (setop CreateMetadata),
" Create XMP metadata from scratch.");
("-set-page-layout",
Arg.String (fun s -> setop (SetPageLayout s) ()),
" Set page layout upon document opening");
("-set-page-mode",
Arg.String (fun s -> setop (SetPageMode s) ()),
" Set page mode upon document opening");
("-set-non-full-screen-page-mode",
Arg.String (fun s -> setop (SetNonFullScreenPageMode s) ()),
" Set non full screen page mode if page mode is FullScreen");
("-open-at-page",
Arg.String setopenatpage,
" Set initial page");
("-open-at-page-fit",
Arg.String setopenatpagefit,
" Set initial page, scaling to fit");
("-open-at-page-custom",
Arg.String setopenatpagecustom,
" Set initial page, with custom scaling");
("-set-metadata",
Arg.String (fun s -> setop (SetMetadata s) ()),
" Set metadata to the contents of a file");
("-print-metadata",
Arg.Unit (setop Metadata),
" Output metadata information");
("-remove-metadata",
Arg.Unit (setop RemoveMetadata),
" Remove document metadata");
("-set-metadata-date",
Arg.String setsetmetadatadate,
" Set the XMP metadata date property");
("-hide-toolbar",
Arg.String hidetoolbar,
" Hide the viewer's toolbar");
("-hide-menubar",
Arg.String hidemenubar,
" Hide the viewer's menubar");
("-hide-window-ui",
Arg.String hidewindowui,
" Hide the viewer's scroll bars etc.");
("-fit-window",
Arg.String fitwindow,
" Resize document's window to fit size of page");
("-center-window",
Arg.String centerwindow,
" Position window in the center of screen");
("-display-doc-title",
Arg.String displaydoctitle,
" Display document's title in the title bar");
("-set-language",
Arg.String (fun s -> setop (SetLanguage s) ()),
" Set the document's language");
("-pages",
Arg.Unit (setop CountPages),
" Count pages");
("-list-attached-files",
Arg.Unit (setop ListAttachedFiles),
" List attached files");
("-dump-attachments",
Arg.Unit (setop DumpAttachedFiles),
" Dump attachments to disk");
("-attach-file",
Arg.String setattachfile,
" Attach a file");
("-to-page",
Arg.String settopage,
" Attach file to given page instead of document");
("-remove-files",
Arg.Unit (setop RemoveAttachedFiles),
" Remove embedded attached document-level files");
("-list-images",
Arg.Unit (setop ListImages),
" List images");
("-list-images-json",
Arg.Unit setlistimagesjson,
" List images in JSON format");
("-list-images-used",
Arg.Unit (fun () -> setop (ImageResolution max_float) ()),
" List images at point of use");
("-list-images-used-json",
Arg.Unit (fun () -> args.format_json <- true; setop (ImageResolution max_float) ()),
" List images at point of use in JSON format");
("-image-resolution",
Arg.Float setimageresolution,
" List images at point of use under a given dpi");
("-image-resolution-json",
Arg.Float (fun f -> setimageresolution f; args.format_json <- true),
" List images at point of use under a given dpi");
("-copy-font",
Arg.String setcopyfont,
" Copy a named font");
("-copy-font-page",
Arg.Int setfontpage,
" Set the page a copied font is drawn from");
("-copy-font-name",
Arg.String setcopyfontname,
" Set the name of the font to copy");
("-remove-fonts",
Arg.Unit (setop RemoveFonts),
" Remove embedded fonts");
("-missing-fonts",
Arg.Unit (setop MissingFonts),
" List missing fonts");
("-remove-id",
Arg.Unit (setop RemoveId),
" Remove the file's /ID tag");
("-draft",
Arg.Unit (setop Draft),
" Remove images from the file");
("-draft-remove-only",
Arg.String (fun s -> args.removeonly <- Some s),
" Only remove named image");
("-boxes",
Arg.Unit setboxes,
" Add crossed boxes to -draft option");
("-remove-all-text",
Arg.Unit (setop RemoveAllText),
" Remove all text");
("-blacktext",
Arg.Unit (setop BlackText),
" Blacken document text");
("-blacklines",
Arg.Unit (setop BlackLines),
" Blacken lines in document");
("-blackfills",
Arg.Unit (setop BlackFills),
" Blacken fills in document");
("-thinlines",
Arg.String setthinlines,
" Set minimum line thickness to the given width");
("-remove-clipping",
Arg.Unit (setop RemoveClipping),
" Remove clipping paths");
("-clean",
Arg.Unit (setop Clean),
" Garbage-collect a file");
("-set-version",
Arg.Int (fun i -> setop (SetVersion i) ()),
" Set PDF version number");
("-copy-id-from",
Arg.String setcopyid,
" Copy one file's ID tag to another");
("-print-page-labels",
Arg.Unit (setop PrintPageLabels),
" Print page labels");
("-print-page-labels-json",
Arg.Unit setprintpagelabelsjson,
" Print page labels in JSON format");
("-remove-page-labels",
Arg.Unit (setop RemovePageLabels),
" Remove page labels");
("-add-page-labels",
Arg.Unit (setop AddPageLabels),
" Add or replace page labels");
("-label-style",
Arg.String setlabelstyle,
" Set label style (default DecimalArabic)");
("-label-prefix",
Arg.String setlabelprefix,
" Set label prefix (default none)");
("-label-startval",
Arg.Int setlabelstartval,
" Set label start value (default 1)");
("-labels-progress",
Arg.Unit setlabelsprogress,
" Label start value progresses with multiple ranges");
("-remove-dict-entry",
Arg.String setremovedictentry,
" Remove an entry from all dictionaries");
("-replace-dict-entry",
Arg.String setreplacedictentry,
" Remove an entry from all dictionaries");
("-replace-dict-entry-value",
Arg.String setreplacedictentryvalue,
" Replacement value for -replace-dict-entry");
("-dict-entry-search",
Arg.String setdictentrysearch,
" Search string for -remove-dict-entry and -replace-dict-entry");
("-print-dict-entry",
Arg.String setprintdictentry,
" Print dictionary values of a given key");
("-producer",
Arg.String setproduceraswego,
" Change the /Producer entry in the /Info dictionary");
("-creator",
Arg.String setcreatoraswego,
" Change the /Creator entry in the /Info dictionary");
("-list-spot-colors",
Arg.Unit (setop ListSpotColours),
" List spot colors");
("-create-pdf",
Arg.Unit (setop CreatePDF),
" Create a new PDF");
("-create-pdf-ua-1",
Arg.String (fun s -> args.subformat <- Some Cpdfua.PDFUA1; args.title <- Some s; setop CreatePDF ()),
" Create a new PDF/UA-1 with the given title");
("-create-pdf-ua-2",
Arg.String (fun s -> args.subformat <- Some Cpdfua.PDFUA2; args.title <- Some s; setop CreatePDF ()),
" Create a new PDF/UA-2 with the given title");
("-create-pdf-pages",
Arg.Int setcreatepdfpages,
" Number of pages for new PDF");
("-create-pdf-papersize",
Arg.String setcreatepdfpapersize,
" Paper size for new PDF");
("-prepend-content",
Arg.String setprepend,
" Prepend content to page");
("-postpend-content",
Arg.String setpostpend,
" Postpend content to page");
("-gs",
Arg.String (fun s -> args.path_to_ghostscript <- s),
" Path to gs executable");
("-gs-malformed",
Arg.Unit setgsmalformed,
" Also try to reconstruct malformed files with gs");
("-gs-quiet",
Arg.Unit (fun () -> args.gs_quiet <- true),
" Make gs go into quiet mode");
("-gs-malformed-force",
Arg.Unit whingemalformed,
" See manual for usage.");
("-im",
Arg.String setimpath,
" Path to magick executable");
("-p2p",
Arg.String setp2ppath,
" Path to pnmtopng executable");
("-extract-images",
Arg.Unit (setop ExtractImages),
" Extract images to file");
("-dedup",
Arg.Unit (fun () -> args.dedup <- true),
" Deduplicate extracted images fully");
("-dedup-perpage",
Arg.Unit (fun () -> args.dedup_per_page <- true),
" Deduplicate extracted images per page only");
("-process-images",
Arg.Unit (setop ProcessImages),
" Process images within PDF");
("-process-images-info",
Arg.Unit setprocessimagesinfo,
" Show info when processing images");
("-jbig2enc",
Arg.String setjbig2encpath,
" Path to jbig2enc executable");
("-jpeg-to-jpeg",
Arg.Float setjpegquality,
" Set JPEG quality for existing JPEGs");
("-jpeg-to-jpeg-scale",
Arg.Float setjpegtojpegscale,
" Set the percentage scale for -jpeg-to-jpeg");
("-jpeg-to-jpeg-dpi",
Arg.Float setjpegtojpegdpi,
" Set the DPI target for -jpeg-to-jpeg");
("-lossless-to-jpeg",
Arg.Float setjpegqualitylossless,
" Set JPEG quality for existing lossless images");
("-1bpp-method",
Arg.String set1bppmethod,
" Set 1bpp compression method for existing images");
("-jbig2-lossy-threshold",
Arg.Float setjbig2_lossy_threshold,
" Set jbig2enc lossy threshold");
("-pixel-threshold",
Arg.Int setpixelthreshold,
" Only process images with more pixels than this");
("-length-threshold",
Arg.Int setlengththreshold,
" Only process images with data longer than this");
("-percentage-threshold",
Arg.Float setpercentagethreshold,
" Only substitute lossy image when smaller than this");
("-dpi-threshold",
Arg.Float setdpithreshold,
" Only process image when always higher than this dpi");
("-lossless-resample",
Arg.Float setlosslessresample,
" Resample lossless images to given part of original");
("-lossless-resample-dpi",
Arg.Float setlosslessresampledpi,
" Resample lossless images to given DPI");
("-resample-interpolate",
Arg.Unit setresampleinterpolate,
" Interpolate when resampling");
("-squeeze",
Arg.Unit setsqueeze,
" Squeeze");
("-squeeze-log-to",
Arg.String setsqueezelogto,
" Squeeze log location");
("-squeeze-no-pagedata",
Arg.Unit (fun () -> args.squeeze_pagedata <- false),
" Don't recompress pages");
("-squeeze-no-recompress",
Arg.Unit (fun () -> args.squeeze_recompress <- false),
" Don't recompress streams");
("-output-json",
Arg.Unit (setop OutputJSON),
" Export PDF file as JSON data");
("-output-json-parse-content-streams",
Arg.Unit (fun () -> args.jsonparsecontentstreams <- true),
" Parse content streams");
("-output-json-no-stream-data",
Arg.Unit (fun () -> args.jsonnostreamdata <- true),
" Skip stream data for brevity");
("-output-json-decompress-streams",
Arg.Unit (fun () -> args.jsondecompressstreams <- true),
" Skip stream data for brevity");
("-output-json-clean-strings",
Arg.Unit (fun () -> args.jsoncleanstrings <- true),
" Convert UTF16BE strings to PDFDocEncoding when possible");
("-j",
Arg.String set_json_input,
" Load a PDF JSON file");
("-ocg-list",
Arg.Unit (setop OCGList),
" List optional content groups");
("-ocg-rename",
Arg.Unit (setop OCGRename),
" Rename optional content group");
("-ocg-rename-from",
Arg.String (fun s -> args.ocgrenamefrom <- s),
" Rename from (with -ocg-rename)");
("-ocg-rename-to",
Arg.String (fun s -> args.ocgrenameto <- s),
" Rename to (with -ocg-rename)");
("-ocg-order-all",
Arg.Unit (setop OCGOrderAll),
" Repair /Order so all OCGs listed ");
("-ocg-coalesce-on-name",
Arg.Unit (setop OCGCoalesce),
" Coalesce OCGs with like name");
("-stamp-as-xobject",
Arg.String setstampasxobject,
" Stamp a file as a form xobject in another");
("-print-font-table",
Arg.String setprintfontencoding,
" Print the /ToUnicode table for a given font, if present.");
("-print-font-table-page",
Arg.Int setfontpage,
" Set page for -print-font-table");
("-extract-font",
Arg.String setextractfontfile,
" Extract a font");
("-table-of-contents",
Arg.Unit (setop TableOfContents),
" Typeset a table of contents from bookmarks");
("-toc-title",
Arg.String settableofcontentstitle,
" Set (or clear if empty) the TOC title");
("-toc-no-bookmark",
Arg.Unit settocnobookmark,
" Don't add the table of contents to the bookmarks");
("-toc-dot-leaders",
Arg.Unit (fun () -> args.dot_leader <- true),
" Add a dot leader to TOC entries");
("-typeset",
Arg.String settypeset,
" Typeset a text file as a PDF");
("-subformat",
Arg.String setsubformat,
" Set subformat");
("-title",
Arg.String (fun s -> args.title <- Some s),
" Set PDF/UA title");
("-composition",
Arg.Unit (setop (Composition false)),
" Show composition of PDF");
("-composition-json",
Arg.Unit (setop (Composition true)),
" Show composition of PDF in JSON format");
("-text-width",
Arg.String settextwidth,
" Find width of a line of text");
("-draw", Arg.Unit setdraw, " Begin drawing");
("-draw-struct-tree", Arg.Unit setdrawstructtree, " Build structure trees when drawing.");
("-tag", Arg.String Cpdfdrawcontrol.addtag, " Begin structure item");
("-stag", Arg.String Cpdfdrawcontrol.addstag, " Begin struture branch");
("-end-tag", Arg.Unit Cpdfdrawcontrol.endtag, " End structure item");
("-end-stag", Arg.Unit Cpdfdrawcontrol.endstag, " End structure branch");
("-auto-tags", Arg.Unit (fun _ -> Cpdfdrawcontrol.autotags true), " Auto-tag paragraphs and figures");
("-no-auto-tags", Arg.Unit (fun _ -> Cpdfdrawcontrol.autotags false), " Don't auto-tag paragraphs and figures");
("-artifact", Arg.Unit (fun _ -> Cpdfdrawcontrol.artifact ()), " Begin an artifact");
("-end-artifact", Arg.Unit (fun _ -> Cpdfdrawcontrol.endartifact ()), "End an artifact");
("-no-auto-artifacts", Arg.Unit (fun _ -> Cpdfdrawcontrol.autoartifacts false), " Don't mark untagged content as artifacts");
("-eltinfo", Arg.String addeltinfo, " Add element information");
("-end-eltinfo", Arg.String (fun s -> Cpdfdrawcontrol.endeltinfo s), " Erase element information");
("-namespace", Arg.String (fun s -> Cpdfdrawcontrol.addnamespace (expand_namespace s)), " Set the structure tree namespace");
("-rolemap", Arg.String (fun s -> Cpdfdrawcontrol.setrolemap s), " Set a role map");
("-rect", Arg.String Cpdfdrawcontrol.addrect, " Draw rectangle");
("-to", Arg.String Cpdfdrawcontrol.addto, " Move to");
("-line", Arg.String Cpdfdrawcontrol.addline, " Add line to");
("-bez", Arg.String Cpdfdrawcontrol.addbezier, " Add Bezier curve to path");
("-bez23", Arg.String Cpdfdrawcontrol.addbezier23, " Add Bezier v-op to path");
("-bez13", Arg.String Cpdfdrawcontrol.addbezier13, " Add Bezier y-op to path");
("-circle", Arg.String Cpdfdrawcontrol.addcircle, " Add circle to path");
("-strokecol", Arg.String Cpdfdrawcontrol.setstroke, " Set stroke colour");
("-fillcol", Arg.String Cpdfdrawcontrol.setfill, " Set fill colour");
("-stroke", Arg.Unit Cpdfdrawcontrol.stroke, " Stroke path");
("-fill", Arg.Unit Cpdfdrawcontrol.fill, " Fill path");
("-filleo", Arg.Unit Cpdfdrawcontrol.fillevenodd, " Fill path, even odd");
("-strokefill", Arg.Unit Cpdfdrawcontrol.strokefill, " Stroke and fill path");
("-strokefilleo", Arg.Unit Cpdfdrawcontrol.strokefillevenodd, " Stroke and fill path, even odd");
("-clip", Arg.Unit Cpdfdrawcontrol.clip, " Clip");
("-clipeo", Arg.Unit Cpdfdrawcontrol.clipevenodd, " Clip, even odd");
("-close", Arg.Unit Cpdfdrawcontrol.closepath, " Close path");
("-thick", Arg.String Cpdfdrawcontrol.setthickness, " Set stroke thickness");
("-cap", Arg.String Cpdfdrawcontrol.setcap, " Set cap");
("-join", Arg.String Cpdfdrawcontrol.setjoin, " Set join");
("-miter", Arg.String Cpdfdrawcontrol.setmiter, " Set miter limit");
("-dash", Arg.String Cpdfdrawcontrol.setdash, " Set dash pattern");
("-push", Arg.Unit Cpdfdrawcontrol.push, " Push graphics stack");
("-pop", Arg.Unit Cpdfdrawcontrol.pop, " Pop graphics stack");
("-matrix", Arg.String Cpdfdrawcontrol.setmatrix, " Append to graphics matrix");
("-mtrans", Arg.String Cpdfdrawcontrol.setmtranslate, " Translate the graphics matrix");
("-mrot", Arg.String Cpdfdrawcontrol.setmrotate, " Rotate the graphics matrix");
("-mscale", Arg.String Cpdfdrawcontrol.setmscale, " Scale the graphics matrix");
("-mshearx", Arg.String Cpdfdrawcontrol.setmshearx, " Shear the graphics matrix in X");
("-msheary", Arg.String Cpdfdrawcontrol.setmsheary, " Shear the graphics matrix in Y");
("-xobj-bbox", Arg.String Cpdfdrawcontrol.xobjbbox, " Specify the bounding box for xobjects");
("-xobj", Arg.String Cpdfdrawcontrol.startxobj, " Begin saving a sequence of graphics operators");
("-end-xobj", Arg.Unit Cpdfdrawcontrol.endxobj, " End saving a sequence of graphics operators");
("-use", Arg.String Cpdfdrawcontrol.usexobj, " Use a saved sequence of graphics operators");
("-draw-jpeg", Arg.String Cpdfdrawcontrol.addjpeg, " Load a JPEG from file and name it");
("-draw-png", Arg.String Cpdfdrawcontrol.addpng, " Load a PNG from file and name it");
("-image", Arg.String (fun s -> Cpdfdrawcontrol.addimage s), " Draw an image which has already been loaded");
("-fill-opacity", Arg.Float Cpdfdrawcontrol.addopacity, " Set opacity");
("-stroke-opacity", Arg.Float Cpdfdrawcontrol.addsopacity, " Set stroke opacity");
("-bt", Arg.Unit Cpdfdrawcontrol.addbt, " Begin text");
("-et", Arg.Unit Cpdfdrawcontrol.addet, " End text");
("-text", Arg.String Cpdfdrawcontrol.addtext, " Draw text");
("-stext", Arg.String Cpdfdrawcontrol.addspecialtext, " Draw text with %specials");
("-para", Arg.String Cpdfdrawcontrol.addpara, " Add a paragraph of text");
("-paras", Arg.String Cpdfdrawcontrol.addparas, " Add paragraphs of text, splitting on newlines");
("-indent", Arg.Float (fun f -> args.indent <- Some f), " Set indent for paragraphs");
("-leading", Arg.String setleading, " Set leading");
("-charspace", Arg.String setcharspace, " Set character spacing");
("-wordspace", Arg.String setwordspace, " Set word space");
("-textscale", Arg.Float (fun f -> Cpdfdrawcontrol.addop (Cpdfdraw.TextScale f)), " Set text scale");
("-rendermode", Arg.Int (fun i -> Cpdfdrawcontrol.addop (Cpdfdraw.RenderMode i)), " Set text rendering mode");
("-rise", Arg.String setrise, " Set text rise");
("-nl", Arg.Unit (fun () -> Cpdfdrawcontrol.addop Cpdfdraw.Newline), " New line");
("-newpage", Arg.Unit Cpdfdrawcontrol.addnewpage, " Move to a fresh page");
("-extract-stream", Arg.String setextractstream, " Extract a stream");
("-extract-stream-decompress", Arg.String setextractstreamdecomp, " Extract a stream, decompressing");
("-replace-stream", Arg.String (fun s -> args.op <- Some (ReplaceStream s)), " Replace a stream");
("-replace-stream-with", Arg.String (fun s -> args.replace_stream_with <- s), " File to replace stream with");
("-obj", Arg.String setprintobj, " Print object");
("-obj-json", Arg.String setprintobjjson, " Print object in JSON format");
("-replace-obj", Arg.String setreplaceobj, " Replace object");
("-remove-obj", Arg.String (fun s -> setop (RemoveObj s) ()), " Remove object");
("-json", Arg.Unit (fun () -> args.format_json <- true), " Format output as JSON");
("-verify", Arg.String (fun s -> setop (Verify s) ()), " Verify conformance to a standard");
("-verify-single", Arg.String (fun s -> args.verify_single <- Some s), " Verify a single test");
("-mark-as", Arg.String (fun s -> setop (MarkAs (Cpdfua.subformat_of_string s)) ()), " Mark as conforming to a standard");
("-remove-mark", Arg.String (fun s -> setop (RemoveMark (Cpdfua.subformat_of_string s)) ()), " Remove conformance mark");
("-print-struct-tree", Arg.Unit (fun () -> setop PrintStructTree ()), " Print structure tree");
("-extract-struct-tree", Arg.Unit (fun () -> setop ExtractStructTree ()), " Extract structure tree in JSON format");
("-replace-struct-tree", Arg.String (fun s -> setop (ReplaceStructTree s) ()), " Replace structure tree from JSON");
("-remove-struct-tree", Arg.Unit (fun () -> setop RemoveStructTree ()), " Remove entire structure tree");
("-mark-as-artifact", Arg.Unit (fun () -> setop MarkAsArtifact ()), " Mark whole file as artifact");
("-redact", Arg.Unit (fun () -> setop Redact ()), " Redact entire pages");
("-rasterize", Arg.Unit (fun () -> setop Rasterize ()), " Rasterize pages");
("-rasterize-gray", Arg.Unit (fun () -> args.rast_device <- "pnggray"), " Rasterize in grayscale");
("-rasterize-1bpp", Arg.Unit (fun () -> args.rast_device <- "pngmono"), " Rasterize in monochrome");
("-rasterize-jpeg", Arg.Unit (fun () -> args.rast_device <- "jpeg"), " Rasterize as JPEG");
("-rasterize-jpeg-gray", Arg.Unit (fun () -> args.rast_device <- "jpeggray"), " Rasterize as JPEG in grayscale");
("-rasterize-res", Arg.Float (fun f -> args.rast_res <- f), " Rastierization resolution");
("-rasterize-annots", Arg.Unit (fun () -> args.rast_annots <- true), " Rasterize annotations");
("-rasterize-no-antialias", Arg.Unit (fun () -> args.rast_antialias <- false), " Don't antialias when rasterizing");
("-rasterize-downsample", Arg.Unit (fun () -> args.rast_downsample <- true), " Antialias by downsampling");
("-rasterize-jpeg-quality", Arg.Int (fun i -> args.rast_jpeg_quality <- i), " Set JPEG quality");
("-output-image", Arg.Unit (fun () -> args.op <- Some OutputImage), " Output pages as images");
("-in", Arg.Unit (fun () -> args.output_unit <- Pdfunits.Inch), " Output dimensions in inches");
("-cm", Arg.Unit (fun () -> args.output_unit <- Pdfunits.Centimetre), " Output dimensions in centimetres");
("-mm", Arg.Unit (fun () -> args.output_unit <- Pdfunits.Millimetre), " Output dimensions in millimetres");
(* These items are undocumented *)
("-debug", Arg.Unit setdebug, "");
("-debug-crypt", Arg.Unit (fun () -> args.debugcrypt <- true), "");
("-debug-force", Arg.Unit (fun () -> args.debugforce <- true), "");
("-debug-malformed", Arg.Set Pdfread.debug_always_treat_malformed, "");
("-debug-stderr-to-stdout", Arg.Unit setstderrtostdout, "");
("-debug-readable-ops", Arg.Unit setreadableops, "");
("-stay-on-error", Arg.Unit setstayonerror, "");
(* These items are unfinished *)
("-extract-text", Arg.Unit (setop ExtractText), "");
("-extract-text-font-size", Arg.Float setextracttextfontsize, "");
]
and usage_msg =
"Syntax: cpdf [<operation>] <input files> [-o <output file>]\n\n\
Copyright Coherent Graphics Ltd.\n\n\
Version " ^ (if agpl then "AGPLv3-licensed " else "") ^ string_of_int major_version ^ "." ^ string_of_int minor_version ^ "." ^ (if minor_minor_version = 0 then "" else string_of_int minor_minor_version) ^ " " ^ version_date ^ "\n\n\
https://www.coherentpdf.com/\n\n\
Input names are distinguished by containing a '.' and may be\n\
followed by a page range specification, for instance \"1,2,3\"\n\
or \"1-6,9-end\" or \"even\" or \"odd\" or \"reverse\".\n\nOperations (See \
manual for full details):\n"
(* Reading and writing *)
let filesize name =
try
let x = open_in_bin name in
let r = in_channel_length x in
close_in x;
r
with
_ -> 0
(* Mend PDF file with Ghostscript. We use this if a file is malformed and CPDF
* cannot mend it. It is copied to a temporary file, fixed, then we return None or Some (pdf). *)
let mend_pdf_file_with_ghostscript filename =
match args.path_to_ghostscript with
| "" ->
Pdfe.log "Please supply path to gs with -gs\n";
exit 2
| _ ->
Pdfe.log "CPDF could not mend. Attempting to mend file with gs\n";
let tmpout = Filename.temp_file "cpdf" ".pdf" in
tempfiles := tmpout::!tempfiles;
let gscall =
Filename.quote_command args.path_to_ghostscript
((if args.gs_quiet then ["-dQUIET"] else []) @
["-dNOPAUSE"; "-sDEVICE=pdfwrite"; "-sOUTPUTFILE=" ^ tmpout; "-dBATCH"; filename])
in
match Sys.command gscall with
| 0 -> Pdfe.log "Succeeded!\n"; tmpout
| _ -> Pdfe.log "Could not fix malformed PDF file, even with gs\n"; exit 2
exception StdInBytes of bytes
let pdf_of_stdin ?revision user_pw owner_pw =
let rbytes = ref (mkbytes 0) in
try
let user_pw = Some user_pw
and owner_pw = if owner_pw = "" then None else Some owner_pw in
let o, bytes = Pdfio.input_output_of_bytes 16384 in
try
while true do o.Pdfio.output_char (input_char stdin) done;
Pdf.empty ()
with
End_of_file ->
let thebytes = Pdfio.extract_bytes_from_input_output o bytes in
rbytes := thebytes;
let i = Pdfio.input_of_bytes thebytes in
pdfread_pdf_of_input ?revision user_pw owner_pw i
with
_ -> raise (StdInBytes !rbytes)
let rec get_single_pdf ?(decrypt=true) ?(fail=false) op read_lazy =
let failout () =
if fail then begin
(* Reconstructed with ghostscript, but then we couldn't read it even then. Do not loop. *)
Pdfe.log "Failed to read gs-reconstructed PDF even though gs succeeded\n";
exit 2
end
in
let warn_gs () =
begin match args.inputs with
(InFile inname, _, _, _, _, _)::_ ->
begin try ignore (close_in (open_in_bin inname)) with _ ->
Pdfe.log (Printf.sprintf "File %s does not exist\n" inname);
exit 2
end
| _ -> ()
end;
Pdfe.log "get_single_pdf: failed to read malformed PDF file. Consider using -gs-malformed\n";
exit 2
in
match args.inputs with
| (InFile inname, x, u, o, y, revision) as input::more ->
if args.squeeze then
Printf.printf "Initial file size is %i bytes\n" (filesize inname);
let pdf =
try
if read_lazy then
pdfread_pdf_of_channel_lazy ?revision (optstring u) (optstring o) (open_in_bin inname)
else
pdfread_pdf_of_file ?revision (optstring u) (optstring o) inname
with
| Cpdferror.SoftError _ as e -> raise e (* Bad owner or user password *)
| _ ->
if args.gs_malformed then
begin
failout ();
let newname = mend_pdf_file_with_ghostscript inname in
args.inputs <- (InFile newname, x, u, o, y, revision)::more;
get_single_pdf ~fail:true op read_lazy
end
else
warn_gs ()
in
args.was_encrypted <- Pdfcrypt.is_encrypted pdf;
if decrypt then decrypt_if_necessary input op pdf else pdf
| (StdIn, x, u, o, y, revision) as input::more ->
let pdf =
try pdf_of_stdin ?revision u o with
StdInBytes b ->
if args.gs_malformed then
begin
failout ();
let inname = Filename.temp_file "cpdf" ".pdf" in
tempfiles := inname::!tempfiles;
let fh = open_out_bin inname in
Pdfio.bytes_to_output_channel fh b;
close_out fh;
let newname = mend_pdf_file_with_ghostscript inname in
args.inputs <- (InFile newname, x, u, o, y, revision)::more;
get_single_pdf ~fail:true op read_lazy
end
else
warn_gs ()
in
args.was_encrypted <- Pdfcrypt.is_encrypted pdf;
if decrypt then decrypt_if_necessary input op pdf else pdf
| (AlreadyInMemory (pdf, s), _, _, _, _, _)::_ -> pdf
| _ ->
raise (Arg.Bad "cpdf: No input specified.\n")
let filenames = null_hash ()
let squeeze_logto filename x =
let fh = open_out_gen [Open_wronly; Open_creat] 0o666 filename in
seek_out fh (out_channel_length fh);
output_string fh x;
close_out fh
(* This now memoizes on the name of the file to make sure we only load each
file once *)
let rec get_pdf_from_input_kind ?(read_lazy=false) ?(decrypt=true) ?(fail=false) ((_, x, u, o, y, revision) as input) op ik =
let failout () =
if fail then begin
(* Reconstructed with ghostscript, but then we couldn't read it even then. Do not loop. *)
Pdfe.log "Failed to read gs-reconstructed PDF even though gs succeeded\n";
exit 2
end
in
let warn_gs () =
begin match input with
(InFile inname, _, _, _, _, _) ->
begin try ignore (close_in (open_in_bin inname)) with _ ->
Pdfe.log (Printf.sprintf "File %s does not exist\n" inname);
exit 2
end
| _ -> ()
end;
Pdfe.log "get_pdf_from_input_kind: failed to read malformed PDF file. Consider using -gs-malformed\n";
exit 2
in
match ik with
| AlreadyInMemory (pdf, _) -> pdf
| InFile s ->
if args.squeeze then
begin
let size = filesize s in
initial_file_size := size;
let str = Printf.sprintf "Initial file size is %i bytes\n" size in
begin match !logto with
| None -> print_string str
| Some filename -> squeeze_logto filename str
end
end;
begin try Hashtbl.find filenames s with
Not_found ->
let pdf =
try
if read_lazy then
pdfread_pdf_of_channel_lazy ?revision (optstring u) (optstring o) (open_in_bin s)
else
pdfread_pdf_of_file ?revision (optstring u) (optstring o) s
with
| Cpdferror.SoftError _ as e -> raise e (* Bad owner or user password *)
| e ->
Printf.printf "%s\n" (Printexc.to_string e);
if args.gs_malformed then
begin
failout ();
let newname = mend_pdf_file_with_ghostscript s in
get_pdf_from_input_kind ~fail:true (InFile newname, x, u, o, y, revision) op (InFile newname);
end
else
warn_gs ()
in
args.was_encrypted <- Pdfcrypt.is_encrypted pdf;
let pdf = if decrypt then decrypt_if_necessary input op pdf else pdf in
Hashtbl.add filenames s pdf; pdf
end
| StdIn ->
let pdf =
try pdf_of_stdin ?revision u o with
StdInBytes b ->
if args.gs_malformed then
begin
failout ();
let inname = Filename.temp_file "cpdf" ".pdf" in
tempfiles := inname::!tempfiles;
let fh = open_out_bin inname in
Pdfio.bytes_to_output_channel fh b;
close_out fh;
let newname = mend_pdf_file_with_ghostscript inname in
get_pdf_from_input_kind ~fail:true (InFile newname, x, u, o, y, revision) op (InFile newname);
end
else
warn_gs ()
in
args.was_encrypted <- Pdfcrypt.is_encrypted pdf;
if decrypt then decrypt_if_necessary input op pdf else pdf
let rec unescape_octals prev = function
| [] -> rev prev
| '\\'::('0'..'9' as a)::('0'..'9' as b)::('0'..'9' as c)::t ->
let chr = char_of_int (int_of_string ("0o" ^ implode [a;b;c])) in
unescape_octals (chr::prev) t
| '\\'::'\\'::t -> unescape_octals ('\\'::prev) t
| h::t -> unescape_octals (h::prev) t
let unescape_octals s =
implode (unescape_octals [] (explode s))
let process s =
if args.encoding <> Cpdfmetadata.Raw
then Pdftext.pdfdocstring_of_utf8 s
else unescape_octals s
let set_producer s pdf =
ignore (Cpdfmetadata.set_pdf_info ("/Producer", Pdf.String (process s), 0) pdf)
let set_creator s pdf =
ignore (Cpdfmetadata.set_pdf_info ("/Creator", Pdf.String (process s), 0) pdf)
let really_write_pdf ?(encryption = None) ?(is_decompress=false) mk_id pdf outname =
if args.producer <> None then set_producer (unopt args.producer) pdf;
if args.creator <> None then set_creator (unopt args.creator) pdf;
if args.debugcrypt then Printf.printf "really_write_pdf\n";
let will_linearize =
args.linearize || args.keeplinearize && pdf.Pdf.was_linearized
in
let outname' =
if will_linearize then Filename.temp_file "cpdflin" ".pdf" else outname
in
if args.debugcrypt then
Printf.printf "args.recrypt = %b, args.was_encrypted = %b\n"
args.recrypt args.was_encrypted;
begin
if args.recrypt && args.was_encrypted then
begin
if args.debugcrypt then
Printf.printf "Recrypting in really_write_pdf\n";
match args.inputs with
[] -> raise (Pdf.PDFError "no input in recryption")
| (_, _, user_pw, owner_pw, _, _)::_ ->
let best_password =
if owner_pw <> "" then owner_pw else user_pw
in
Pdfwrite.pdf_to_file_options
~preserve_objstm:args.preserve_objstm
~generate_objstm:args.create_objstm
~compress_objstm:(not is_decompress)
~recrypt:(Some best_password)
None mk_id pdf outname'
end
else
begin
if args.debugforce || not args.was_encrypted || args.was_decrypted_with_owner then
begin
if args.debugcrypt then
Printf.printf "Pdf to file in really_write_pdf\n";
Pdfwrite.pdf_to_file_options
~preserve_objstm:args.preserve_objstm
~generate_objstm:args.create_objstm
~compress_objstm:(not is_decompress)
encryption mk_id pdf outname'
end
else
soft_error
"You must supply -recrypt here, or add -decrypt-force, or provide the owner password."
end
end;
begin
if will_linearize then
let cpdflin = find_cpdflin args.cpdflin in
match args.inputs with
[] -> raise (Pdf.PDFError "no input in recryption")
| (_, _, user_pw, owner_pw, _, _)::_ ->
let best_password =
if owner_pw <> "" then owner_pw else user_pw
in
let code =
call_cpdflin cpdflin outname' outname best_password
in
if code > 0 then
begin
begin try Sys.remove outname with _ -> () end;
Sys.rename outname' outname;
soft_error
"Linearizer failed with above error. \
File written without linearization."
end
else
begin try Sys.remove outname' with _ -> () end;
end;
if args.squeeze then
let s = filesize outname in
begin
let str =
Printf.sprintf
"Final file size is %i bytes, %.2f%% of original.\n"
s
((float s /. float !initial_file_size) *. 100.)
in
match !logto with
| None -> print_string str
| Some filename -> squeeze_logto filename str
end
let write_pdf ?(encryption = None) ?(is_decompress=false) mk_id pdf =
if args.debugcrypt then Printf.printf "write_pdf\n";
if args.create_objstm && not (args.keepversion || pdf.Pdf.major > 1)
then pdf.Pdf.minor <- max pdf.Pdf.minor 5;
match args.out with
| NoOutputSpecified ->
output_pdfs =| pdf
| File outname ->
begin match encryption with
None ->
if not is_decompress then
begin
ignore (Cpdfsqueeze.recompress_pdf pdf);
if args.squeeze then Cpdfsqueeze.squeeze ~pagedata:args.squeeze_pagedata ?logto:!logto pdf;
end;
Pdf.remove_unreferenced pdf;
really_write_pdf ~is_decompress mk_id pdf outname
| Some _ ->
really_write_pdf ~encryption ~is_decompress mk_id pdf outname
end
| Stdout ->
let temp = Filename.temp_file "cpdfstdout" ".pdf" in
begin match encryption with
None ->
if not is_decompress then
begin
ignore (Cpdfsqueeze.recompress_pdf pdf);
if args.squeeze then Cpdfsqueeze.squeeze ~pagedata:args.squeeze_pagedata ?logto:!logto pdf;
Pdf.remove_unreferenced pdf
end;
really_write_pdf ~encryption ~is_decompress mk_id pdf temp;
| Some _ ->
really_write_pdf ~encryption ~is_decompress mk_id pdf temp
end;
let temp_file = open_in_bin temp in
try
while true do output_char stdout (input_char temp_file) done;
assert false
with
End_of_file ->
begin try close_in temp_file; Sys.remove temp with
e -> Pdfe.log (Printf.sprintf "Failed to remove temp file %s (%s)\n" temp (Printexc.to_string e))
end;
flush stdout (*r For Windows *)
(* Find the stem of a filename *)
let stem s =
implode
(rev (tail_no_fail
(dropwhile
(neq '.') (rev (explode (Filename.basename s))))))
let fast_write_split_pdfs
?(names=[]) enc splitlevel original_filename sq spec main_pdf pagenums pdf_pages
=
let marks = Pdfmarks.read_bookmarks ~preserve_actions:true main_pdf in
iter2
(fun number pagenums ->
let pdf = Pdfpage.pdf_of_pages ~retain_numbering:args.retain_numbering ~process_struct_tree:args.process_struct_trees main_pdf pagenums in
let startpage, endpage = extremes pagenums in
let name =
if names <> [] then List.nth names (number - 1) else
Cpdfbookmarks.name_of_spec
args.encoding marks main_pdf splitlevel spec number
(stem original_filename) startpage endpage
in
Pdf.remove_unreferenced pdf;
if sq then Cpdfsqueeze.squeeze ~pagedata:args.squeeze_pagedata ?logto:!logto pdf;
really_write_pdf ~encryption:enc (not (enc = None)) pdf name)
(indx pagenums)
pagenums
(* Return list, in order, a *set* of page numbers of bookmarks at a given level *)
let bookmark_pages level pdf =
let refnums = Pdf.page_reference_numbers pdf in
let fastrefnums = hashtable_of_dictionary (combine refnums (indx refnums)) in
setify_preserving_order
(option_map
(function
l when l.Pdfmarks.level = level ->
Some (Pdfpage.pagenumber_of_target ~fastrefnums pdf l.Pdfmarks.target)
| _ -> None)
(Pdfmarks.read_bookmarks ~preserve_actions:false pdf))
let split_at_bookmarks
enc original_filename ~squeeze level spec pdf
=
let pdf_pages = Pdfpage.pages_of_pagetree pdf in
let points = bookmark_pages level pdf in
let points =
lose (fun x -> x <= 0 || x > Pdfpage.endpage pdf) (map pred points)
in
let pts = splitat points (indx pdf_pages) in
fast_write_split_pdfs
enc level original_filename squeeze spec pdf pts pdf_pages
let split_pdf
enc original_filename
chunksize linearize ~cpdflin ~squeeze
spec pdf
=
let pdf_pages = Pdfpage.pages_of_pagetree pdf in
fast_write_split_pdfs
enc 0 original_filename squeeze spec pdf
(splitinto chunksize (indx pdf_pages)) pdf_pages
(* Given a PDF, write the split as if we had selected pages, and return its filesize. Delete it. *)
let split_max_fits pdf s p q =
if q < p then error "split_max_fits" else
let filename = Filename.temp_file "cpdf" "sm" in
let range = ilist p q in
let newpdf = Pdfpage.pdf_of_pages ~process_struct_tree:args.process_struct_trees ~retain_numbering:args.retain_numbering pdf range in
let r = args.out in
args.out <- File filename;
write_pdf false newpdf;
args.out <- r;
let fh = open_in_bin filename in
let size = in_channel_length fh in
begin try close_in fh; Sys.remove filename with _ -> () end;
size <= s
(* Binary search on q from current value down to p to find max which fits. Returns q. Upon failure, returns -1 *)
let rec split_max_search pdf s b p q =
if p = q then
if split_max_fits pdf s b q then q else -1
else
let half = (q + p) / 2 in
if split_max_fits pdf s b (half + 1)
then split_max_search pdf s b (half + 1) q
else split_max_search pdf s b p half
let split_max enc original_filename ~squeeze output_spec s pdf =
let outs = ref [] in
let p = ref 1 in
let endpage = Pdfpage.endpage pdf in
let q = ref endpage in
while !p < !q || !p = endpage do
let newq = split_max_search pdf s !p !p !q in
if newq = -1 then (Printf.eprintf "Failed to make small enough split at page %i. No files written.\n" !p; exit 2) else
begin
(*Printf.printf "Pages %i-%i will fit...\n%!" !p newq;*)
outs := ilist !p newq::!outs;
p := newq + 1;
q := endpage
end
done;
fast_write_split_pdfs enc 0 original_filename squeeze output_spec pdf (rev !outs) (Pdfpage.pages_of_pagetree pdf)
let getencryption pdf =
match Pdfread.what_encryption pdf with
| None | Some Pdfwrite.AlreadyEncrypted -> "Not encrypted"
| Some Pdfwrite.PDF40bit -> "40bit"
| Some Pdfwrite.PDF128bit -> "128bit"
| Some (Pdfwrite.AES128bit true) -> "128bit AES, Metadata encrypted"
| Some (Pdfwrite.AES128bit false) -> "128bit AES, Metadata not encrypted"
| Some (Pdfwrite.AES256bit true) -> "256bit AES, Metadata encrypted"
| Some (Pdfwrite.AES256bit false) -> "256bit AES, Metadata not encrypted"
| Some (Pdfwrite.AES256bitISO true) -> "256bit AES ISO, Metadata encrypted"
| Some (Pdfwrite.AES256bitISO false) -> "256bit AES ISO, Metadata not encrypted"
let write_json output pdf =
match output with
| NoOutputSpecified ->
error "-output-json: no output name specified"
| Stdout ->
Cpdfjson.to_output
(Pdfio.output_of_channel stdout)
~utf8:(args.encoding = Cpdfmetadata.UTF8)
~parse_content:args.jsonparsecontentstreams
~no_stream_data:args.jsonnostreamdata
~decompress_streams:args.jsondecompressstreams
~clean_strings:args.jsoncleanstrings
pdf
| File filename ->
let f = open_out filename in
Cpdfjson.to_output
(Pdfio.output_of_channel f)
~utf8:(args.encoding = Cpdfmetadata.UTF8)
~parse_content:args.jsonparsecontentstreams
~no_stream_data:args.jsonnostreamdata
~decompress_streams:args.jsondecompressstreams
~clean_strings:args.jsoncleanstrings
pdf;
close_out f
let json_to_output json = function
| NoOutputSpecified ->
error "no output name specified"
| Stdout ->
output_string stdout (Cpdfyojson.Safe.pretty_to_string json);
| File filename ->
let f = open_out filename in
output_string f (Cpdfyojson.Safe.pretty_to_string json);
close_out f
let collate n (names, pdfs, ranges) =
let ois = map ref (combine3 names pdfs ranges) in
let nis = ref [] in
while flatten (map (fun {contents = (_, _, r)} -> r) ois) <> [] do
iter
(fun ({contents = (name, pdf, range)} as r) ->
match range with
| [] -> ()
| l ->
if length l > n then
begin
nis := (name, pdf, take l n)::!nis;
r := (name, pdf, drop l n)
end
else
begin
nis := (name, pdf, l)::!nis;
r := (name, pdf, [])
end)
ois
done;
split3 (rev !nis)
let warn_prerotate range pdf =
if not args.prerotate && not (Cpdfpage.alluprightonly range pdf) then
Pdfe.log "Some pages in the range have non-zero rotation. \
Consider adding -prerotate or pre-processing with -upright. \
To silence this warning use -no-warn-rotate\n"
let prerotate range pdf =
Cpdfpage.upright ~fast:args.fast range pdf
let check_bookmarks_mistake () =
if args.merge_add_bookmarks_use_titles && not args.merge_add_bookmarks then
Pdfe.log "Warning: -merge-add-bookmarks-use-titles is for use with -merge-add-bookmarks\n"
let check_clashing_output_name () =
match args.out with
| File s ->
if (List.exists (function (InFile s', _, _, _, _, _) when s = s' -> true | _ -> false) args.inputs) then
Pdfe.log "Warning: output file name clashes with input file name. Malformed file may result.\n"
| _ -> ()
let build_enc () =
match args.crypt_method with
| "" -> None
| _ ->
Some
{Pdfwrite.encryption_method =
(match args.crypt_method with
| "40bit" -> Pdfwrite.PDF40bit
| "128bit" -> Pdfwrite.PDF128bit
| "AES" -> Pdfwrite.AES128bit args.encrypt_metadata
| "AES256" -> Pdfwrite.AES256bit args.encrypt_metadata
| "AES256ISO" -> Pdfwrite.AES256bitISO args.encrypt_metadata
| _ -> assert false (* Pre-checked *));
Pdfwrite.owner_password = args.owner;
Pdfwrite.user_password = args.user;
Pdfwrite.permissions = banlist_of_args ()}
let print_obj json pdf objspec =
let obj = Cpdftweak.find_obj pdf objspec in
let trim s = implode (rev (tl (rev (tl (explode s))))) in
if json then
print_string (Cpdfyojson.Safe.pretty_to_string (Cpdfjson.json_of_object ~utf8:true pdf (fun _ -> ()) ~no_stream_data:false ~parse_content:false obj))
else
print_endline (trim (Printf.sprintf "%S" (Pdfwrite.string_of_pdf obj)))
let extract_stream_find_obj pdf objspec =
int_of_string objspec
let extract_stream pdf decomp objspec =
let obj = Cpdftweak.find_obj pdf objspec in
Pdf.getstream obj;
if decomp then Pdfcodec.decode_pdfstream_until_unknown pdf obj;
let data =
match obj with
| Pdf.Stream {contents = (_, Pdf.Got x)} -> x
| _ -> raise (Pdf.PDFError "Stream not found")
in
match args.out with
| NoOutputSpecified ->
raise (Pdf.PDFError "No output specified")
| File outname ->
let fh = open_out_bin outname in
output_string fh (Pdfio.string_of_bytes data);
close_out fh
| Stdout ->
output_string stdout (Pdfio.string_of_bytes data)
let print_version () =
flprint
("cpdf " ^ (if agpl then "AGPL " else "") ^ "Version " ^ string_of_int major_version ^ "." ^ string_of_int minor_version ^ (if minor_minor_version = 0 then "" else "." ^ string_of_int minor_minor_version) ^ " " ^ version_date ^ "\n")
(* Call out to GhostScript to rasterize. Read back in and replace the page contents with the resultant PNG. *)
let rasterize antialias downsample device res annots quality pdf range =
if args.path_to_ghostscript = "" then begin
Pdfe.log "Please supply path to gs with -gs\n";
exit 2
end;
let tmppdf = Filename.temp_file "cpdf" ".pdf" in
tempfiles := tmppdf::!tempfiles;
Pdfwrite.pdf_to_file (Pdf.deep_copy pdf) tmppdf;
let pdf = Pdfpage.change_pages true pdf
(map2
(fun page pnum ->
if not (mem pnum range) then page else
let tmpout = Filename.temp_file "cpdf" ".png" in
tempfiles := tmpout::!tempfiles;
let antialias, res =
if downsample then ["-dDownScaleFactor=4"], res *. 4. else
let bits = if antialias then "4" else "1" in
["-dTextAlphaBits=" ^ bits; "-dGraphicsAlphaBits=" ^ bits], res
in
let gscall =
Filename.quote_command args.path_to_ghostscript
((if args.gs_quiet then ["-dQUIET"] else []) @
antialias @
["-dBATCH"; "-dNOPAUSE"; "-sDEVICE=" ^ device; "-dUseCropBox"; "-dShowAnnots=" ^ string_of_bool annots;
"-dJPEGQ=" ^ string_of_int quality; "-sOutputFile=" ^ tmpout; "-sPageList=" ^ string_of_int pnum;
"-r" ^ string_of_float res; tmppdf])
in
(*Printf.printf "CALL: %S\n" gscall;*)
begin match Sys.command gscall with
| 0 -> ()
| _ -> Pdfe.log "Rasterization failed\n"; exit 2
end;
let data = Pdfio.bytes_of_string (Pdfutil.contents_of_file tmpout) in
Sys.remove tmpout;
let image, _ = (if device = "jpeg" || device = "jpeggray" then Cpdfimage.obj_of_jpeg_data else Cpdfimage.obj_of_png_data) data in
let imageobj = Pdf.addobj pdf image in
let w, h =
match device with
| "jpeg" | "jpeggray" -> Cpdfjpeg.jpeg_dimensions data
| _ -> let png = Cpdfpng.read_png (Pdfio.input_of_bytes data) in (png.Cpdfpng.width, png.Cpdfpng.height)
in
let w, h =
match page.Pdfpage.rotate with
| Pdfpage.Rotate90 | Pdfpage.Rotate270 -> h, w
| _ -> w, h
in
let w, h = if downsample then w * 4, h * 4 else w, h in
let (minx, miny, maxx, maxy) =
Pdf.parse_rectangle
pdf
(match Pdf.lookup_direct pdf "/CropBox" page.Pdfpage.rest with
| Some r -> r
| None -> page.Pdfpage.mediabox)
in
let rotation = rad_of_deg (float_of_int (Pdfpage.int_of_rotation page.Pdfpage.rotate)) in
let tx, ty =
match page.Pdfpage.rotate with
| Pdfpage.Rotate0 -> (minx, miny)
| Pdfpage.Rotate270 -> (minx, miny +. (maxy -. miny))
| Pdfpage.Rotate90 -> (minx +. (maxx -. minx), miny)
| Pdfpage.Rotate180 -> (minx +. (maxx -. minx), miny +. (maxy -. miny))
in
let ops =
[Pdfops.Op_cm
(Pdftransform.matrix_of_transform
[Pdftransform.Translate (tx, ty);
Pdftransform.Scale ((0., 0.), float_of_int w *. 72. /. res, float_of_int h *. 72. /. res);
Pdftransform.Rotate ((0., 0.), rotation)]);
Pdfops.Op_BMC "/Artifact";
Pdfops.Op_Do "/I0";
Pdfops.Op_EMC]
in
{page with Pdfpage.content = [Pdfops.stream_of_ops ops];
Pdfpage.resources = Pdf.Dictionary [("/XObject", Pdf.Dictionary [("/I0", Pdf.Indirect imageobj)])]})
(Pdfpage.pages_of_pagetree pdf)
(ilist 1 (Pdfpage.endpage pdf)))
in
let pdf = if annots then Cpdfannot.remove_annotations range pdf else pdf in
Sys.remove tmppdf;
pdf
let write_images device res quality boxname annots antialias downsample spec pdf range =
if args.path_to_ghostscript = "" then begin
Pdfe.log "Please supply path to gs with -gs\n";
exit 2
end;
let tmppdf = Filename.temp_file "cpdf" ".pdf" in
tempfiles := tmppdf::!tempfiles;
Pdfwrite.pdf_to_file (Pdf.deep_copy pdf) tmppdf;
let endpage = Pdfpage.endpage pdf in
iter2
(fun page pnum ->
if not (mem pnum range) then () else
let out = Cpdfbookmarks.name_of_spec Cpdfmetadata.UTF8 [] pdf 0 spec pnum "" 0 0 in
let antialias, res =
if downsample then ["-dDownScaleFactor=4"], res *. 4. else
let bits = if antialias then "4" else "1" in
["-dTextAlphaBits=" ^ bits; "-dGraphicsAlphaBits=" ^ bits], res
in
let gscall =
Filename.quote_command args.path_to_ghostscript
((if args.gs_quiet then ["-dQUIET"] else []) @
(if boxname = None then [] else ["-dUse" ^ (implode (tl (explode (unopt boxname))))]) @
antialias @
["-dBATCH"; "-dNOPAUSE"; "-sDEVICE=" ^ device; "-dShowAnnots=" ^ string_of_bool annots;
"-dJPEGQ=" ^ string_of_int quality; "-sOutputFile=" ^ out; "-sPageList=" ^ string_of_int pnum;
"-r" ^ string_of_float res; tmppdf])
in
(*Printf.printf "CALL: %S\n" gscall;*)
begin match Sys.command gscall with
| 0 -> ()
| _ -> Pdfe.log "Rasterization failed\n"; exit 2
end)
(Pdfpage.pages_of_pagetree pdf)
(ilist 1 endpage);
Sys.remove tmppdf
(* Main function *)
let go () =
check_bookmarks_mistake ();
check_clashing_output_name ();
match args.op with
| Some Version -> print_version ()
| None | Some Merge ->
begin match args.out, args.inputs with
| _, (_::_ as inputs) ->
let op = match inputs with [_] -> None | _ -> Some Merge in
let names, ranges, rotations, _, _, _ = split6 inputs in
let pdfs = map2 (fun i -> get_pdf_from_input_kind i op) inputs names in
(* If at least one file had object streams and args.preserve_objstm is true, set -objstm-create *)
if args.preserve_objstm then
iter
(fun pdf ->
if Hashtbl.length pdf.Pdf.objects.Pdf.object_stream_ids > 0
then args.create_objstm <- true)
pdfs;
begin match pdfs with
| [pdf] ->
if hd ranges <> "all" then
let range = parse_pagespec pdf (hd ranges) in
let newpdf = Pdfpage.pdf_of_pages ~process_struct_tree:args.process_struct_trees ~retain_numbering:args.retain_numbering pdf range in
write_pdf false newpdf
else
write_pdf false pdf
| _ ->
(* We check permissions. A merge is allowed if each file
included was (a) not encrypted (detected by the absence of
saved encryption information in the PDF, or (b) decrypted using
the owner password (stored in the input) *)
if
(not args.debugforce) &&
(not
(fold_left ( && ) true
(map2
(fun (_, _, _, _, was_dec_with_owner, _) pdf ->
!was_dec_with_owner || pdf.Pdf.saved_encryption = None)
inputs
pdfs)))
then
soft_error "Merge requires the owner password for all encrypted files, or -decrypt-force."
else
let pdfs =
if args.merge_add_bookmarks then
map2
(fun filename pdf -> Cpdfbookmarks.add_bookmark_title filename args.merge_add_bookmarks_use_titles pdf)
(map (function InFile s -> s | StdIn -> "" | AlreadyInMemory (_, s) -> s) names)
pdfs
else
pdfs
in
(* If args.keep_this_id is set, change the ID to the one from the kept one *)
let rangenums = map2 parse_pagespec pdfs ranges in
(* At this point, we have the information for collation. *)
let names = map string_of_input_kind names in
let names, pdfs, rangenums =
(if args.collate > 0 then collate args.collate else Fun.id) (names, pdfs, rangenums)
in
let outpdf =
Pdfmerge.merge_pdfs
args.retain_numbering args.remove_duplicate_fonts ~process_struct_trees:args.process_struct_trees
~add_toplevel_document:(args.subformat = Some Cpdfua.PDFUA2) names pdfs rangenums
in
if args.remove_duplicate_streams then Pdfmerge.remove_duplicate_fonts outpdf; (* JBIG2 Globals *)
write_pdf false outpdf
end
| _ ->
match args.op with
| Some Merge ->
error "Merge: Must specify one output and at least one input"
| None ->
error "Must specify one output and at least one input"
| _ -> assert false
end
| Some (CopyFont fromfile) ->
begin match args.inputs, args.out with
| (_, pagespec, u, o, _, _)::_, _ ->
let pdf = get_single_pdf (Some (CopyFont fromfile)) false
and frompdf = pdfread_pdf_of_file (optstring u) (optstring o) fromfile in
let range = parse_pagespec_allow_empty pdf pagespec in
let copyfontname =
match args.copyfontname with
| Some x -> x
| None -> failwith "copy_font: no font name given"
in
let outpdf = Cpdffont.copy_font frompdf copyfontname args.copyfontpage range pdf in
write_pdf true outpdf
| _ -> error "copyfont: bad command line"
end
| Some RemoveFonts ->
begin match args.inputs, args.out with
| (_, pagespec, _, _, _, _)::_, _ ->
let pdf = get_single_pdf (Some RemoveFonts) false in
write_pdf true (Cpdffont.remove_fonts pdf)
| _ -> error "remove fonts: bad command line"
end
| Some (ExtractFontFile spec) ->
begin match args.inputs, args.out with
| (_, pagespec, u, o, _, _)::_, File filename ->
let pdf = get_single_pdf (Some (ExtractFontFile spec)) false in
begin match String.split_on_char ',' spec with
| [pnum; name] ->
begin try Cpdffont.extract_fontfile (int_of_string pnum) name filename pdf with
Failure _ (*"int_of_string"*) -> error "extract font: bad page number"
end
| _ -> error "extract font: bad specification"
end
| _ -> error "extract fontfile: bad command line"
end
| Some CountPages ->
begin match args.inputs with
[(ik, _, _, _, _, _) as input] ->
let pdf = get_pdf_from_input_kind ~read_lazy:true ~decrypt:false input (Some CountPages) ik in
output_page_count pdf
| _ -> raise (Arg.Bad "CountPages: must have a single input file only")
end
| Some Clean ->
let pdf' = get_single_pdf (Some Clean) false in
write_pdf false pdf'
| Some Info ->
let pdf, inname, input =
match args.inputs with
| (InFile inname, _, u, o, _, _) as input::_ ->
pdfread_pdf_of_channel_lazy (optstring u) (optstring o) (open_in_bin inname), inname, input
| (StdIn, _, u, o, _, _) as input::_ -> pdf_of_stdin u o, "", input
| (AlreadyInMemory (pdf, _), _, _, _, _, _) as input::_ -> pdf, "", input
| _ -> raise (Arg.Bad "cpdf: No input specified.\n")
in
let json = ref [] in
if args.format_json
then json =| ("Encryption", `String (getencryption pdf))
else Printf.printf "Encryption: %s\n" (getencryption pdf);
if args.format_json
then json =| ("Permissions", `List (map (fun p -> `String (string_of_permission p)) (Pdfread.permissions pdf)))
else Printf.printf "Permissions: %s\n" (getpermissions pdf);
if inname <> "" then
let lin = Pdfread.is_linearized (Pdfio.input_of_channel (open_in_bin inname)) in
if args.format_json then
json =| ("Linearized", `Bool lin) else Printf.printf "Linearized: %b\n" lin;
let objstm = length (list_of_hashtbl pdf.Pdf.objects.Pdf.object_stream_ids) > 0 in
if args.format_json
then json =| ("Object streams", `Bool objstm)
else Printf.printf "Object streams: %b\n" objstm;
let ida, idb =
match Pdf.lookup_direct pdf "/ID" pdf.Pdf.trailerdict with
| Some (Pdf.Array [Pdf.String s; Pdf.String s']) ->
(Pdfwrite.make_hex_pdf_string s, Pdfwrite.make_hex_pdf_string s')
| _ -> "", ""
in
let fixid s = implode (rev (tl (rev (tl (explode s))))) in
if args.format_json
then json =| ("ID", if ida ^ idb = "" then `Null else `List [`String (fixid ida); `String (fixid idb)])
else (if ida ^ idb = "" then Printf.printf "ID: None\n" else Printf.printf "ID: %s %s\n" ida idb);
let pdf = decrypt_if_necessary input (Some Info) pdf in
if args.format_json then
begin
Cpdfmetadata.output_info ~json Cpdfmetadata.UTF8 args.output_unit pdf;
Cpdfmetadata.output_xmp_info ~json Cpdfmetadata.UTF8 args.output_unit pdf;
flprint (Cpdfyojson.Safe.pretty_to_string (`Assoc (rev !json)))
end
else
begin
Cpdfmetadata.output_info args.encoding args.output_unit pdf;
Cpdfmetadata.output_xmp_info args.encoding args.output_unit pdf
end
| Some PageInfo ->
begin match args.inputs, args.out with
| (_, pagespec, _, _, _, _)::_, _ ->
let pdf = get_single_pdf args.op true in
let range = parse_pagespec_allow_empty pdf pagespec in
Cpdfpage.output_page_info ~json:args.format_json args.output_unit pdf range
| _ -> error "list-bookmarks: bad command line"
end
| Some Metadata ->
Cpdfmetadata.print_metadata (get_single_pdf (Some Metadata) true)
| Some Fonts ->
begin match args.inputs, args.out with
| (_, pagespec, _, _, _, _)::_, _ ->
let pdf = get_single_pdf (Some Fonts) true in
let range = parse_pagespec_allow_empty pdf pagespec in
Cpdffont.print_fonts ~json:args.format_json pdf range
| _ -> error "-list-fonts: bad command line"
end
| Some ListBookmarks ->
begin match args.inputs, args.out with
| (_, pagespec, _, _, _, _)::_, _ ->
let pdf = get_single_pdf args.op true in
let range = parse_pagespec_allow_empty pdf pagespec in
Cpdfbookmarks.list_bookmarks ~json:args.format_json ~json_preserve_actions:args.preserve_actions args.encoding range pdf (Pdfio.output_of_channel stdout);
flush stdout
| _ -> error "list-bookmarks: bad command line"
end
| Some Crop ->
begin match args.inputs, args.out with
| (_, pagespec, _, _, _, _)::_, _ ->
let pdf = get_single_pdf (Some Crop) false in
let xywhlist = Cpdfcoord.parse_rectangles pdf args.rectangle in
let range = parse_pagespec_allow_empty pdf pagespec in
let pdf = Cpdfpage.crop_pdf xywhlist pdf range in
write_pdf false pdf
| _ -> error "crop: bad command line"
end
| Some Art ->
begin match args.inputs, args.out with
| (_, pagespec, _, _, _, _)::_, _ ->
let pdf = get_single_pdf (Some Art) false in
let xywhlist = Cpdfcoord.parse_rectangles pdf args.rectangle in
let range = parse_pagespec_allow_empty pdf pagespec in
let pdf = Cpdfpage.crop_pdf ~box:"/ArtBox" xywhlist pdf range in
write_pdf false pdf
| _ -> error "art: bad command line"
end
| Some Bleed ->
begin match args.inputs, args.out with
| (_, pagespec, _, _, _, _)::_, _ ->
let pdf = get_single_pdf (Some Bleed) false in
let xywhlist = Cpdfcoord.parse_rectangles pdf args.rectangle in
let range = parse_pagespec_allow_empty pdf pagespec in
let pdf = Cpdfpage.crop_pdf ~box:"/BleedBox" xywhlist pdf range in
write_pdf false pdf
| _ -> error "bleed: bad command line"
end
| Some Trim ->
begin match args.inputs, args.out with
| (_, pagespec, _, _, _, _)::_, _ ->
let pdf = get_single_pdf (Some Trim) false in
let xywhlist = Cpdfcoord.parse_rectangles pdf args.rectangle in
let range = parse_pagespec_allow_empty pdf pagespec in
let pdf = Cpdfpage.crop_pdf ~box:"/TrimBox" xywhlist pdf range in
write_pdf false pdf
| _ -> error "trim: bad command line"
end
| Some MediaBox ->
begin match args.inputs, args.out with
| (_, pagespec, _, _, _, _)::_, _ ->
let pdf = get_single_pdf (Some MediaBox) false in
let xywhlist = Cpdfcoord.parse_rectangles pdf args.rectangle in
let range = parse_pagespec_allow_empty pdf pagespec in
let pdf = Cpdfpage.set_mediabox xywhlist pdf range in
write_pdf false pdf
| _ -> error "set media box: bad command line"
end
| Some (HardBox box) ->
begin match args.inputs, args.out with
| (_, pagespec, _, _, _, _)::_, _ ->
let pdf = get_single_pdf (Some (HardBox box)) false in
let range = parse_pagespec_allow_empty pdf pagespec in
let pdf = Cpdfpage.hard_box pdf range box args.mediabox_if_missing args.fast in
write_pdf false pdf
| _ -> error "hard box: bad command line"
end
| Some CopyBox ->
begin match args.inputs, args.out with
| (_, pagespec, _, _, _, _)::_, _ ->
let pdf = get_single_pdf (Some CopyBox) false in
let range = parse_pagespec_allow_empty pdf pagespec in
let f, t =
begin match args.frombox, args.tobox with
| Some f, Some t -> f, t
| _ -> error "Copy box: no tobox or no frombox specified"
end
in
let pdf = Cpdfpage.copy_box f t args.mediabox_if_missing pdf range in
write_pdf false pdf
| _ -> error "Copy Box: bad command line"
end
| Some Decompress ->
let pdf = get_single_pdf (Some Decompress) false in
Pdf.iter_stream
(function stream ->
try Pdfcodec.decode_pdfstream_until_unknown pdf stream with
e -> Pdfe.log (Printf.sprintf "Decode failure: %s. Carrying on...\n" (Printexc.to_string e)); ())
pdf;
write_pdf ~is_decompress:true false pdf
| Some Compress ->
let pdf = get_single_pdf (Some Compress) false in
if args.remove_duplicate_streams then
Pdfmerge.remove_duplicate_fonts pdf;
write_pdf false (Cpdfsqueeze.recompress_pdf pdf)
| Some RemoveCrop ->
begin match args.inputs, args.out with
| (_, pagespec, _, _, _, _)::_, _ ->
let pdf = get_single_pdf (Some RemoveCrop) false in
let range = parse_pagespec_allow_empty pdf pagespec in
let pdf = Cpdfpage.remove_cropping_pdf pdf range in
write_pdf false pdf
| _ -> error "remove-crop: bad command line"
end
| Some RemoveArt ->
begin match args.inputs, args.out with
| (_, pagespec, _, _, _, _)::_, _ ->
let pdf = get_single_pdf (Some RemoveArt) false in
let range = parse_pagespec_allow_empty pdf pagespec in
let pdf = Cpdfpage.remove_art_pdf pdf range in
write_pdf false pdf
| _ -> error "remove-crop: bad command line"
end
| Some RemoveTrim ->
begin match args.inputs, args.out with
| (_, pagespec, _, _, _, _)::_, _ ->
let pdf = get_single_pdf (Some RemoveTrim) false in
let range = parse_pagespec_allow_empty pdf pagespec in
let pdf = Cpdfpage.remove_trim_pdf pdf range in
write_pdf false pdf
| _ -> error "remove-crop: bad command line"
end
| Some RemoveBleed ->
begin match args.inputs, args.out with
| (_, pagespec, _, _, _, _)::_, _ ->
let pdf = get_single_pdf (Some RemoveBleed) false in
let range = parse_pagespec_allow_empty pdf pagespec in
let pdf = Cpdfpage.remove_bleed_pdf pdf range in
write_pdf false pdf
| _ -> error "remove-crop: bad command line"
end
| Some (Rotate _) | Some (Rotateby _) ->
begin match args.inputs, args.out with
| (_, pagespec, _, _, _, _)::_, _ ->
let pdf = get_single_pdf args.op false in
let range = parse_pagespec_allow_empty pdf pagespec in
let rotate =
match args.op with
| Some (Rotate i) -> Cpdfpage.rotate_pdf i
| Some (Rotateby i) -> Cpdfpage.rotate_pdf_by i
| _ -> assert false
in
let pdf = rotate pdf range in
write_pdf false pdf
| _ -> error "rotate: bad command line"
end
| Some (RotateContents a) ->
begin match args.inputs, args.out with
| (_, pagespec, _, _, _, _)::_, _ ->
let pdf = get_single_pdf args.op false in
let range = parse_pagespec_allow_empty pdf pagespec in
let pdf = Cpdfpage.rotate_contents ~fast:args.fast a pdf range in
write_pdf false pdf
| _ -> error "rotate-contents: bad command line"
end
| Some Upright ->
begin match args.inputs, args.out with
| (_, pagespec, _, _, _, _)::_, _ ->
let pdf = get_single_pdf args.op false in
let range = parse_pagespec_allow_empty pdf pagespec in
let pdf = Cpdfpage.upright ~fast:args.fast range pdf in
write_pdf false pdf
| _ -> error "rotate-contents: bad command line"
end
| Some ((VFlip | HFlip) as flip) ->
begin match args.inputs, args.out with
| (_, pagespec, _, _, _, _)::_, _ ->
let pdf = get_single_pdf args.op false in
let range = parse_pagespec_allow_empty pdf pagespec in
let pdf =
if flip = VFlip
then Cpdfpage.vflip_pdf ~fast:args.fast pdf range
else Cpdfpage.hflip_pdf ~fast:args.fast pdf range
in
write_pdf false pdf
| _ -> error "flip: bad command line"
end
| Some ((SetAuthor _ | SetTitle _ | SetSubject _ | SetKeywords _
| SetCreate _ | SetModify _ | SetCreator _ | SetProducer _
| SetTrapped | SetUntrapped) as op) ->
let key, value, version =
let f s = if args.encoding <> Cpdfmetadata.Raw then Pdftext.pdfdocstring_of_utf8 s else unescape_octals s in
match op with
| SetAuthor s -> "/Author", Pdf.String (f s), 0
| SetTitle s -> "/Title", Pdf.String (f s), 1
| SetSubject s -> "/Subject", Pdf.String (f s), 1
| SetKeywords s -> "/Keywords", Pdf.String (f s), 1
| SetCreate s -> "/CreationDate", Pdf.String (Cpdfmetadata.expand_date s), 0
| SetModify s -> "/ModDate", Pdf.String (Cpdfmetadata.expand_date s), 0
| SetCreator s -> "/Creator", Pdf.String (f s), 0
| SetProducer s -> "/Producer", Pdf.String (f s), 0
| SetTrapped -> "/Trapped", Pdf.Boolean true, 3
| SetUntrapped -> "/Trapped", Pdf.Boolean false, 3
| _ -> assert false
in
let pdf = get_single_pdf args.op false in
let version = if args.keepversion || pdf.Pdf.major > 1 then pdf.Pdf.minor else version in
write_pdf false
(Cpdfmetadata.set_pdf_info
~xmp_also:args.alsosetxml
~xmp_just_set:args.justsetxml
(key, value, version) pdf)
| Some (SetMetadataDate date) ->
write_pdf false (Cpdfmetadata.set_metadata_date (get_single_pdf args.op false) date)
| Some ((HideToolbar _ | HideMenubar _ | HideWindowUI _
| FitWindow _ | CenterWindow _ | DisplayDocTitle _) as op) ->
begin match args.out with
| _ ->
let key, value, version =
match op with
| HideToolbar s -> "/HideToolbar", Pdf.Boolean s, 0
| HideMenubar s -> "/HideMenubar", Pdf.Boolean s, 0
| HideWindowUI s -> "/HideWindowUI", Pdf.Boolean s, 0
| FitWindow s -> "/FitWindow", Pdf.Boolean s, 0
| CenterWindow s -> "/CenterWindow", Pdf.Boolean s, 0
| DisplayDocTitle s -> "/DisplayDocTitle", Pdf.Boolean s, 4
| _ -> assert false
in
let pdf = get_single_pdf args.op false in
let version = if args.keepversion || pdf.Pdf.major > 1 then pdf.Pdf.minor else version in
write_pdf false (Cpdfmetadata.set_viewer_preference (key, value, version) pdf)
end
| Some (OpenAtPage str) ->
let pdf = get_single_pdf args.op false in
let range = parse_pagespec_allow_empty pdf str in
let n = match range with [x] -> x | _ -> error "open_at_page: range does not specify single page" in
write_pdf false (Cpdfmetadata.set_open_action pdf false n)
| Some (OpenAtPageFit str) ->
let pdf = get_single_pdf args.op false in
let range = parse_pagespec_allow_empty pdf str in
let n = match range with [x] -> x | _ -> error "open_at_page_fit: range does not specify single page" in
write_pdf false (Cpdfmetadata.set_open_action pdf true n)
| Some (OpenAtPageCustom dest) ->
let pdf = get_single_pdf args.op false in
write_pdf false (Cpdfmetadata.set_open_action ~dest pdf true 1)
| Some (SetMetadata metadata_file) ->
write_pdf false (Cpdfmetadata.set_metadata args.keepversion metadata_file (get_single_pdf args.op false))
| Some (SetVersion v) ->
let pdf = get_single_pdf args.op false in
let pdf =
if v >= 10
then {pdf with Pdf.major = 2; Pdf.minor = v - 10}
else {pdf with Pdf.major = 1; Pdf.minor = v}
in
write_pdf false pdf
| Some (SetPageLayout s) ->
write_pdf false (Cpdfmetadata.set_page_layout (get_single_pdf args.op false) s)
| Some (SetPageMode s) ->
write_pdf false (Cpdfmetadata.set_page_mode (get_single_pdf args.op false) s)
| Some (SetNonFullScreenPageMode s) ->
write_pdf false (Cpdfmetadata.set_non_full_screen_page_mode (get_single_pdf args.op false) s)
| Some Split ->
begin match args.inputs, args.out with
| [(f, ranges, _, _, _, _)], File output_spec ->
let pdf = get_single_pdf args.op true in
let enc = build_enc () in
if args.preserve_objstm then args.create_objstm <- true; (* For split, always create if preserving *)
split_pdf
enc args.original_filename args.chunksize args.linearize ~cpdflin:args.cpdflin
~squeeze:args.squeeze output_spec pdf
| _, Stdout -> error "Can't split to standard output"
| _, NoOutputSpecified -> error "Split: No output format specified"
| _ -> error "Split: bad parameters"
end
| Some (SplitOnBookmarks level) ->
begin match args.out with
| File output_spec ->
let pdf = get_single_pdf args.op false in
let enc = build_enc () in
args.create_objstm <- args.preserve_objstm;
split_at_bookmarks
enc args.original_filename ~squeeze:args.squeeze level output_spec pdf
| Stdout -> error "Can't split to standard output"
| NoOutputSpecified -> error "Split: No output format specified"
end
| Some (SplitMax s) ->
begin match args.out with
| File output_spec ->
let pdf = get_single_pdf args.op false in
let enc = build_enc () in
args.create_objstm <- args.preserve_objstm;
split_max enc args.original_filename ~squeeze:args.squeeze output_spec s pdf
| Stdout -> error "Can't split to standard output"
| NoOutputSpecified -> error "Split: No output format specified"
end
| Some Spray ->
begin match args.inputs, args.out with
| (_, pagespec, _, _, _, _)::_, File output_spec ->
let pdf = get_single_pdf args.op false in
let range = ref (parse_pagespec pdf pagespec) in
let enc = build_enc () in
let pagenums = map ref (many [] (length !spray_outputs)) in
let n = ref 0 in
while !range <> [] do
List.nth pagenums (!n mod (length !spray_outputs)) =| hd !range;
range := tl !range;
n += 1;
done;
let names = rev !spray_outputs in
iter (fun x -> if !x = [] then error "Spray: must have at least one page for each output") pagenums;
args.create_objstm <- args.preserve_objstm;
fast_write_split_pdfs ~names enc 0 args.original_filename args.squeeze output_spec pdf (map rev (map (!) pagenums)) (Pdfpage.pages_of_pagetree pdf)
| _, Stdout -> error "Can't spray to standard output"
| _, NoOutputSpecified -> error "Spray: No output format specified"
| _, _ -> error "Spray: no input"
end
| Some Presentation ->
let pdf = get_single_pdf args.op false in
let range = parse_pagespec_allow_empty pdf (get_pagespec ()) in
let pdf' =
Cpdfpresent.presentation
range
args.transition args.duration args.horizontal
args.inward args.direction args.effect_duration pdf
in
pdf.Pdf.minor <- if args.keepversion || pdf.Pdf.major > 1 then pdf.Pdf.minor else max pdf.Pdf.minor 1;
write_pdf false pdf'
| Some ChangeId ->
if args.recrypt then
soft_error "Cannot recrypt with change id: an id is part of encryption information";
begin match args.inputs, args.out with
| [(k, _, _, _, _, _) as input], File s ->
let pdf = get_pdf_from_input_kind input args.op k in
write_pdf true pdf
| [(k, _, _, _, _, _) as input], Stdout ->
let pdf = get_pdf_from_input_kind input args.op k in
write_pdf true pdf
| _ -> error "ChangeId: exactly one input file and output file required."
end
| Some RemoveId ->
if args.recrypt then
soft_error "Cannot recrypt with remove id: an id is part of encryption information";
let pdf = get_single_pdf args.op false in
pdf.Pdf.trailerdict <- Pdf.remove_dict_entry pdf.Pdf.trailerdict "/ID";
write_pdf false pdf
| Some (CopyId getfrom) ->
if args.recrypt then
soft_error "Cannot recrypt with copy id: an id is part of encryption information";
begin match args.inputs with
| [(k, _, u, o, _, _) as input] ->
let pdf =
Cpdfmetadata.copy_id
args.keepversion
(pdfread_pdf_of_file (optstring u) (optstring o) getfrom)
(get_pdf_from_input_kind input args.op k)
in
write_pdf false pdf
| _ -> error "copy-id: No input file specified"
end
| Some (ThinLines w) ->
let pdf = get_single_pdf args.op false in
let range = parse_pagespec_allow_empty pdf (get_pagespec ()) in
write_pdf false (Cpdftweak.thinlines range w pdf)
| Some BlackText ->
let pdf = get_single_pdf args.op false in
let range = parse_pagespec_allow_empty pdf (get_pagespec ()) in
write_pdf false (Cpdftweak.blacktext args.color range pdf)
| Some BlackLines ->
let pdf = get_single_pdf args.op false in
let range = parse_pagespec_allow_empty pdf (get_pagespec ()) in
write_pdf false (Cpdftweak.blacklines args.color range pdf)
| Some BlackFills ->
let pdf = get_single_pdf args.op false in
let range = parse_pagespec_allow_empty pdf (get_pagespec ()) in
write_pdf false (Cpdftweak.blackfills args.color range pdf)
| Some RemoveAnnotations ->
let pdf = get_single_pdf args.op false in
let range = parse_pagespec_allow_empty pdf (get_pagespec ()) in
write_pdf false (Cpdfannot.remove_annotations range pdf)
| Some (CopyAnnotations getfrom) ->
begin match args.inputs with
| [(k, _, u, o, _, _) as input] ->
let input_pdf = get_pdf_from_input_kind input args.op k in
let range = parse_pagespec_allow_empty input_pdf (get_pagespec ()) in
Cpdfannot.copy_annotations
range
(pdfread_pdf_of_file (optstring u) (optstring o) getfrom)
input_pdf;
write_pdf false input_pdf
| _ -> error "copy-annotations: No input file specified"
end
| Some (SetAnnotations json) ->
let data = Pdfio.input_of_channel (open_in_bin json) in
let pdf = get_single_pdf args.op false in
Cpdfannot.set_annotations_json pdf data;
write_pdf false pdf
| Some ListAnnotations ->
let pdf = get_single_pdf args.op true in
let range = parse_pagespec_allow_empty pdf (get_pagespec ()) in
if args.format_json then
flprint (Pdfio.string_of_bytes (Cpdfannot.get_annotations_json pdf range))
else
Cpdfannot.list_annotations range args.encoding pdf
| Some Shift ->
let pdf = get_single_pdf args.op false in
let range = parse_pagespec_allow_empty pdf (get_pagespec ()) in
let dxdylist = Cpdfcoord.parse_coordinates pdf args.coord in
write_pdf false (Cpdfpage.shift_pdf ~fast:args.fast dxdylist pdf range)
| Some ShiftBoxes ->
let pdf = get_single_pdf args.op false in
let range = parse_pagespec_allow_empty pdf (get_pagespec ()) in
let dxdylist = Cpdfcoord.parse_coordinates pdf args.coord in
write_pdf false (Cpdfpage.shift_boxes dxdylist pdf range)
| Some Scale ->
let pdf = get_single_pdf args.op false in
let range = parse_pagespec_allow_empty pdf (get_pagespec ()) in
let sxsylist = Cpdfcoord.parse_coordinates pdf args.coord in
write_pdf false (Cpdfpage.scale_pdf ~fast:args.fast sxsylist pdf range)
| Some ScaleToFit ->
let pdf = get_single_pdf args.op false in
let range = parse_pagespec_allow_empty pdf (get_pagespec ()) in
warn_prerotate range pdf;
let pdf = if args.prerotate then prerotate range pdf else pdf in
let xylist = Cpdfcoord.parse_coordinates pdf args.coord
and scale = args.scale in
write_pdf false (Cpdfpage.scale_to_fit_pdf ~fast:args.fast args.position scale xylist args.op pdf range)
| Some Stretch ->
let pdf = get_single_pdf args.op false in
let range = parse_pagespec_allow_empty pdf (get_pagespec ()) in
warn_prerotate range pdf;
let pdf = if args.prerotate then prerotate range pdf else pdf in
let xylist = Cpdfcoord.parse_coordinates pdf args.coord in
write_pdf false (Cpdfpage.stretch ~fast:args.fast xylist pdf range)
| Some CenterToFit ->
let pdf = get_single_pdf args.op false in
let range = parse_pagespec_allow_empty pdf (get_pagespec ()) in
warn_prerotate range pdf;
let pdf = if args.prerotate then prerotate range pdf else pdf in
let xylist = Cpdfcoord.parse_coordinates pdf args.coord in
write_pdf false (Cpdfpage.center_to_fit xylist pdf range)
| Some (ScaleContents scale) ->
let pdf = get_single_pdf args.op false in
let range = parse_pagespec_allow_empty pdf (get_pagespec ()) in
write_pdf false (Cpdfpage.scale_contents ~fast:args.fast args.position scale pdf range)
| Some ListAttachedFiles ->
let pdf = get_single_pdf args.op false in
let attachments = Cpdfattach.list_attached_files pdf in
iter
(fun a -> Printf.printf "%i %s\n" a.Cpdfattach.pagenumber a.Cpdfattach.name)
attachments;
flprint ""
| Some DumpAttachedFiles ->
let pdf = get_single_pdf args.op false in
begin match args.out with
| NoOutputSpecified -> Cpdfattach.dump_attached_files pdf ""
| File n -> Cpdfattach.dump_attached_files pdf n
| Stdout -> error "Can't dump attachments to stdout"
end
| Some RemoveAttachedFiles ->
write_pdf false (Cpdfattach.remove_attached_files (get_single_pdf args.op false))
| Some (AttachFile files) ->
begin match args.inputs with
| [(k, _, _, _, _, _) as input] ->
let pdf = get_pdf_from_input_kind input args.op k in
let topage =
try
match args.topage with
| None -> None
| Some "end" -> Some (Pdfpage.endpage pdf)
| Some s -> Some (int_of_string s)
with _ -> error "Bad -to-page"
in
let pdf = fold_left (Cpdfattach.attach_file args.keepversion topage) pdf (rev files) in
write_pdf false pdf
| _ -> error "attach file: No input file specified"
end
| Some PadBefore ->
let pdf = get_single_pdf args.op false in
let range = parse_pagespec_allow_empty pdf (get_pagespec ()) in
let padwith =
match args.padwith with
None -> None
| Some filename -> Some (pdfread_pdf_of_file None None filename)
in
write_pdf false (Cpdfpad.padbefore ?padwith range pdf)
| Some PadAfter ->
let pdf = get_single_pdf args.op false in
let range = parse_pagespec_allow_empty pdf (get_pagespec ()) in
let padwith =
match args.padwith with
None -> None
| Some filename -> Some (pdfread_pdf_of_file None None filename)
in
write_pdf false (Cpdfpad.padafter ?padwith range pdf)
| Some (PadEvery n) ->
let pdf = get_single_pdf args.op false in
let range =
match keep (function m -> m mod n = 0) (ilist 1 (Pdfpage.endpage pdf)) with
| [] -> []
| l -> if last l = Pdfpage.endpage pdf then all_but_last l else l
in
let padwith =
match args.padwith with
None -> None
| Some filename -> Some (pdfread_pdf_of_file None None filename)
in
write_pdf false (Cpdfpad.padafter ?padwith range pdf)
| Some (PadMultiple n) ->
let pdf = get_single_pdf args.op false in
write_pdf false (Cpdfpad.padmultiple n pdf)
| Some (PadMultipleBefore n) ->
let pdf = get_single_pdf args.op false in
write_pdf false (Cpdfpad.padmultiple (-n) pdf)
| Some Draft ->
let pdf = get_single_pdf args.op false in
let range = parse_pagespec_allow_empty pdf (get_pagespec ()) in
write_pdf false (Cpdfdraft.draft args.removeonly args.boxes range pdf)
| Some (AddText text) ->
let pdf = get_single_pdf args.op false in
let range = parse_pagespec_allow_empty pdf (get_pagespec ()) in
let cpdffont = embed_font () in
warn_prerotate range pdf;
let pdf =
if args.prerotate then prerotate range pdf else pdf
and filename =
match args.inputs with
| (InFile inname, _, _, _, _, _)::_ -> inname
| _ -> ""
in
write_pdf false
(Cpdfaddtext.addtexts
args.linewidth args.outline args.fast args.fontname
cpdffont args.bates args.batespad args.color args.position
args.linespacing args.fontsize args.underneath text range
args.relative_to_cropbox args.opacity
args.justification args.midline args.topline filename
args.extract_text_font_size args.coord ~raw:(args.encoding = Raw) pdf)
| Some RemoveText ->
let pdf = get_single_pdf args.op false in
let range = parse_pagespec_allow_empty pdf (get_pagespec ()) in
write_pdf false (Cpdfremovetext.removetext range pdf)
| Some AddRectangle ->
let pdf = get_single_pdf args.op false in
let range = parse_pagespec_allow_empty pdf (get_pagespec ()) in
write_pdf false
(Cpdfaddtext.addrectangle
args.fast (Cpdfcoord.parse_coordinate pdf args.coord)
args.color args.outline args.linewidth args.opacity args.position
args.relative_to_cropbox args.underneath range pdf)
| Some (AddBookmarks file) ->
write_pdf false
(Cpdfbookmarks.add_bookmarks ~json:args.format_json true (Pdfio.input_of_channel (open_in_bin file))
(get_single_pdf args.op false))
| Some RemoveBookmarks ->
write_pdf false (Pdfmarks.remove_bookmarks (get_single_pdf args.op false))
| Some TwoUp ->
write_pdf false (Cpdfimpose.twoup ~process_struct_tree:args.process_struct_trees args.fast (get_single_pdf args.op false))
| Some TwoUpStack ->
write_pdf false (Cpdfimpose.twoup_stack ~process_struct_tree:args.process_struct_trees args.fast (get_single_pdf args.op false))
| Some Impose fit ->
let pdf = get_single_pdf args.op false in
let x, y = Cpdfcoord.parse_coordinate pdf args.coord in
if not fit && (x < 0.0 || y < 0.0) then error "Negative imposition parameters not allowed." else
write_pdf false
(Cpdfimpose.impose ~process_struct_tree:args.process_struct_trees ~x ~y ~fit ~columns:args.impose_columns ~rtl:args.impose_rtl ~btt:args.impose_btt ~center:args.impose_center
~margin:args.impose_margin ~spacing:args.impose_spacing ~linewidth:args.impose_linewidth ~fast:args.fast pdf)
| Some (StampOn over) ->
let overpdf =
match over with
| "stamp_use_stdin" -> pdf_of_stdin "" ""
| x -> pdfread_pdf_of_file None None x
in
let pdf = get_single_pdf args.op false in
let range = parse_pagespec_allow_empty pdf (get_pagespec ()) in
let pdf =
Cpdfpage.stamp
~process_struct_tree:args.process_struct_trees args.relative_to_cropbox args.position args.topline args.midline args.fast
args.scale_stamp_to_fit true range overpdf pdf
in
write_pdf false pdf
| Some (StampUnder under) ->
let underpdf =
match under with
| "stamp_use_stdin" -> pdf_of_stdin "" ""
| x -> pdfread_pdf_of_file None None x
in
let pdf = get_single_pdf args.op false in
let range = parse_pagespec_allow_empty pdf (get_pagespec ()) in
let pdf =
Cpdfpage.stamp
~process_struct_tree:args.process_struct_trees args.relative_to_cropbox args.position args.topline args.midline args.fast
args.scale_stamp_to_fit false range underpdf pdf
in
write_pdf false pdf
| Some (CombinePages over) ->
let underpdf = get_single_pdf args.op false in
let overpdf = pdfread_pdf_of_file None None over in
warn_prerotate (parse_pagespec underpdf "all") underpdf;
warn_prerotate (parse_pagespec overpdf "all") overpdf;
write_pdf false
(Cpdfpage.combine_pages
~process_struct_tree:args.process_struct_trees
args.fast
(prerotate (parse_pagespec underpdf "all") underpdf)
(prerotate (parse_pagespec overpdf "all") overpdf)
args.scale_stamp_to_fit args.underneath)
| Some Encrypt ->
let pdf = get_single_pdf args.op false in
let pdf = Cpdfsqueeze.recompress_pdf pdf
and encryption = build_enc () in
Pdf.remove_unreferenced pdf;
if not args.keepversion then
begin
let newversion =
match args.crypt_method with
"40bit" -> 1 | "128bit" -> 4 | "AES" -> 6 | "AES256" | "AES256ISO" -> 7 | _ -> 0
in
let newversion = if args.create_objstm then 5 else newversion in
if pdf.Pdf.major = 1 then pdf.Pdf.minor <- max pdf.Pdf.minor newversion
end;
write_pdf ~encryption false pdf
| Some Decrypt ->
args.recrypt <- false;
write_pdf false (get_single_pdf args.op false)
| Some RemoveMetadata ->
write_pdf false (Cpdfmetadata.remove_metadata (get_single_pdf args.op false))
| Some ExtractImages ->
let output_spec =
begin match args.out with
| File output_spec -> output_spec
| _ -> ""
end
in
let pdf = get_single_pdf args.op true in
let range = parse_pagespec_allow_empty pdf (get_pagespec ()) in
Cpdfimage.extract_images ~raw:(args.encoding = Cpdfmetadata.Raw) ?path_to_p2p:(match args.path_to_p2p with "" -> None | x -> Some x) ?path_to_im:(match args.path_to_im with "" -> None | x -> Some x) args.encoding args.dedup args.dedup_per_page pdf range output_spec
| Some (ImageResolution f) ->
let pdf = get_single_pdf args.op true in
let range = parse_pagespec_allow_empty pdf (get_pagespec ()) in
if args.format_json then
flprint (Pdfio.string_of_bytes (Cpdfimage.image_resolution_json pdf range f))
else
let images = Cpdfimage.image_resolution pdf range f in
iter
(function (pagenum, xobject, w, h, wdpi, hdpi, objnum) ->
Printf.printf "%i, %s, %i, %i, %f, %f, %i\n" pagenum xobject w h wdpi hdpi objnum)
images
| Some ListImages ->
let pdf = get_single_pdf args.op true in
let range = parse_pagespec_allow_empty pdf (get_pagespec ()) in
let json = Cpdfimage.images pdf range in
if args.format_json then
flprint (Cpdfyojson.Safe.pretty_to_string json)
else
begin match json with
| `List l ->
iter
(function (`Assoc [(_, `Int i); (_, `List pages); (_, `String name); (_, `Int w); (_, `Int h); (_, `Int size); (_, bpc); (_, cs); (_, filter)]) ->
let pages = combine_with_spaces (map (function `Int i -> string_of_int i | _ -> "") pages) in
let filter = match filter with `String s -> s | _ -> "none" in
let bpc = match bpc with `Int bpc -> string_of_int bpc | _ -> "none" in
let cs = match cs with `String cs -> cs | _ -> "none" in
flprint (Printf.sprintf "%i, %s, %s, %i, %i, %i, %s, %s, %s\n" i pages name w h size bpc cs filter)
| _ -> ())
l
| _ -> ()
end
| Some MissingFonts ->
let pdf = get_single_pdf args.op true in
let range = parse_pagespec_allow_empty pdf (get_pagespec ()) in
Cpdffont.missing_fonts pdf range
| Some ExtractText ->
let pdf = get_single_pdf args.op true in
let range = parse_pagespec_allow_empty pdf (get_pagespec ()) in
let text = Cpdfextracttext.extract_text args.extract_text_font_size pdf range in
begin match args.out with
| File filename ->
let fh = open_out_bin filename in
output_string fh text;
close_out fh
| NoOutputSpecified | Stdout ->
print_string text;
print_newline ()
end
| Some AddPageLabels ->
let pdf = get_single_pdf args.op false in
let range = parse_pagespec pdf (get_pagespec ()) in
Cpdfpagelabels.add_page_labels
pdf args.labelsprogress args.labelstyle args.labelprefix args.labelstartval range;
write_pdf false pdf
| Some RemovePageLabels ->
let pdf = get_single_pdf args.op false in
Pdfpagelabels.remove pdf;
write_pdf false pdf
| Some PrintPageLabels ->
let pdf = get_single_pdf args.op true in
if args.format_json then
let json_of_pagelabel l =
`Assoc
[("labelstyle", `String (Pdfpagelabels.string_of_labelstyle l.Pdfpagelabels.labelstyle));
("labelprefix", begin match l.Pdfpagelabels.labelprefix with None -> `Null | Some s -> `String s end);
("startpage", `Int l.Pdfpagelabels.startpage);
("startvalue", `Int l.Pdfpagelabels.startvalue)]
in
flprint (Cpdfyojson.Safe.pretty_to_string (`List (map json_of_pagelabel (Pdfpagelabels.read pdf))))
else
iter
print_string
(map Pdfpagelabels.string_of_pagelabel (Pdfpagelabels.read pdf))
| Some (RemoveDictEntry key) ->
let pdf = get_single_pdf args.op true in
Cpdfutil.remove_dict_entry pdf key args.dict_entry_search;
write_pdf false pdf
| Some (ReplaceDictEntry key) ->
let pdf = get_single_pdf args.op true in
Cpdfutil.replace_dict_entry pdf key args.replace_dict_entry_value args.dict_entry_search;
write_pdf false pdf
| Some (PrintDictEntry key) ->
let pdf = get_single_pdf args.op true in
if args.format_json then
print_string (Pdfio.string_of_bytes (Cpdftweak.get_dict_entries ~utf8:(args.encoding = Cpdfmetadata.UTF8) pdf key))
else
Cpdftweak.print_dict_entry ~utf8:(args.encoding = Cpdfmetadata.UTF8) pdf key
| Some ListSpotColours ->
let pdf = get_single_pdf args.op false in
Cpdfspot.list_spot_colours pdf
| Some RemoveClipping ->
let pdf = get_single_pdf args.op false in
let range = parse_pagespec_allow_empty pdf (get_pagespec ()) in
write_pdf false (Cpdftweak.remove_clipping pdf range)
| Some CreateMetadata ->
let pdf = get_single_pdf args.op false in
write_pdf false (Cpdfmetadata.create_metadata pdf)
| Some EmbedMissingFonts ->
let fi =
match args.inputs with
[(InFile fi, _, _, _, _, _)] -> fi
| _ -> error "Input method not supported for -embed-missing-fonts"
in
let fo =
match args.out with
File fo -> fo
| _ -> error "Output method not supported for -embed-missing-fonts"
in
Cpdffont.embed_missing_fonts args.path_to_ghostscript args.gs_quiet fi fo
| Some (BookmarksOpenToLevel n) ->
let pdf = get_single_pdf args.op false in
write_pdf false (Cpdfbookmarks.bookmarks_open_to_level n pdf)
| Some CreatePDF ->
begin match args.subformat with
| Some Cpdfua.PDFUA1 ->
begin match args.title with None -> error "Provide -title" | _ -> () end;
let pdf = Cpdfua.create_pdfua1 (unopt args.title) args.createpdf_pagesize args.createpdf_pages in
write_pdf false pdf
| Some Cpdfua.PDFUA2 ->
begin match args.title with None -> error "Provide -title" | _ -> () end;
let pdf = Cpdfua.create_pdfua2 (unopt args.title) args.createpdf_pagesize args.createpdf_pages in
write_pdf false pdf
| None ->
let pdf = Cpdfcreate.blank_document_paper args.createpdf_pagesize args.createpdf_pages in
write_pdf false pdf
end
| Some RemoveAllText ->
let pdf = get_single_pdf args.op false in
let range = parse_pagespec_allow_empty pdf (get_pagespec ()) in
write_pdf false (Cpdfremovetext.remove_all_text range pdf)
| Some ShowBoxes ->
let pdf = get_single_pdf args.op false in
let range = parse_pagespec_allow_empty pdf (get_pagespec ()) in
write_pdf false (Cpdfpage.show_boxes pdf range)
| Some TrimMarks ->
let pdf = get_single_pdf args.op false in
let range = parse_pagespec_allow_empty pdf (get_pagespec ()) in
write_pdf false (Cpdfpage.trim_marks pdf range)
| Some (Postpend s | Prepend s as x) ->
let pdf = get_single_pdf args.op false in
let range = parse_pagespec_allow_empty pdf (get_pagespec ()) in
let before = match x with Prepend _ -> true | _ -> false in
write_pdf false (Cpdftweak.append_page_content s before args.fast range pdf)
| Some OutputJSON ->
let pdf = get_single_pdf args.op false in
write_json args.out pdf
| Some OCGCoalesce ->
let pdf = get_single_pdf args.op false in
Cpdfocg.ocg_coalesce pdf;
write_pdf false pdf
| Some OCGList ->
let pdf = get_single_pdf args.op true in
Cpdfocg.ocg_list pdf
| Some OCGRename ->
let pdf = get_single_pdf args.op false in
Cpdfocg.ocg_rename args.ocgrenamefrom args.ocgrenameto pdf;
write_pdf false pdf
| Some OCGOrderAll ->
let pdf = get_single_pdf args.op false in
Cpdfocg.ocg_order_all pdf;
write_pdf false pdf
| Some (StampAsXObject stamp) ->
let stamp_pdf =
match stamp with
| "stamp_use_stdin" -> pdf_of_stdin "" ""
| x -> pdfread_pdf_of_file None None x
in
let pdf = get_single_pdf args.op false in
let range = parse_pagespec_allow_empty pdf (get_pagespec ()) in
let pdf, xobj_name =
Cpdfxobject.stamp_as_xobject pdf range stamp_pdf
in
Printf.printf "%s\n" xobj_name;
flush stdout;
write_pdf false pdf
| Some (PrintFontEncoding fontname) ->
let pdf = get_single_pdf args.op true in
Cpdffont.print_font_table pdf fontname args.copyfontpage
| Some TableOfContents ->
let pdf = get_single_pdf args.op false in
let cpdffont = embed_font () in
let pdf =
Cpdftoc.typeset_table_of_contents
~font:cpdffont ~fontsize:args.fontsize ~title:args.toc_title
~bookmark:args.toc_bookmark ~dotleader:args.dot_leader ~process_struct_tree:args.process_struct_trees ?subformat:args.subformat pdf
in
write_pdf false pdf
| Some (Typeset filename) ->
let text = Pdfio.bytes_of_input_channel (open_in_bin filename) in
let cpdffont = embed_font () in
let pdf = Cpdftexttopdf.typeset ~process_struct_tree:args.process_struct_trees
?subformat:args.subformat ?title:args.title ~font:cpdffont ~papersize:args.createpdf_pagesize ~fontsize:args.fontsize text in
write_pdf false pdf
| Some (TextWidth s) ->
let rawwidth =
match args.font with
| StandardFont f ->
Pdfstandard14.textwidth false WinAnsiEncoding f s
| _ ->
error "-text-width only works for the standard 14 fonts"
in
let w = (float rawwidth *. args.fontsize) /. 1000. in
Printf.printf "%f\n" w
| Some Draw ->
let pdf = get_single_pdf args.op false in
let range = parse_pagespec_allow_empty pdf (get_pagespec ()) in
let ops = match !Cpdfdrawcontrol.drawops with [("_MAIN", ops)] -> rev ops | _ -> error "not enough -end-xobj or -et" in
write_pdf
false
(Cpdfdraw.draw ~struct_tree:args.draw_struct_tree ~fast:args.fast ~underneath:args.underneath ~filename:args.original_filename ~bates:args.bates ~batespad:args.batespad range pdf ops)
| Some (Composition json) ->
let pdf = get_single_pdf args.op false in
let filesize =
match args.inputs with
| (InFile inname, _, _, _, _, _)::_ -> filesize inname
| _ -> 0
in
Cpdfcomposition.show_composition filesize json pdf
| Some (Chop (x, y)) ->
let pdf = get_single_pdf args.op false in
let range = parse_pagespec_allow_empty pdf (get_pagespec ()) in
write_pdf false (Cpdfchop.chop ~x ~y ~columns:args.impose_columns ~btt:args.impose_btt ~rtl:args.impose_rtl pdf range)
| Some (ChopHV (is_h, line)) ->
let pdf = get_single_pdf args.op false in
let range = parse_pagespec_allow_empty pdf (get_pagespec ()) in
write_pdf false (Cpdfchop.chop_hv ~is_h ~line ~columns:args.impose_columns pdf range)
| Some ProcessImages ->
let pdf = get_single_pdf args.op false in
let range = parse_pagespec_allow_empty pdf (get_pagespec ()) in
Cpdfimage.process
~q:args.jpegquality ~qlossless:args.jpegqualitylossless ~onebppmethod:args.onebppmethod ~jbig2_lossy_threshold:args.jbig2_lossy_threshold
~length_threshold:args.length_threshold ~percentage_threshold:args.percentage_threshold ~pixel_threshold:args.pixel_threshold
~dpi_threshold:args.dpi_threshold ~factor:args.resample_factor ~interpolate:args.resample_interpolate
~jpeg_to_jpeg_scale:args.jpegtojpegscale ~jpeg_to_jpeg_dpi:args.jpegtojpegdpi
~path_to_jbig2enc:args.path_to_jbig2enc ~path_to_convert:args.path_to_im range pdf;
write_pdf false pdf
| Some (ExtractStream s) ->
let pdf = get_single_pdf args.op true in
extract_stream pdf args.extract_stream_decompress s
| Some (ReplaceStream s) ->
let pdf = get_single_pdf args.op false in
Cpdftweak.replace_stream pdf s args.replace_stream_with;
write_pdf false pdf
| Some (PrintObj s) ->
let pdf = get_single_pdf args.op true in
print_obj args.format_json pdf s
| Some (ReplaceObj (a, b)) ->
let pdf = get_single_pdf args.op false in
let pdfobj = pdf_or_json b in
Cpdftweak.replace_obj pdf a pdfobj;
write_pdf false pdf
| Some (RemoveObj s) ->
let pdf = get_single_pdf args.op true in
Cpdftweak.remove_obj pdf s;
write_pdf false pdf
| Some (Verify standard) ->
begin match standard with
| "PDF/UA-1(matterhorn)" ->
let pdf = get_single_pdf args.op false in
let testname = match args.verify_single with None -> "" | Some x -> x in
if args.format_json
then flprint (Cpdfyojson.Safe.pretty_to_string (Cpdfua.test_matterhorn_json pdf testname))
else Cpdfua.test_matterhorn_print pdf testname
| _ -> error "Unknown verification type."
end
| Some (MarkAs standard) ->
begin match standard with
| Cpdfua.PDFUA1 ->
let pdf = get_single_pdf args.op false in
Cpdfua.mark pdf;
write_pdf false pdf
| Cpdfua.PDFUA2 ->
let pdf = get_single_pdf args.op false in
Cpdfua.mark2 2024 pdf;
write_pdf false pdf
end
| Some (RemoveMark standard) ->
begin match standard with
| Cpdfua.PDFUA1 | Cpdfua.PDFUA2 ->
let pdf = get_single_pdf args.op false in
Cpdfua.remove_mark pdf;
write_pdf false pdf
end
| Some PrintStructTree ->
let pdf = get_single_pdf args.op true in
Cpdfua.print_struct_tree pdf
| Some ExtractStructTree ->
let pdf = get_single_pdf args.op true in
let json = Cpdfua.extract_struct_tree pdf in
json_to_output json args.out
| Some (ReplaceStructTree s) ->
let pdf = get_single_pdf args.op false in
let json = Cpdfyojson.Safe.from_file s in
Cpdfua.replace_struct_tree pdf json;
write_pdf false pdf
| Some RemoveStructTree ->
let pdf = get_single_pdf args.op false in
let pdf = Cpdfpage.remove_struct_tree pdf in
write_pdf false pdf
| Some MarkAsArtifact ->
let pdf = get_single_pdf args.op false in
let pdf = Cpdfpage.mark_all_as_artifact pdf in
write_pdf false pdf
| Some (SetLanguage s) ->
let pdf = get_single_pdf args.op false in
Cpdfmetadata.set_language pdf s;
write_pdf false pdf
| Some Redact ->
let pdf = get_single_pdf args.op false in
let range = parse_pagespec_allow_empty pdf (get_pagespec ()) in
write_pdf false (Cpdfpage.redact ~process_struct_tree:args.process_struct_trees pdf range)
| Some Rasterize ->
let pdf = get_single_pdf args.op false in
let range = parse_pagespec_allow_empty pdf (get_pagespec ()) in
write_pdf false (rasterize args.rast_antialias args.rast_downsample args.rast_device args.rast_res args.rast_annots args.rast_jpeg_quality pdf range)
| Some OutputImage ->
let spec = match args.out with File spec -> spec | _ -> error "Output must be to a file" in
let pdf = get_single_pdf args.op false in
let range = parse_pagespec_allow_empty pdf (get_pagespec ()) in
write_images args.rast_device args.rast_res args.rast_jpeg_quality args.tobox args.rast_annots args.rast_antialias args.rast_downsample spec pdf range
(* Advise the user if a combination of command line flags makes little sense,
or error out if it make no sense at all. *)
let check_command_line () =
if args.gs_malformed && !Pdfread.error_on_malformed then
error "Setting both -gs-malformed and -error-on-malformed makes no sense"
let parse_argv () s specs anon_fun usage_msg =
if args.debug then
Array.iter (fun s -> Pdfe.log (Printf.sprintf "arg: %s\n" s)) Sys.argv;
Arg.parse_argv ~current:(ref 0) s specs anon_fun usage_msg;
check_command_line ()
let align_specs s =
Arg.align s
(* The old -control mechanism clashed with AND, but must be retained for
backwards compatibility. There is a new mechanism -args file which performs
direct textual substitution of the file, before any expansion of ANDs *)
let rec expand_args_inner prev = function
[] -> rev prev
| "-args"::filename::r ->
expand_args_inner (rev (parse_control_file filename) @ prev) r
| "-args-json"::filename::r ->
expand_args_inner (rev (parse_control_file_json filename) @ prev) r
| h::t -> expand_args_inner (h::prev) t
let expand_args argv =
let l = Array.to_list argv in
Array.of_list (expand_args_inner [] l)
let gs_malformed_force fi fo =
if args.path_to_ghostscript = "" then begin
Pdfe.log "Please supply path to gs with -gs\n";
exit 2
end;
let gscall =
Filename.quote_command args.path_to_ghostscript
((if args.gs_quiet then ["-dQUIET"] else []) @
["-dNOPAUSE"; "-sDEVICE=pdfwrite"; "-sOUTPUTFILE=" ^ fo; "-dBATCH"; fi])
in
match Sys.command gscall with
| 0 -> exit 0
| _ -> Pdfe.log "Failed to mend file.\n"; exit 2
let process_env_vars () =
match Sys.getenv_opt "CPDF_DEBUG" with
| Some "true" -> args.debug <- true
| Some "false" -> args.debug <- false
| _ -> ()
(* Main function. *)
let go_withargv argv =
(* Check for the standalone -gs-malformed-force special command line. This
* has exactly one file input and exactly one output and just -gs <gs>
* -gs-malformed-force between. *)
match argv with
| [|_|] -> print_version ()
| [|_; inputfilename; "-gs"; gslocation; "-gs-malformed-force"; "-o"; outputfilename|] ->
args.path_to_ghostscript <- gslocation;
ignore (gs_malformed_force inputfilename outputfilename);
exit 0
| [|_; inputfilename; "-gs"; gslocation; "-gs-malformed-force"; "-o"; outputfilename; "-gs-quiet"|] ->
args.path_to_ghostscript <- gslocation;
args.gs_quiet <- true;
ignore (gs_malformed_force inputfilename outputfilename);
exit 0
| _ ->
Hashtbl.clear filenames;
if demo then
flprint "This demo functions normally, but is for evaluation only. https://www.coherentpdf.com/\n";
try
(* Pre-expand -args *)
let argv = expand_args argv in
(* Split the arguments into sets either side of ANDs *)
let sets =
let args =
(map (fun l -> "cpdf"::l) (split_around (eq "AND") (tl (Array.to_list argv))))
in
match args with
| [] -> []
| _ -> combine (map Array.of_list args) (map (eq (length args)) (ilist 1 (length args)))
in
iter
(fun (s, islast) ->
(*Printf.printf "AND:%b, %s\n" islast (Array.fold_left (fun x y -> x ^ " " ^ y) "" s);
flprint "\n";*)
reset_arguments ();
Cpdfdrawcontrol.drawops := [("_MAIN", [])];
process_env_vars ();
parse_argv () s (align_specs specs) anon_fun usage_msg;
let addrange pdf = AlreadyInMemory (pdf, "fromAND"), args.dashrange, "", "", ref false, None in
args.inputs <- rev (map addrange !output_pdfs) @ rev args.inputs;
output_pdfs := [];
go ())
sets;
flush stdout; (*r for Windows *)
exit 0
with
| Arg.Bad s ->
Pdfe.log
(implode (takewhile (neq '\n') (explode s)) ^ " Use -help for help.\n\n");
if not !stay_on_error then exit 2 else raise StayOnError
| Arg.Help _ ->
Arg.usage (align_specs specs) usage_msg;
flush stderr (*r for Windows *)
| Sys_error s as e ->
Pdfe.log (s ^ "\n\n");
if not !stay_on_error then
(if args.debug then raise e else exit 2)
else raise StayOnError
| Pdf.PDFError s as e ->
Pdfe.log
("cpdf encountered an error. Technical details follow:\n\n" ^ s ^ "\n\n");
if not !stay_on_error then
if args.debug then raise e else exit 2
else
raise StayOnError
| Cpdferror.SoftError s -> soft_error s
| Cpdferror.HardError s -> error s
| e ->
Pdfe.log
("cpdf encountered an unexpected error. Technical Details follow:\n" ^
Printexc.to_string e ^ "\n\n");
if not !stay_on_error then
(if args.debug then raise e else exit 2) else raise StayOnError
let go () =
go_withargv Sys.argv
|