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
|
/*
* $Id: PdfReader.java 3948 2009-06-03 15:17:22Z blowagie $
*
* Copyright 2001, 2002 Paulo Soares
*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the License.
*
* The Original Code is 'iText, a free JAVA-PDF library'.
*
* The Initial Developer of the Original Code is Bruno Lowagie. Portions created by
* the Initial Developer are Copyright (C) 1999, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 by Paulo Soares. All Rights Reserved.
*
* Contributor(s): all the names of the contributors are added in the source code
* where applicable.
*
* Alternatively, the contents of this file may be used under the terms of the
* LGPL license (the "GNU LIBRARY GENERAL PUBLIC LICENSE"), in which case the
* provisions of LGPL are applicable instead of those above. If you wish to
* allow use of your version of this file only under the terms of the LGPL
* License and not to allow others to use your version of this file under
* the MPL, indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by the LGPL.
* If you do not delete the provisions above, a recipient may use your version
* of this file under either the MPL or the GNU LIBRARY GENERAL PUBLIC LICENSE.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the MPL as stated above or under the terms of the GNU
* Library General Public License as published by the Free Software Foundation;
* either version 2 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Library general Public License for more
* details.
*
* If you didn't download this code from the following link, you should check if
* you aren't using an obsolete version:
* http://www.lowagie.com/iText/
*/
package com.lowagie.text.pdf;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.zip.InflaterInputStream;
import java.util.Stack;
import java.security.Key;
import java.security.MessageDigest;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import com.lowagie.text.ExceptionConverter;
import com.lowagie.text.PageSize;
import com.lowagie.text.Rectangle;
import com.lowagie.text.exceptions.BadPasswordException;
import com.lowagie.text.exceptions.InvalidPdfException;
import com.lowagie.text.exceptions.UnsupportedPdfException;
import com.lowagie.text.pdf.interfaces.PdfViewerPreferences;
import com.lowagie.text.pdf.internal.PdfViewerPreferencesImp;
import org.bouncycastle.cms.CMSEnvelopedData;
import org.bouncycastle.cms.RecipientInformation;
import org.bouncycastle.cms.jcajce.JceKeyTransEnvelopedRecipient;
/** Reads a PDF document.
* @author Paulo Soares (psoares@consiste.pt)
* @author Kazuya Ujihara
*/
public class PdfReader implements PdfViewerPreferences {
static final PdfName pageInhCandidates[] = {
PdfName.MEDIABOX, PdfName.ROTATE, PdfName.RESOURCES, PdfName.CROPBOX
};
static final byte endstream[] = PdfEncodings.convertToBytes("endstream", null);
static final byte endobj[] = PdfEncodings.convertToBytes("endobj", null);
protected PRTokeniser tokens;
// Each xref pair is a position
// type 0 -> -1, 0
// type 1 -> offset, 0
// type 2 -> index, obj num
protected int xref[];
protected HashMap objStmMark;
protected IntHashtable objStmToOffset;
protected boolean newXrefType;
private ArrayList xrefObj;
PdfDictionary rootPages;
protected PdfDictionary trailer;
protected PdfDictionary catalog;
protected PageRefs pageRefs;
protected PRAcroForm acroForm = null;
protected boolean acroFormParsed = false;
protected boolean encrypted = false;
protected boolean rebuilt = false;
protected int freeXref;
protected boolean tampered = false;
protected int lastXref;
protected int eofPos;
protected char pdfVersion;
protected PdfEncryption decrypt;
protected byte password[] = null; //added by ujihara for decryption
protected Key certificateKey = null; //added by Aiken Sam for certificate decryption
protected Certificate certificate = null; //added by Aiken Sam for certificate decryption
protected String certificateKeyProvider = null; //added by Aiken Sam for certificate decryption
private boolean ownerPasswordUsed;
protected ArrayList strings = new ArrayList();
protected boolean sharedStreams = true;
protected boolean consolidateNamedDestinations = false;
protected int rValue;
protected int pValue;
private int objNum;
private int objGen;
private int fileLength;
private boolean hybridXref;
private int lastXrefPartial = -1;
private boolean partial;
private PRIndirectReference cryptoRef;
private PdfViewerPreferencesImp viewerPreferences = new PdfViewerPreferencesImp();
private boolean encryptionError;
/**
* Holds value of property appendable.
*/
private boolean appendable;
protected PdfReader() {
}
/** Reads and parses a PDF document.
* @param filename the file name of the document
* @throws IOException on error
*/
public PdfReader(String filename) throws IOException {
this(filename, null);
}
/** Reads and parses a PDF document.
* @param filename the file name of the document
* @param ownerPassword the password to read the document
* @throws IOException on error
*/
public PdfReader(String filename, byte ownerPassword[]) throws IOException {
password = ownerPassword;
tokens = new PRTokeniser(filename);
readPdf();
}
/** Reads and parses a PDF document.
* @param pdfIn the byte array with the document
* @throws IOException on error
*/
public PdfReader(byte pdfIn[]) throws IOException {
this(pdfIn, null);
}
/** Reads and parses a PDF document.
* @param pdfIn the byte array with the document
* @param ownerPassword the password to read the document
* @throws IOException on error
*/
public PdfReader(byte pdfIn[], byte ownerPassword[]) throws IOException {
password = ownerPassword;
tokens = new PRTokeniser(pdfIn);
readPdf();
}
/** Reads and parses a PDF document.
* @param filename the file name of the document
* @param certificate the certificate to read the document
* @param certificateKey the private key of the certificate
* @param certificateKeyProvider the security provider for certificateKey
* @throws IOException on error
*/
public PdfReader(String filename, Certificate certificate, Key certificateKey, String certificateKeyProvider) throws IOException {
this.certificate = certificate;
this.certificateKey = certificateKey;
this.certificateKeyProvider = certificateKeyProvider;
tokens = new PRTokeniser(filename);
readPdf();
}
/** Reads and parses a PDF document.
* @param url the URL of the document
* @throws IOException on error
*/
public PdfReader(URL url) throws IOException {
this(url, null);
}
/** Reads and parses a PDF document.
* @param url the URL of the document
* @param ownerPassword the password to read the document
* @throws IOException on error
*/
public PdfReader(URL url, byte ownerPassword[]) throws IOException {
password = ownerPassword;
tokens = new PRTokeniser(new RandomAccessFileOrArray(url));
readPdf();
}
/**
* Reads and parses a PDF document.
* @param is the <CODE>InputStream</CODE> containing the document. The stream is read to the
* end but is not closed
* @param ownerPassword the password to read the document
* @throws IOException on error
*/
public PdfReader(InputStream is, byte ownerPassword[]) throws IOException {
password = ownerPassword;
tokens = new PRTokeniser(new RandomAccessFileOrArray(is));
readPdf();
}
/**
* Reads and parses a PDF document.
* @param is the <CODE>InputStream</CODE> containing the document. The stream is read to the
* end but is not closed
* @throws IOException on error
*/
public PdfReader(InputStream is) throws IOException {
this(is, null);
}
/**
* Reads and parses a pdf document. Contrary to the other constructors only the xref is read
* into memory. The reader is said to be working in "partial" mode as only parts of the pdf
* are read as needed. The pdf is left open but may be closed at any time with
* <CODE>PdfReader.close()</CODE>, reopen is automatic.
* @param raf the document location
* @param ownerPassword the password or <CODE>null</CODE> for no password
* @throws IOException on error
*/
public PdfReader(RandomAccessFileOrArray raf, byte ownerPassword[]) throws IOException {
password = ownerPassword;
partial = true;
tokens = new PRTokeniser(raf);
readPdfPartial();
}
/** Creates an independent duplicate.
* @param reader the <CODE>PdfReader</CODE> to duplicate
*/
public PdfReader(PdfReader reader) {
this.appendable = reader.appendable;
this.consolidateNamedDestinations = reader.consolidateNamedDestinations;
this.encrypted = reader.encrypted;
this.rebuilt = reader.rebuilt;
this.sharedStreams = reader.sharedStreams;
this.tampered = reader.tampered;
this.password = reader.password;
this.pdfVersion = reader.pdfVersion;
this.eofPos = reader.eofPos;
this.freeXref = reader.freeXref;
this.lastXref = reader.lastXref;
this.tokens = new PRTokeniser(reader.tokens.getSafeFile());
if (reader.decrypt != null)
this.decrypt = new PdfEncryption(reader.decrypt);
this.pValue = reader.pValue;
this.rValue = reader.rValue;
this.xrefObj = new ArrayList(reader.xrefObj);
for (int k = 0; k < reader.xrefObj.size(); ++k) {
this.xrefObj.set(k, duplicatePdfObject((PdfObject)reader.xrefObj.get(k), this));
}
this.pageRefs = new PageRefs(reader.pageRefs, this);
this.trailer = (PdfDictionary)duplicatePdfObject(reader.trailer, this);
this.catalog = trailer.getAsDict(PdfName.ROOT);
this.rootPages = catalog.getAsDict(PdfName.PAGES);
this.fileLength = reader.fileLength;
this.partial = reader.partial;
this.hybridXref = reader.hybridXref;
this.objStmToOffset = reader.objStmToOffset;
this.xref = reader.xref;
this.cryptoRef = (PRIndirectReference)duplicatePdfObject(reader.cryptoRef, this);
this.ownerPasswordUsed = reader.ownerPasswordUsed;
}
/** Gets a new file instance of the original PDF
* document.
* @return a new file instance of the original PDF document
*/
public RandomAccessFileOrArray getSafeFile() {
return tokens.getSafeFile();
}
protected PdfReaderInstance getPdfReaderInstance(PdfWriter writer) {
return new PdfReaderInstance(this, writer);
}
/** Gets the number of pages in the document.
* @return the number of pages in the document
*/
public int getNumberOfPages() {
return pageRefs.size();
}
/** Returns the document's catalog. This dictionary is not a copy,
* any changes will be reflected in the catalog.
* @return the document's catalog
*/
public PdfDictionary getCatalog() {
return catalog;
}
/** Returns the document's acroform, if it has one.
* @return the document's acroform
*/
public PRAcroForm getAcroForm() {
if (!acroFormParsed) {
acroFormParsed = true;
PdfObject form = catalog.get(PdfName.ACROFORM);
if (form != null) {
try {
acroForm = new PRAcroForm(this);
acroForm.readAcroForm((PdfDictionary)getPdfObject(form));
}
catch (Exception e) {
acroForm = null;
}
}
}
return acroForm;
}
/**
* Gets the page rotation. This value can be 0, 90, 180 or 270.
* @param index the page number. The first page is 1
* @return the page rotation
*/
public int getPageRotation(int index) {
return getPageRotation(pageRefs.getPageNRelease(index));
}
int getPageRotation(PdfDictionary page) {
PdfNumber rotate = page.getAsNumber(PdfName.ROTATE);
if (rotate == null)
return 0;
else {
int n = rotate.intValue();
n %= 360;
return n < 0 ? n + 360 : n;
}
}
/** Gets the page size, taking rotation into account. This
* is a <CODE>Rectangle</CODE> with the value of the /MediaBox and the /Rotate key.
* @param index the page number. The first page is 1
* @return a <CODE>Rectangle</CODE>
*/
public Rectangle getPageSizeWithRotation(int index) {
return getPageSizeWithRotation(pageRefs.getPageNRelease(index));
}
/**
* Gets the rotated page from a page dictionary.
* @param page the page dictionary
* @return the rotated page
*/
public Rectangle getPageSizeWithRotation(PdfDictionary page) {
Rectangle rect = getPageSize(page);
int rotation = getPageRotation(page);
while (rotation > 0) {
rect = rect.rotate();
rotation -= 90;
}
return rect;
}
/** Gets the page size without taking rotation into account. This
* is the value of the /MediaBox key.
* @param index the page number. The first page is 1
* @return the page size
*/
public Rectangle getPageSize(int index) {
return getPageSize(pageRefs.getPageNRelease(index));
}
/**
* Gets the page from a page dictionary
* @param page the page dictionary
* @return the page
*/
public Rectangle getPageSize(PdfDictionary page) {
PdfArray mediaBox = page.getAsArray(PdfName.MEDIABOX);
return getNormalizedRectangle(mediaBox);
}
/** Gets the crop box without taking rotation into account. This
* is the value of the /CropBox key. The crop box is the part
* of the document to be displayed or printed. It usually is the same
* as the media box but may be smaller. If the page doesn't have a crop
* box the page size will be returned.
* @param index the page number. The first page is 1
* @return the crop box
*/
public Rectangle getCropBox(int index) {
PdfDictionary page = pageRefs.getPageNRelease(index);
PdfArray cropBox = (PdfArray)getPdfObjectRelease(page.get(PdfName.CROPBOX));
if (cropBox == null)
return getPageSize(page);
return getNormalizedRectangle(cropBox);
}
/** Gets the box size. Allowed names are: "crop", "trim", "art", "bleed" and "media".
* @param index the page number. The first page is 1
* @param boxName the box name
* @return the box rectangle or null
*/
public Rectangle getBoxSize(int index, String boxName) {
PdfDictionary page = pageRefs.getPageNRelease(index);
PdfArray box = null;
if (boxName.equals("trim"))
box = (PdfArray)getPdfObjectRelease(page.get(PdfName.TRIMBOX));
else if (boxName.equals("art"))
box = (PdfArray)getPdfObjectRelease(page.get(PdfName.ARTBOX));
else if (boxName.equals("bleed"))
box = (PdfArray)getPdfObjectRelease(page.get(PdfName.BLEEDBOX));
else if (boxName.equals("crop"))
box = (PdfArray)getPdfObjectRelease(page.get(PdfName.CROPBOX));
else if (boxName.equals("media"))
box = (PdfArray)getPdfObjectRelease(page.get(PdfName.MEDIABOX));
if (box == null)
return null;
return getNormalizedRectangle(box);
}
/** Returns the content of the document information dictionary as a <CODE>HashMap</CODE>
* of <CODE>String</CODE>.
* @return content of the document information dictionary
*/
public HashMap getInfo() {
HashMap map = new HashMap();
PdfDictionary info = trailer.getAsDict(PdfName.INFO);
if (info == null)
return map;
for (Iterator it = info.getKeys().iterator(); it.hasNext();) {
PdfName key = (PdfName)it.next();
PdfObject obj = getPdfObject(info.get(key));
if (obj == null)
continue;
String value = obj.toString();
switch (obj.type()) {
case PdfObject.STRING: {
value = ((PdfString)obj).toUnicodeString();
break;
}
case PdfObject.NAME: {
value = PdfName.decodeName(value);
break;
}
}
map.put(PdfName.decodeName(key.toString()), value);
}
return map;
}
/** Normalizes a <CODE>Rectangle</CODE> so that llx and lly are smaller than urx and ury.
* @param box the original rectangle
* @return a normalized <CODE>Rectangle</CODE>
*/
public static Rectangle getNormalizedRectangle(PdfArray box) {
float llx = ((PdfNumber)getPdfObjectRelease(box.getPdfObject(0))).floatValue();
float lly = ((PdfNumber)getPdfObjectRelease(box.getPdfObject(1))).floatValue();
float urx = ((PdfNumber)getPdfObjectRelease(box.getPdfObject(2))).floatValue();
float ury = ((PdfNumber)getPdfObjectRelease(box.getPdfObject(3))).floatValue();
return new Rectangle(Math.min(llx, urx), Math.min(lly, ury),
Math.max(llx, urx), Math.max(lly, ury));
}
protected void readPdf() throws IOException {
try {
fileLength = tokens.getFile().length();
pdfVersion = tokens.checkPdfHeader();
try {
readXref();
}
catch (Exception e) {
try {
rebuilt = true;
rebuildXref();
lastXref = -1;
}
catch (Exception ne) {
throw new InvalidPdfException("Rebuild failed: " + ne.getMessage() + "; Original message: " + e.getMessage());
}
}
try {
readDocObj();
}
catch (Exception e) {
if (e instanceof BadPasswordException)
throw new BadPasswordException(e.getMessage());
if (rebuilt || encryptionError)
throw new InvalidPdfException(e.getMessage());
rebuilt = true;
encrypted = false;
rebuildXref();
lastXref = -1;
readDocObj();
}
strings.clear();
readPages();
eliminateSharedStreams();
removeUnusedObjects();
}
finally {
try {
tokens.close();
}
catch (Exception e) {
// empty on purpose
}
}
}
protected void readPdfPartial() throws IOException {
try {
fileLength = tokens.getFile().length();
pdfVersion = tokens.checkPdfHeader();
try {
readXref();
}
catch (Exception e) {
try {
rebuilt = true;
rebuildXref();
lastXref = -1;
}
catch (Exception ne) {
throw new InvalidPdfException("Rebuild failed: " + ne.getMessage() + "; Original message: " + e.getMessage());
}
}
readDocObjPartial();
readPages();
}
catch (IOException e) {
try{tokens.close();}catch(Exception ee){}
throw e;
}
}
private boolean equalsArray(byte ar1[], byte ar2[], int size) {
for (int k = 0; k < size; ++k) {
if (ar1[k] != ar2[k])
return false;
}
return true;
}
/**
* @throws IOException
*/
private void readDecryptedDocObj() throws IOException {
if (encrypted)
return;
PdfObject encDic = trailer.get(PdfName.ENCRYPT);
if (encDic == null || encDic.toString().equals("null"))
return;
encryptionError = true;
byte[] encryptionKey = null;
encrypted = true;
PdfDictionary enc = (PdfDictionary)getPdfObject(encDic);
String s;
PdfObject o;
PdfArray documentIDs = trailer.getAsArray(PdfName.ID);
byte documentID[] = null;
if (documentIDs != null) {
o = documentIDs.getPdfObject(0);
strings.remove(o);
s = o.toString();
documentID = com.lowagie.text.DocWriter.getISOBytes(s);
if (documentIDs.size() > 1)
strings.remove(documentIDs.getPdfObject(1));
}
// just in case we have a broken producer
if (documentID == null)
documentID = new byte[0];
byte uValue[] = null;
byte oValue[] = null;
int cryptoMode = PdfWriter.STANDARD_ENCRYPTION_40;
int lengthValue = 0;
PdfObject filter = getPdfObjectRelease(enc.get(PdfName.FILTER));
if (filter.equals(PdfName.STANDARD)) {
s = enc.get(PdfName.U).toString();
strings.remove(enc.get(PdfName.U));
uValue = com.lowagie.text.DocWriter.getISOBytes(s);
s = enc.get(PdfName.O).toString();
strings.remove(enc.get(PdfName.O));
oValue = com.lowagie.text.DocWriter.getISOBytes(s);
o = enc.get(PdfName.P);
if (!o.isNumber())
throw new InvalidPdfException("Illegal P value.");
pValue = ((PdfNumber)o).intValue();
o = enc.get(PdfName.R);
if (!o.isNumber())
throw new InvalidPdfException("Illegal R value.");
rValue = ((PdfNumber)o).intValue();
switch (rValue) {
case 2:
cryptoMode = PdfWriter.STANDARD_ENCRYPTION_40;
break;
case 3:
o = enc.get(PdfName.LENGTH);
if (!o.isNumber())
throw new InvalidPdfException("Illegal Length value.");
lengthValue = ( (PdfNumber) o).intValue();
if (lengthValue > 128 || lengthValue < 40 || lengthValue % 8 != 0)
throw new InvalidPdfException("Illegal Length value.");
cryptoMode = PdfWriter.STANDARD_ENCRYPTION_128;
break;
case 4:
PdfDictionary dic = (PdfDictionary)enc.get(PdfName.CF);
if (dic == null)
throw new InvalidPdfException("/CF not found (encryption)");
dic = (PdfDictionary)dic.get(PdfName.STDCF);
if (dic == null)
throw new InvalidPdfException("/StdCF not found (encryption)");
if (PdfName.V2.equals(dic.get(PdfName.CFM)))
cryptoMode = PdfWriter.STANDARD_ENCRYPTION_128;
else if (PdfName.AESV2.equals(dic.get(PdfName.CFM)))
cryptoMode = PdfWriter.ENCRYPTION_AES_128;
else
throw new UnsupportedPdfException("No compatible encryption found");
PdfObject em = enc.get(PdfName.ENCRYPTMETADATA);
if (em != null && em.toString().equals("false"))
cryptoMode |= PdfWriter.DO_NOT_ENCRYPT_METADATA;
break;
default:
throw new UnsupportedPdfException("Unknown encryption type R = " + rValue);
}
}
else if (filter.equals(PdfName.PUBSEC)) {
boolean foundRecipient = false;
byte[] envelopedData = null;
PdfArray recipients = null;
o = enc.get(PdfName.V);
if (!o.isNumber())
throw new InvalidPdfException("Illegal V value.");
int vValue = ((PdfNumber)o).intValue();
switch(vValue) {
case 1:
cryptoMode = PdfWriter.STANDARD_ENCRYPTION_40;
lengthValue = 40;
recipients = (PdfArray)enc.get(PdfName.RECIPIENTS);
break;
case 2:
o = enc.get(PdfName.LENGTH);
if (!o.isNumber())
throw new InvalidPdfException("Illegal Length value.");
lengthValue = ( (PdfNumber) o).intValue();
if (lengthValue > 128 || lengthValue < 40 || lengthValue % 8 != 0)
throw new InvalidPdfException("Illegal Length value.");
cryptoMode = PdfWriter.STANDARD_ENCRYPTION_128;
recipients = (PdfArray)enc.get(PdfName.RECIPIENTS);
break;
case 4:
PdfDictionary dic = (PdfDictionary)enc.get(PdfName.CF);
if (dic == null)
throw new InvalidPdfException("/CF not found (encryption)");
dic = (PdfDictionary)dic.get(PdfName.DEFAULTCRYPTFILTER);
if (dic == null)
throw new InvalidPdfException("/DefaultCryptFilter not found (encryption)");
if (PdfName.V2.equals(dic.get(PdfName.CFM))) {
cryptoMode = PdfWriter.STANDARD_ENCRYPTION_128;
lengthValue = 128;
}
else if (PdfName.AESV2.equals(dic.get(PdfName.CFM))) {
cryptoMode = PdfWriter.ENCRYPTION_AES_128;
lengthValue = 128;
}
else
throw new UnsupportedPdfException("No compatible encryption found");
PdfObject em = dic.get(PdfName.ENCRYPTMETADATA);
if (em != null && em.toString().equals("false"))
cryptoMode |= PdfWriter.DO_NOT_ENCRYPT_METADATA;
recipients = (PdfArray)dic.get(PdfName.RECIPIENTS);
break;
default:
throw new UnsupportedPdfException("Unknown encryption type V = " + rValue);
}
for (int i = 0; i<recipients.size(); i++) {
PdfObject recipient = recipients.getPdfObject(i);
strings.remove(recipient);
CMSEnvelopedData data = null;
try {
data = new CMSEnvelopedData(recipient.getBytes());
Iterator<RecipientInformation> recipientCertificatesIt = data.getRecipientInfos().getRecipients().iterator();
while (recipientCertificatesIt.hasNext()) {
RecipientInformation recipientInfo = recipientCertificatesIt.next();
if (recipientInfo.getRID().match(certificate) && !foundRecipient) {
envelopedData = recipientInfo.getContent(new JceKeyTransEnvelopedRecipient((PrivateKey) certificateKey).setProvider(certificateKeyProvider));
foundRecipient = true;
}
}
}
catch (Exception f) {
throw new ExceptionConverter(f);
}
}
if(!foundRecipient || envelopedData == null) {
throw new UnsupportedPdfException("Bad certificate and key.");
}
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA-1");
md.update(envelopedData, 0, 20);
for (int i = 0; i<recipients.size(); i++) {
byte[] encodedRecipient = recipients.getPdfObject(i).getBytes();
md.update(encodedRecipient);
}
if ((cryptoMode & PdfWriter.DO_NOT_ENCRYPT_METADATA) != 0)
md.update(new byte[]{(byte)255, (byte)255, (byte)255, (byte)255});
encryptionKey = md.digest();
}
catch (Exception f) {
throw new ExceptionConverter(f);
}
}
decrypt = new PdfEncryption();
decrypt.setCryptoMode(cryptoMode, lengthValue);
if (filter.equals(PdfName.STANDARD)) {
//check by owner password
decrypt.setupByOwnerPassword(documentID, password, uValue, oValue, pValue);
if (!equalsArray(uValue, decrypt.userKey, (rValue == 3 || rValue == 4) ? 16 : 32)) {
//check by user password
decrypt.setupByUserPassword(documentID, password, oValue, pValue);
if (!equalsArray(uValue, decrypt.userKey, (rValue == 3 || rValue == 4) ? 16 : 32)) {
throw new BadPasswordException("Bad user password");
}
}
else
ownerPasswordUsed = true;
}
else if (filter.equals(PdfName.PUBSEC)) {
decrypt.setupByEncryptionKey(encryptionKey, lengthValue);
ownerPasswordUsed = true;
}
for (int k = 0; k < strings.size(); ++k) {
PdfString str = (PdfString)strings.get(k);
str.decrypt(this);
}
if (encDic.isIndirect()) {
cryptoRef = (PRIndirectReference)encDic;
xrefObj.set(cryptoRef.getNumber(), null);
}
encryptionError = false;
}
/**
* @param obj
* @return a PdfObject
*/
public static PdfObject getPdfObjectRelease(PdfObject obj) {
PdfObject obj2 = getPdfObject(obj);
releaseLastXrefPartial(obj);
return obj2;
}
/**
* Reads a <CODE>PdfObject</CODE> resolving an indirect reference
* if needed.
* @param obj the <CODE>PdfObject</CODE> to read
* @return the resolved <CODE>PdfObject</CODE>
*/
public static PdfObject getPdfObject(PdfObject obj) {
if (obj == null)
return null;
if (!obj.isIndirect())
return obj;
try {
PRIndirectReference ref = (PRIndirectReference)obj;
int idx = ref.getNumber();
boolean appendable = ref.getReader().appendable;
obj = ref.getReader().getPdfObject(idx);
if (obj == null) {
return null;
}
else {
if (appendable) {
switch (obj.type()) {
case PdfObject.NULL:
obj = new PdfNull();
break;
case PdfObject.BOOLEAN:
obj = new PdfBoolean(((PdfBoolean)obj).booleanValue());
break;
case PdfObject.NAME:
obj = new PdfName(obj.getBytes());
break;
}
obj.setIndRef(ref);
}
return obj;
}
}
catch (Exception e) {
throw new ExceptionConverter(e);
}
}
/**
* Reads a <CODE>PdfObject</CODE> resolving an indirect reference
* if needed. If the reader was opened in partial mode the object will be released
* to save memory.
* @param obj the <CODE>PdfObject</CODE> to read
* @param parent
* @return a PdfObject
*/
public static PdfObject getPdfObjectRelease(PdfObject obj, PdfObject parent) {
PdfObject obj2 = getPdfObject(obj, parent);
releaseLastXrefPartial(obj);
return obj2;
}
/**
* @param obj
* @param parent
* @return a PdfObject
*/
public static PdfObject getPdfObject(PdfObject obj, PdfObject parent) {
if (obj == null)
return null;
if (!obj.isIndirect()) {
PRIndirectReference ref = null;
if (parent != null && (ref = parent.getIndRef()) != null && ref.getReader().isAppendable()) {
switch (obj.type()) {
case PdfObject.NULL:
obj = new PdfNull();
break;
case PdfObject.BOOLEAN:
obj = new PdfBoolean(((PdfBoolean)obj).booleanValue());
break;
case PdfObject.NAME:
obj = new PdfName(obj.getBytes());
break;
}
obj.setIndRef(ref);
}
return obj;
}
return getPdfObject(obj);
}
/**
* @param idx
* @return a PdfObject
*/
public PdfObject getPdfObjectRelease(int idx) {
PdfObject obj = getPdfObject(idx);
releaseLastXrefPartial();
return obj;
}
/**
* @param idx
* @return aPdfObject
*/
public PdfObject getPdfObject(int idx) {
try {
lastXrefPartial = -1;
if (idx < 0 || idx >= xrefObj.size())
return null;
PdfObject obj = (PdfObject)xrefObj.get(idx);
if (!partial || obj != null)
return obj;
if (idx * 2 >= xref.length)
return null;
obj = readSingleObject(idx);
lastXrefPartial = -1;
if (obj != null)
lastXrefPartial = idx;
return obj;
}
catch (Exception e) {
throw new ExceptionConverter(e);
}
}
/**
*
*/
public void resetLastXrefPartial() {
lastXrefPartial = -1;
}
/**
*
*/
public void releaseLastXrefPartial() {
if (partial && lastXrefPartial != -1) {
xrefObj.set(lastXrefPartial, null);
lastXrefPartial = -1;
}
}
/**
* @param obj
*/
public static void releaseLastXrefPartial(PdfObject obj) {
if (obj == null)
return;
if (!obj.isIndirect())
return;
if (!(obj instanceof PRIndirectReference))
return;
PRIndirectReference ref = (PRIndirectReference)obj;
PdfReader reader = ref.getReader();
if (reader.partial && reader.lastXrefPartial != -1 && reader.lastXrefPartial == ref.getNumber()) {
reader.xrefObj.set(reader.lastXrefPartial, null);
}
reader.lastXrefPartial = -1;
}
private void setXrefPartialObject(int idx, PdfObject obj) {
if (!partial || idx < 0)
return;
xrefObj.set(idx, obj);
}
/**
* @param obj
* @return an indirect reference
*/
public PRIndirectReference addPdfObject(PdfObject obj) {
xrefObj.add(obj);
return new PRIndirectReference(this, xrefObj.size() - 1);
}
protected void readPages() throws IOException {
catalog = trailer.getAsDict(PdfName.ROOT);
rootPages = catalog.getAsDict(PdfName.PAGES);
pageRefs = new PageRefs(this);
}
protected void readDocObjPartial() throws IOException {
xrefObj = new ArrayList(xref.length / 2);
xrefObj.addAll(Collections.nCopies(xref.length / 2, null));
readDecryptedDocObj();
if (objStmToOffset != null) {
int keys[] = objStmToOffset.getKeys();
for (int k = 0; k < keys.length; ++k) {
int n = keys[k];
objStmToOffset.put(n, xref[n * 2]);
xref[n * 2] = -1;
}
}
}
protected PdfObject readSingleObject(int k) throws IOException {
strings.clear();
int k2 = k * 2;
int pos = xref[k2];
if (pos < 0)
return null;
if (xref[k2 + 1] > 0)
pos = objStmToOffset.get(xref[k2 + 1]);
if (pos == 0)
return null;
tokens.seek(pos);
tokens.nextValidToken();
if (tokens.getTokenType() != PRTokeniser.TK_NUMBER)
tokens.throwError("Invalid object number.");
objNum = tokens.intValue();
tokens.nextValidToken();
if (tokens.getTokenType() != PRTokeniser.TK_NUMBER)
tokens.throwError("Invalid generation number.");
objGen = tokens.intValue();
tokens.nextValidToken();
if (!tokens.getStringValue().equals("obj"))
tokens.throwError("Token 'obj' expected.");
PdfObject obj;
try {
obj = readPRObject();
for (int j = 0; j < strings.size(); ++j) {
PdfString str = (PdfString)strings.get(j);
str.decrypt(this);
}
if (obj.isStream()) {
checkPRStreamLength((PRStream)obj);
}
}
catch (Exception e) {
obj = null;
}
if (xref[k2 + 1] > 0) {
obj = readOneObjStm((PRStream)obj, xref[k2]);
}
xrefObj.set(k, obj);
return obj;
}
protected PdfObject readOneObjStm(PRStream stream, int idx) throws IOException {
int first = stream.getAsNumber(PdfName.FIRST).intValue();
byte b[] = getStreamBytes(stream, tokens.getFile());
PRTokeniser saveTokens = tokens;
tokens = new PRTokeniser(b);
try {
int address = 0;
boolean ok = true;
++idx;
for (int k = 0; k < idx; ++k) {
ok = tokens.nextToken();
if (!ok)
break;
if (tokens.getTokenType() != PRTokeniser.TK_NUMBER) {
ok = false;
break;
}
ok = tokens.nextToken();
if (!ok)
break;
if (tokens.getTokenType() != PRTokeniser.TK_NUMBER) {
ok = false;
break;
}
address = tokens.intValue() + first;
}
if (!ok)
throw new InvalidPdfException("Error reading ObjStm");
tokens.seek(address);
return readPRObject();
}
finally {
tokens = saveTokens;
}
}
/**
* @return the percentage of the cross reference table that has been read
*/
public double dumpPerc() {
int total = 0;
for (int k = 0; k < xrefObj.size(); ++k) {
if (xrefObj.get(k) != null)
++total;
}
return (total * 100.0 / xrefObj.size());
}
protected void readDocObj() throws IOException {
ArrayList streams = new ArrayList();
xrefObj = new ArrayList(xref.length / 2);
xrefObj.addAll(Collections.nCopies(xref.length / 2, null));
for (int k = 2; k < xref.length; k += 2) {
int pos = xref[k];
if (pos <= 0 || xref[k + 1] > 0)
continue;
tokens.seek(pos);
tokens.nextValidToken();
if (tokens.getTokenType() != PRTokeniser.TK_NUMBER)
tokens.throwError("Invalid object number.");
objNum = tokens.intValue();
tokens.nextValidToken();
if (tokens.getTokenType() != PRTokeniser.TK_NUMBER)
tokens.throwError("Invalid generation number.");
objGen = tokens.intValue();
tokens.nextValidToken();
if (!tokens.getStringValue().equals("obj"))
tokens.throwError("Token 'obj' expected.");
PdfObject obj;
try {
obj = readPRObject();
if (obj.isStream()) {
streams.add(obj);
}
}
catch (Exception e) {
obj = null;
}
xrefObj.set(k / 2, obj);
}
for (int k = 0; k < streams.size(); ++k) {
checkPRStreamLength((PRStream)streams.get(k));
}
readDecryptedDocObj();
if (objStmMark != null) {
for (Iterator i = objStmMark.entrySet().iterator(); i.hasNext();) {
Map.Entry entry = (Map.Entry)i.next();
int n = ((Integer)entry.getKey()).intValue();
IntHashtable h = (IntHashtable)entry.getValue();
readObjStm((PRStream)xrefObj.get(n), h);
xrefObj.set(n, null);
}
objStmMark = null;
}
xref = null;
}
private void checkPRStreamLength(PRStream stream) throws IOException {
int fileLength = tokens.length();
int start = stream.getOffset();
boolean calc = false;
int streamLength = 0;
PdfObject obj = getPdfObjectRelease(stream.get(PdfName.LENGTH));
if (obj != null && obj.type() == PdfObject.NUMBER) {
streamLength = ((PdfNumber)obj).intValue();
if (streamLength + start > fileLength - 20)
calc = true;
else {
tokens.seek(start + streamLength);
String line = tokens.readString(20);
if (!line.startsWith("\nendstream") &&
!line.startsWith("\r\nendstream") &&
!line.startsWith("\rendstream") &&
!line.startsWith("endstream"))
calc = true;
}
}
else
calc = true;
if (calc) {
byte tline[] = new byte[16];
tokens.seek(start);
while (true) {
int pos = tokens.getFilePointer();
if (!tokens.readLineSegment(tline))
break;
if (equalsn(tline, endstream)) {
streamLength = pos - start;
break;
}
if (equalsn(tline, endobj)) {
tokens.seek(pos - 16);
String s = tokens.readString(16);
int index = s.indexOf("endstream");
if (index >= 0)
pos = pos - 16 + index;
streamLength = pos - start;
break;
}
}
}
stream.setLength(streamLength);
}
protected void readObjStm(PRStream stream, IntHashtable map) throws IOException {
int first = stream.getAsNumber(PdfName.FIRST).intValue();
int n = stream.getAsNumber(PdfName.N).intValue();
byte b[] = getStreamBytes(stream, tokens.getFile());
PRTokeniser saveTokens = tokens;
tokens = new PRTokeniser(b);
try {
int address[] = new int[n];
int objNumber[] = new int[n];
boolean ok = true;
for (int k = 0; k < n; ++k) {
ok = tokens.nextToken();
if (!ok)
break;
if (tokens.getTokenType() != PRTokeniser.TK_NUMBER) {
ok = false;
break;
}
objNumber[k] = tokens.intValue();
ok = tokens.nextToken();
if (!ok)
break;
if (tokens.getTokenType() != PRTokeniser.TK_NUMBER) {
ok = false;
break;
}
address[k] = tokens.intValue() + first;
}
if (!ok)
throw new InvalidPdfException("Error reading ObjStm");
for (int k = 0; k < n; ++k) {
if (map.containsKey(k)) {
tokens.seek(address[k]);
PdfObject obj = readPRObject();
xrefObj.set(objNumber[k], obj);
}
}
}
finally {
tokens = saveTokens;
}
}
/**
* Eliminates the reference to the object freeing the memory used by it and clearing
* the xref entry.
* @param obj the object. If it's an indirect reference it will be eliminated
* @return the object or the already erased dereferenced object
*/
public static PdfObject killIndirect(PdfObject obj) {
if (obj == null || obj.isNull())
return null;
PdfObject ret = getPdfObjectRelease(obj);
if (obj.isIndirect()) {
PRIndirectReference ref = (PRIndirectReference)obj;
PdfReader reader = ref.getReader();
int n = ref.getNumber();
reader.xrefObj.set(n, null);
if (reader.partial)
reader.xref[n * 2] = -1;
}
return ret;
}
private void ensureXrefSize(int size) {
if (size == 0)
return;
if (xref == null)
xref = new int[size];
else {
if (xref.length < size) {
int xref2[] = new int[size];
System.arraycopy(xref, 0, xref2, 0, xref.length);
xref = xref2;
}
}
}
protected void readXref() throws IOException {
hybridXref = false;
newXrefType = false;
tokens.seek(tokens.getStartxref());
tokens.nextToken();
if (!tokens.getStringValue().equals("startxref"))
throw new InvalidPdfException("startxref not found.");
tokens.nextToken();
if (tokens.getTokenType() != PRTokeniser.TK_NUMBER)
throw new InvalidPdfException("startxref is not followed by a number.");
int startxref = tokens.intValue();
lastXref = startxref;
eofPos = tokens.getFilePointer();
try {
if (readXRefStream(startxref)) {
newXrefType = true;
return;
}
}
catch (Exception e) {}
xref = null;
tokens.seek(startxref);
trailer = readXrefSection();
PdfDictionary trailer2 = trailer;
while (true) {
PdfNumber prev = (PdfNumber)trailer2.get(PdfName.PREV);
if (prev == null)
break;
tokens.seek(prev.intValue());
trailer2 = readXrefSection();
}
}
protected PdfDictionary readXrefSection() throws IOException {
tokens.nextValidToken();
if (!tokens.getStringValue().equals("xref"))
tokens.throwError("xref subsection not found");
int start = 0;
int end = 0;
int pos = 0;
int gen = 0;
while (true) {
tokens.nextValidToken();
if (tokens.getStringValue().equals("trailer"))
break;
if (tokens.getTokenType() != PRTokeniser.TK_NUMBER)
tokens.throwError("Object number of the first object in this xref subsection not found");
start = tokens.intValue();
tokens.nextValidToken();
if (tokens.getTokenType() != PRTokeniser.TK_NUMBER)
tokens.throwError("Number of entries in this xref subsection not found");
end = tokens.intValue() + start;
if (start == 1) { // fix incorrect start number
int back = tokens.getFilePointer();
tokens.nextValidToken();
pos = tokens.intValue();
tokens.nextValidToken();
gen = tokens.intValue();
if (pos == 0 && gen == PdfWriter.GENERATION_MAX) {
--start;
--end;
}
tokens.seek(back);
}
ensureXrefSize(end * 2);
for (int k = start; k < end; ++k) {
tokens.nextValidToken();
pos = tokens.intValue();
tokens.nextValidToken();
gen = tokens.intValue();
tokens.nextValidToken();
int p = k * 2;
if (tokens.getStringValue().equals("n")) {
if (xref[p] == 0 && xref[p + 1] == 0) {
// if (pos == 0)
// tokens.throwError("File position 0 cross-reference entry in this xref subsection");
xref[p] = pos;
}
}
else if (tokens.getStringValue().equals("f")) {
if (xref[p] == 0 && xref[p + 1] == 0)
xref[p] = -1;
}
else
tokens.throwError("Invalid cross-reference entry in this xref subsection");
}
}
PdfDictionary trailer = (PdfDictionary)readPRObject();
PdfNumber xrefSize = (PdfNumber)trailer.get(PdfName.SIZE);
ensureXrefSize(xrefSize.intValue() * 2);
PdfObject xrs = trailer.get(PdfName.XREFSTM);
if (xrs != null && xrs.isNumber()) {
int loc = ((PdfNumber)xrs).intValue();
try {
readXRefStream(loc);
newXrefType = true;
hybridXref = true;
}
catch (IOException e) {
xref = null;
throw e;
}
}
return trailer;
}
protected boolean readXRefStream(int ptr) throws IOException {
tokens.seek(ptr);
int thisStream = 0;
if (!tokens.nextToken())
return false;
if (tokens.getTokenType() != PRTokeniser.TK_NUMBER)
return false;
thisStream = tokens.intValue();
if (!tokens.nextToken() || tokens.getTokenType() != PRTokeniser.TK_NUMBER)
return false;
if (!tokens.nextToken() || !tokens.getStringValue().equals("obj"))
return false;
PdfObject object = readPRObject();
PRStream stm = null;
if (object.isStream()) {
stm = (PRStream)object;
if (!PdfName.XREF.equals(stm.get(PdfName.TYPE)))
return false;
}
else
return false;
if (trailer == null) {
trailer = new PdfDictionary();
trailer.putAll(stm);
}
stm.setLength(((PdfNumber)stm.get(PdfName.LENGTH)).intValue());
int size = ((PdfNumber)stm.get(PdfName.SIZE)).intValue();
PdfArray index;
PdfObject obj = stm.get(PdfName.INDEX);
if (obj == null) {
index = new PdfArray();
index.add(new int[]{0, size});
}
else
index = (PdfArray)obj;
PdfArray w = (PdfArray)stm.get(PdfName.W);
int prev = -1;
obj = stm.get(PdfName.PREV);
if (obj != null)
prev = ((PdfNumber)obj).intValue();
// Each xref pair is a position
// type 0 -> -1, 0
// type 1 -> offset, 0
// type 2 -> index, obj num
ensureXrefSize(size * 2);
if (objStmMark == null && !partial)
objStmMark = new HashMap();
if (objStmToOffset == null && partial)
objStmToOffset = new IntHashtable();
byte b[] = getStreamBytes(stm, tokens.getFile());
int bptr = 0;
int wc[] = new int[3];
for (int k = 0; k < 3; ++k)
wc[k] = w.getAsNumber(k).intValue();
for (int idx = 0; idx < index.size(); idx += 2) {
int start = index.getAsNumber(idx).intValue();
int length = index.getAsNumber(idx + 1).intValue();
ensureXrefSize((start + length) * 2);
while (length-- > 0) {
int type = 1;
if (wc[0] > 0) {
type = 0;
for (int k = 0; k < wc[0]; ++k)
type = (type << 8) + (b[bptr++] & 0xff);
}
int field2 = 0;
for (int k = 0; k < wc[1]; ++k)
field2 = (field2 << 8) + (b[bptr++] & 0xff);
int field3 = 0;
for (int k = 0; k < wc[2]; ++k)
field3 = (field3 << 8) + (b[bptr++] & 0xff);
int base = start * 2;
if (xref[base] == 0 && xref[base + 1] == 0) {
switch (type) {
case 0:
xref[base] = -1;
break;
case 1:
xref[base] = field2;
break;
case 2:
xref[base] = field3;
xref[base + 1] = field2;
if (partial) {
objStmToOffset.put(field2, 0);
}
else {
Integer on = new Integer(field2);
IntHashtable seq = (IntHashtable)objStmMark.get(on);
if (seq == null) {
seq = new IntHashtable();
seq.put(field3, 1);
objStmMark.put(on, seq);
}
else
seq.put(field3, 1);
}
break;
}
}
++start;
}
}
thisStream *= 2;
if (thisStream < xref.length)
xref[thisStream] = -1;
if (prev == -1)
return true;
return readXRefStream(prev);
}
protected void rebuildXref() throws IOException {
hybridXref = false;
newXrefType = false;
tokens.seek(0);
int xr[][] = new int[1024][];
int top = 0;
trailer = null;
byte line[] = new byte[64];
for (;;) {
int pos = tokens.getFilePointer();
if (!tokens.readLineSegment(line))
break;
if (line[0] == 't') {
if (!PdfEncodings.convertToString(line, null).startsWith("trailer"))
continue;
tokens.seek(pos);
tokens.nextToken();
pos = tokens.getFilePointer();
try {
PdfDictionary dic = (PdfDictionary)readPRObject();
if (dic.get(PdfName.ROOT) != null)
trailer = dic;
else
tokens.seek(pos);
}
catch (Exception e) {
tokens.seek(pos);
}
}
else if (line[0] >= '0' && line[0] <= '9') {
int obj[] = PRTokeniser.checkObjectStart(line);
if (obj == null)
continue;
int num = obj[0];
int gen = obj[1];
if (num >= xr.length) {
int newLength = num * 2;
int xr2[][] = new int[newLength][];
System.arraycopy(xr, 0, xr2, 0, top);
xr = xr2;
}
if (num >= top)
top = num + 1;
if (xr[num] == null || gen >= xr[num][1]) {
obj[0] = pos;
xr[num] = obj;
}
}
}
if (trailer == null)
throw new InvalidPdfException("trailer not found.");
xref = new int[top * 2];
for (int k = 0; k < top; ++k) {
int obj[] = xr[k];
if (obj != null)
xref[k * 2] = obj[0];
}
}
protected PdfDictionary readDictionary() throws IOException {
PdfDictionary dic = new PdfDictionary();
while (true) {
tokens.nextValidToken();
if (tokens.getTokenType() == PRTokeniser.TK_END_DIC)
break;
if (tokens.getTokenType() != PRTokeniser.TK_NAME)
tokens.throwError("Dictionary key is not a name.");
PdfName name = new PdfName(tokens.getStringValue(), false);
PdfObject obj = readPRObject();
int type = obj.type();
if (-type == PRTokeniser.TK_END_DIC)
tokens.throwError("Unexpected '>>'");
if (-type == PRTokeniser.TK_END_ARRAY)
tokens.throwError("Unexpected ']'");
dic.put(name, obj);
}
return dic;
}
protected PdfArray readArray() throws IOException {
PdfArray array = new PdfArray();
while (true) {
PdfObject obj = readPRObject();
int type = obj.type();
if (-type == PRTokeniser.TK_END_ARRAY)
break;
if (-type == PRTokeniser.TK_END_DIC)
tokens.throwError("Unexpected '>>'");
array.add(obj);
}
return array;
}
// Track how deeply nested the current object is, so
// we know when to return an individual null or boolean, or
// reuse one of the static ones.
private int readDepth = 0;
protected PdfObject readPRObject() throws IOException {
tokens.nextValidToken();
int type = tokens.getTokenType();
switch (type) {
case PRTokeniser.TK_START_DIC: {
++readDepth;
PdfDictionary dic = readDictionary();
--readDepth;
int pos = tokens.getFilePointer();
// be careful in the trailer. May not be a "next" token.
boolean hasNext;
do {
hasNext = tokens.nextToken();
} while (hasNext && tokens.getTokenType() == PRTokeniser.TK_COMMENT);
if (hasNext && tokens.getStringValue().equals("stream")) {
//skip whitespaces
int ch;
do {
ch = tokens.read();
} while (ch == 32 || ch == 9 || ch == 0 || ch == 12);
if (ch != '\n')
ch = tokens.read();
if (ch != '\n')
tokens.backOnePosition(ch);
PRStream stream = new PRStream(this, tokens.getFilePointer());
stream.putAll(dic);
// crypto handling
stream.setObjNum(objNum, objGen);
return stream;
}
else {
tokens.seek(pos);
return dic;
}
}
case PRTokeniser.TK_START_ARRAY: {
++readDepth;
PdfArray arr = readArray();
--readDepth;
return arr;
}
case PRTokeniser.TK_NUMBER:
return new PdfNumber(tokens.getStringValue());
case PRTokeniser.TK_STRING:
PdfString str = new PdfString(tokens.getStringValue(), null).setHexWriting(tokens.isHexString());
// crypto handling
str.setObjNum(objNum, objGen);
if (strings != null)
strings.add(str);
return str;
case PRTokeniser.TK_NAME: {
PdfName cachedName = (PdfName)PdfName.staticNames.get( tokens.getStringValue() );
if (readDepth > 0 && cachedName != null) {
return cachedName;
} else {
// an indirect name (how odd...), or a non-standard one
return new PdfName(tokens.getStringValue(), false);
}
}
case PRTokeniser.TK_REF:
int num = tokens.getReference();
PRIndirectReference ref = new PRIndirectReference(this, num, tokens.getGeneration());
return ref;
default:
String sv = tokens.getStringValue();
if ("null".equals(sv)) {
if (readDepth == 0) {
return new PdfNull();
} //else
return PdfNull.PDFNULL;
}
else if ("true".equals(sv)) {
if (readDepth == 0) {
return new PdfBoolean( true );
} //else
return PdfBoolean.PDFTRUE;
}
else if ("false".equals(sv)) {
if (readDepth == 0) {
return new PdfBoolean( false );
} //else
return PdfBoolean.PDFFALSE;
}
return new PdfLiteral(-type, tokens.getStringValue());
}
}
/** Decodes a stream that has the FlateDecode filter.
* @param in the input data
* @return the decoded data
*/
public static byte[] FlateDecode(byte in[]) {
byte b[] = FlateDecode(in, true);
if (b == null)
return FlateDecode(in, false);
return b;
}
/**
* @param in
* @param dicPar
* @return a byte array
*/
public static byte[] decodePredictor(byte in[], PdfObject dicPar) {
if (dicPar == null || !dicPar.isDictionary())
return in;
PdfDictionary dic = (PdfDictionary)dicPar;
PdfObject obj = getPdfObject(dic.get(PdfName.PREDICTOR));
if (obj == null || !obj.isNumber())
return in;
int predictor = ((PdfNumber)obj).intValue();
if (predictor < 10)
return in;
int width = 1;
obj = getPdfObject(dic.get(PdfName.COLUMNS));
if (obj != null && obj.isNumber())
width = ((PdfNumber)obj).intValue();
int colors = 1;
obj = getPdfObject(dic.get(PdfName.COLORS));
if (obj != null && obj.isNumber())
colors = ((PdfNumber)obj).intValue();
int bpc = 8;
obj = getPdfObject(dic.get(PdfName.BITSPERCOMPONENT));
if (obj != null && obj.isNumber())
bpc = ((PdfNumber)obj).intValue();
DataInputStream dataStream = new DataInputStream(new ByteArrayInputStream(in));
ByteArrayOutputStream fout = new ByteArrayOutputStream(in.length);
int bytesPerPixel = colors * bpc / 8;
int bytesPerRow = (colors*width*bpc + 7)/8;
byte[] curr = new byte[bytesPerRow];
byte[] prior = new byte[bytesPerRow];
// Decode the (sub)image row-by-row
while (true) {
// Read the filter type byte and a row of data
int filter = 0;
try {
filter = dataStream.read();
if (filter < 0) {
return fout.toByteArray();
}
dataStream.readFully(curr, 0, bytesPerRow);
} catch (Exception e) {
return fout.toByteArray();
}
switch (filter) {
case 0: //PNG_FILTER_NONE
break;
case 1: //PNG_FILTER_SUB
for (int i = bytesPerPixel; i < bytesPerRow; i++) {
curr[i] += curr[i - bytesPerPixel];
}
break;
case 2: //PNG_FILTER_UP
for (int i = 0; i < bytesPerRow; i++) {
curr[i] += prior[i];
}
break;
case 3: //PNG_FILTER_AVERAGE
for (int i = 0; i < bytesPerPixel; i++) {
curr[i] += prior[i] / 2;
}
for (int i = bytesPerPixel; i < bytesPerRow; i++) {
curr[i] += ((curr[i - bytesPerPixel] & 0xff) + (prior[i] & 0xff))/2;
}
break;
case 4: //PNG_FILTER_PAETH
for (int i = 0; i < bytesPerPixel; i++) {
curr[i] += prior[i];
}
for (int i = bytesPerPixel; i < bytesPerRow; i++) {
int a = curr[i - bytesPerPixel] & 0xff;
int b = prior[i] & 0xff;
int c = prior[i - bytesPerPixel] & 0xff;
int p = a + b - c;
int pa = Math.abs(p - a);
int pb = Math.abs(p - b);
int pc = Math.abs(p - c);
int ret;
if ((pa <= pb) && (pa <= pc)) {
ret = a;
} else if (pb <= pc) {
ret = b;
} else {
ret = c;
}
curr[i] += (byte)(ret);
}
break;
default:
// Error -- unknown filter type
throw new RuntimeException("PNG filter unknown.");
}
try {
fout.write(curr);
}
catch (IOException ioe) {
// Never happens
}
// Swap curr and prior
byte[] tmp = prior;
prior = curr;
curr = tmp;
}
}
/** A helper to FlateDecode.
* @param in the input data
* @param strict <CODE>true</CODE> to read a correct stream. <CODE>false</CODE>
* to try to read a corrupted stream
* @return the decoded data
*/
public static byte[] FlateDecode(byte in[], boolean strict) {
ByteArrayInputStream stream = new ByteArrayInputStream(in);
InflaterInputStream zip = new InflaterInputStream(stream);
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte b[] = new byte[strict ? 4092 : 1];
try {
int n;
while ((n = zip.read(b)) >= 0) {
out.write(b, 0, n);
}
zip.close();
out.close();
return out.toByteArray();
}
catch (Exception e) {
if (strict)
return null;
return out.toByteArray();
}
}
/** Decodes a stream that has the ASCIIHexDecode filter.
* @param in the input data
* @return the decoded data
*/
public static byte[] ASCIIHexDecode(byte in[]) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
boolean first = true;
int n1 = 0;
for (int k = 0; k < in.length; ++k) {
int ch = in[k] & 0xff;
if (ch == '>')
break;
if (PRTokeniser.isWhitespace(ch))
continue;
int n = PRTokeniser.getHex(ch);
if (n == -1)
throw new RuntimeException("Illegal character in ASCIIHexDecode.");
if (first)
n1 = n;
else
out.write((byte)((n1 << 4) + n));
first = !first;
}
if (!first)
out.write((byte)(n1 << 4));
return out.toByteArray();
}
/** Decodes a stream that has the ASCII85Decode filter.
* @param in the input data
* @return the decoded data
*/
public static byte[] ASCII85Decode(byte in[]) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
int state = 0;
int chn[] = new int[5];
for (int k = 0; k < in.length; ++k) {
int ch = in[k] & 0xff;
if (ch == '~')
break;
if (PRTokeniser.isWhitespace(ch))
continue;
if (ch == 'z' && state == 0) {
out.write(0);
out.write(0);
out.write(0);
out.write(0);
continue;
}
if (ch < '!' || ch > 'u')
throw new RuntimeException("Illegal character in ASCII85Decode.");
chn[state] = ch - '!';
++state;
if (state == 5) {
state = 0;
int r = 0;
for (int j = 0; j < 5; ++j)
r = r * 85 + chn[j];
out.write((byte)(r >> 24));
out.write((byte)(r >> 16));
out.write((byte)(r >> 8));
out.write((byte)r);
}
}
int r = 0;
// We'll ignore the next two lines for the sake of perpetuating broken PDFs
// if (state == 1)
// throw new RuntimeException("Illegal length in ASCII85Decode.");
if (state == 2) {
r = chn[0] * 85 * 85 * 85 * 85 + chn[1] * 85 * 85 * 85 + 85 * 85 * 85 + 85 * 85 + 85;
out.write((byte)(r >> 24));
}
else if (state == 3) {
r = chn[0] * 85 * 85 * 85 * 85 + chn[1] * 85 * 85 * 85 + chn[2] * 85 * 85 + 85 * 85 + 85;
out.write((byte)(r >> 24));
out.write((byte)(r >> 16));
}
else if (state == 4) {
r = chn[0] * 85 * 85 * 85 * 85 + chn[1] * 85 * 85 * 85 + chn[2] * 85 * 85 + chn[3] * 85 + 85;
out.write((byte)(r >> 24));
out.write((byte)(r >> 16));
out.write((byte)(r >> 8));
}
return out.toByteArray();
}
/** Decodes a stream that has the LZWDecode filter.
* @param in the input data
* @return the decoded data
*/
public static byte[] LZWDecode(byte in[]) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
LZWDecoder lzw = new LZWDecoder();
lzw.decode(in, out);
return out.toByteArray();
}
/** Checks if the document had errors and was rebuilt.
* @return true if rebuilt.
*
*/
public boolean isRebuilt() {
return this.rebuilt;
}
/** Gets the dictionary that represents a page.
* @param pageNum the page number. 1 is the first
* @return the page dictionary
*/
public PdfDictionary getPageN(int pageNum) {
PdfDictionary dic = pageRefs.getPageN(pageNum);
if (dic == null)
return null;
if (appendable)
dic.setIndRef(pageRefs.getPageOrigRef(pageNum));
return dic;
}
/**
* @param pageNum
* @return a Dictionary object
*/
public PdfDictionary getPageNRelease(int pageNum) {
PdfDictionary dic = getPageN(pageNum);
pageRefs.releasePage(pageNum);
return dic;
}
/**
* @param pageNum
*/
public void releasePage(int pageNum) {
pageRefs.releasePage(pageNum);
}
/**
*
*/
public void resetReleasePage() {
pageRefs.resetReleasePage();
}
/** Gets the page reference to this page.
* @param pageNum the page number. 1 is the first
* @return the page reference
*/
public PRIndirectReference getPageOrigRef(int pageNum) {
return pageRefs.getPageOrigRef(pageNum);
}
/** Gets the contents of the page.
* @param pageNum the page number. 1 is the first
* @param file the location of the PDF document
* @throws IOException on error
* @return the content
*/
public byte[] getPageContent(int pageNum, RandomAccessFileOrArray file) throws IOException{
PdfDictionary page = getPageNRelease(pageNum);
if (page == null)
return null;
PdfObject contents = getPdfObjectRelease(page.get(PdfName.CONTENTS));
if (contents == null)
return new byte[0];
ByteArrayOutputStream bout = null;
if (contents.isStream()) {
return getStreamBytes((PRStream)contents, file);
}
else if (contents.isArray()) {
PdfArray array = (PdfArray)contents;
bout = new ByteArrayOutputStream();
for (int k = 0; k < array.size(); ++k) {
PdfObject item = getPdfObjectRelease(array.getPdfObject(k));
if (item == null || !item.isStream())
continue;
byte[] b = getStreamBytes((PRStream)item, file);
bout.write(b);
if (k != array.size() - 1)
bout.write('\n');
}
return bout.toByteArray();
}
else
return new byte[0];
}
/** Gets the contents of the page.
* @param pageNum the page number. 1 is the first
* @throws IOException on error
* @return the content
*/
public byte[] getPageContent(int pageNum) throws IOException{
RandomAccessFileOrArray rf = getSafeFile();
try {
rf.reOpen();
return getPageContent(pageNum, rf);
}
finally {
try{rf.close();}catch(Exception e){}
}
}
protected void killXref(PdfObject obj) {
if (obj == null)
return;
if ((obj instanceof PdfIndirectReference) && !obj.isIndirect())
return;
switch (obj.type()) {
case PdfObject.INDIRECT: {
int xr = ((PRIndirectReference)obj).getNumber();
obj = (PdfObject)xrefObj.get(xr);
xrefObj.set(xr, null);
freeXref = xr;
killXref(obj);
break;
}
case PdfObject.ARRAY: {
PdfArray t = (PdfArray)obj;
for (int i = 0; i < t.size(); ++i)
killXref(t.getPdfObject(i));
break;
}
case PdfObject.STREAM:
case PdfObject.DICTIONARY: {
PdfDictionary dic = (PdfDictionary)obj;
for (Iterator i = dic.getKeys().iterator(); i.hasNext();){
killXref(dic.get((PdfName)i.next()));
}
break;
}
}
}
/** Sets the contents of the page.
* @param content the new page content
* @param pageNum the page number. 1 is the first
*/
public void setPageContent(int pageNum, byte content[]) {
setPageContent(pageNum, content, PdfStream.DEFAULT_COMPRESSION);
}
/** Sets the contents of the page.
* @param content the new page content
* @param pageNum the page number. 1 is the first
* @since 2.1.3 (the method already existed without param compressionLevel)
*/
public void setPageContent(int pageNum, byte content[], int compressionLevel) {
PdfDictionary page = getPageN(pageNum);
if (page == null)
return;
PdfObject contents = page.get(PdfName.CONTENTS);
freeXref = -1;
killXref(contents);
if (freeXref == -1) {
xrefObj.add(null);
freeXref = xrefObj.size() - 1;
}
page.put(PdfName.CONTENTS, new PRIndirectReference(this, freeXref));
xrefObj.set(freeXref, new PRStream(this, content, compressionLevel));
}
/** Get the content from a stream applying the required filters.
* @param stream the stream
* @param file the location where the stream is
* @throws IOException on error
* @return the stream content
*/
public static byte[] getStreamBytes(PRStream stream, RandomAccessFileOrArray file) throws IOException {
PdfObject filter = getPdfObjectRelease(stream.get(PdfName.FILTER));
byte[] b = getStreamBytesRaw(stream, file);
ArrayList filters = new ArrayList();
if (filter != null) {
if (filter.isName())
filters.add(filter);
else if (filter.isArray())
filters = ((PdfArray)filter).getArrayList();
}
ArrayList dp = new ArrayList();
PdfObject dpo = getPdfObjectRelease(stream.get(PdfName.DECODEPARMS));
if (dpo == null || (!dpo.isDictionary() && !dpo.isArray()))
dpo = getPdfObjectRelease(stream.get(PdfName.DP));
if (dpo != null) {
if (dpo.isDictionary())
dp.add(dpo);
else if (dpo.isArray())
dp = ((PdfArray)dpo).getArrayList();
}
String name;
for (int j = 0; j < filters.size(); ++j) {
name = ((PdfName)getPdfObjectRelease((PdfObject)filters.get(j))).toString();
if (name.equals("/FlateDecode") || name.equals("/Fl")) {
b = FlateDecode(b);
PdfObject dicParam = null;
if (j < dp.size()) {
dicParam = (PdfObject)dp.get(j);
b = decodePredictor(b, dicParam);
}
}
else if (name.equals("/ASCIIHexDecode") || name.equals("/AHx"))
b = ASCIIHexDecode(b);
else if (name.equals("/ASCII85Decode") || name.equals("/A85"))
b = ASCII85Decode(b);
else if (name.equals("/LZWDecode")) {
b = LZWDecode(b);
PdfObject dicParam = null;
if (j < dp.size()) {
dicParam = (PdfObject)dp.get(j);
b = decodePredictor(b, dicParam);
}
}
else if (name.equals("/Crypt")) {
}
else
throw new UnsupportedPdfException("The filter " + name + " is not supported.");
}
return b;
}
/** Get the content from a stream applying the required filters.
* @param stream the stream
* @throws IOException on error
* @return the stream content
*/
public static byte[] getStreamBytes(PRStream stream) throws IOException {
RandomAccessFileOrArray rf = stream.getReader().getSafeFile();
try {
rf.reOpen();
return getStreamBytes(stream, rf);
}
finally {
try{rf.close();}catch(Exception e){}
}
}
/** Get the content from a stream as it is without applying any filter.
* @param stream the stream
* @param file the location where the stream is
* @throws IOException on error
* @return the stream content
*/
public static byte[] getStreamBytesRaw(PRStream stream, RandomAccessFileOrArray file) throws IOException {
PdfReader reader = stream.getReader();
byte b[];
if (stream.getOffset() < 0)
b = stream.getBytes();
else {
b = new byte[stream.getLength()];
file.seek(stream.getOffset());
file.readFully(b);
PdfEncryption decrypt = reader.getDecrypt();
if (decrypt != null) {
PdfObject filter = getPdfObjectRelease(stream.get(PdfName.FILTER));
ArrayList filters = new ArrayList();
if (filter != null) {
if (filter.isName())
filters.add(filter);
else if (filter.isArray())
filters = ((PdfArray)filter).getArrayList();
}
boolean skip = false;
for (int k = 0; k < filters.size(); ++k) {
PdfObject obj = getPdfObjectRelease((PdfObject)filters.get(k));
if (obj != null && obj.toString().equals("/Crypt")) {
skip = true;
break;
}
}
if (!skip) {
decrypt.setHashKey(stream.getObjNum(), stream.getObjGen());
b = decrypt.decryptByteArray(b);
}
}
}
return b;
}
/** Get the content from a stream as it is without applying any filter.
* @param stream the stream
* @throws IOException on error
* @return the stream content
*/
public static byte[] getStreamBytesRaw(PRStream stream) throws IOException {
RandomAccessFileOrArray rf = stream.getReader().getSafeFile();
try {
rf.reOpen();
return getStreamBytesRaw(stream, rf);
}
finally {
try{rf.close();}catch(Exception e){}
}
}
/** Eliminates shared streams if they exist. */
public void eliminateSharedStreams() {
if (!sharedStreams)
return;
sharedStreams = false;
if (pageRefs.size() == 1)
return;
ArrayList newRefs = new ArrayList();
ArrayList newStreams = new ArrayList();
IntHashtable visited = new IntHashtable();
for (int k = 1; k <= pageRefs.size(); ++k) {
PdfDictionary page = pageRefs.getPageN(k);
if (page == null)
continue;
PdfObject contents = getPdfObject(page.get(PdfName.CONTENTS));
if (contents == null)
continue;
if (contents.isStream()) {
PRIndirectReference ref = (PRIndirectReference)page.get(PdfName.CONTENTS);
if (visited.containsKey(ref.getNumber())) {
// need to duplicate
newRefs.add(ref);
newStreams.add(new PRStream((PRStream)contents, null));
}
else
visited.put(ref.getNumber(), 1);
}
else if (contents.isArray()) {
PdfArray array = (PdfArray)contents;
for (int j = 0; j < array.size(); ++j) {
PRIndirectReference ref = (PRIndirectReference)array.getPdfObject(j);
if (visited.containsKey(ref.getNumber())) {
// need to duplicate
newRefs.add(ref);
newStreams.add(new PRStream((PRStream)getPdfObject(ref), null));
}
else
visited.put(ref.getNumber(), 1);
}
}
}
if (newStreams.isEmpty())
return;
for (int k = 0; k < newStreams.size(); ++k) {
xrefObj.add(newStreams.get(k));
PRIndirectReference ref = (PRIndirectReference)newRefs.get(k);
ref.setNumber(xrefObj.size() - 1, 0);
}
}
/** Checks if the document was changed.
* @return <CODE>true</CODE> if the document was changed,
* <CODE>false</CODE> otherwise
*/
public boolean isTampered() {
return tampered;
}
/**
* Sets the tampered state. A tampered PdfReader cannot be reused in PdfStamper.
* @param tampered the tampered state
*/
public void setTampered(boolean tampered) {
this.tampered = tampered;
pageRefs.keepPages();
}
/** Gets the XML metadata.
* @throws IOException on error
* @return the XML metadata
*/
public byte[] getMetadata() throws IOException {
PdfObject obj = getPdfObject(catalog.get(PdfName.METADATA));
if (!(obj instanceof PRStream))
return null;
RandomAccessFileOrArray rf = getSafeFile();
byte b[] = null;
try {
rf.reOpen();
b = getStreamBytes((PRStream)obj, rf);
}
finally {
try {
rf.close();
}
catch (Exception e) {
// empty on purpose
}
}
return b;
}
/**
* Gets the byte address of the last xref table.
* @return the byte address of the last xref table
*/
public int getLastXref() {
return lastXref;
}
/**
* Gets the number of xref objects.
* @return the number of xref objects
*/
public int getXrefSize() {
return xrefObj.size();
}
/**
* Gets the byte address of the %%EOF marker.
* @return the byte address of the %%EOF marker
*/
public int getEofPos() {
return eofPos;
}
/**
* Gets the PDF version. Only the last version char is returned. For example
* version 1.4 is returned as '4'.
* @return the PDF version
*/
public char getPdfVersion() {
return pdfVersion;
}
/**
* Returns <CODE>true</CODE> if the PDF is encrypted.
* @return <CODE>true</CODE> if the PDF is encrypted
*/
public boolean isEncrypted() {
return encrypted;
}
/**
* Gets the encryption permissions. It can be used directly in
* <CODE>PdfWriter.setEncryption()</CODE>.
* @return the encryption permissions
*/
public int getPermissions() {
return pValue;
}
/**
* Returns <CODE>true</CODE> if the PDF has a 128 bit key encryption.
* @return <CODE>true</CODE> if the PDF has a 128 bit key encryption
*/
public boolean is128Key() {
return rValue == 3;
}
/**
* Gets the trailer dictionary
* @return the trailer dictionary
*/
public PdfDictionary getTrailer() {
return trailer;
}
PdfEncryption getDecrypt() {
return decrypt;
}
static boolean equalsn(byte a1[], byte a2[]) {
int length = a2.length;
for (int k = 0; k < length; ++k) {
if (a1[k] != a2[k])
return false;
}
return true;
}
static boolean existsName(PdfDictionary dic, PdfName key, PdfName value) {
PdfObject type = getPdfObjectRelease(dic.get(key));
if (type == null || !type.isName())
return false;
PdfName name = (PdfName)type;
return name.equals(value);
}
static String getFontName(PdfDictionary dic) {
if (dic == null)
return null;
PdfObject type = getPdfObjectRelease(dic.get(PdfName.BASEFONT));
if (type == null || !type.isName())
return null;
return PdfName.decodeName(type.toString());
}
static String getSubsetPrefix(PdfDictionary dic) {
if (dic == null)
return null;
String s = getFontName(dic);
if (s == null)
return null;
if (s.length() < 8 || s.charAt(6) != '+')
return null;
for (int k = 0; k < 6; ++k) {
char c = s.charAt(k);
if (c < 'A' || c > 'Z')
return null;
}
return s;
}
/** Finds all the font subsets and changes the prefixes to some
* random values.
* @return the number of font subsets altered
*/
public int shuffleSubsetNames() {
int total = 0;
for (int k = 1; k < xrefObj.size(); ++k) {
PdfObject obj = getPdfObjectRelease(k);
if (obj == null || !obj.isDictionary())
continue;
PdfDictionary dic = (PdfDictionary)obj;
if (!existsName(dic, PdfName.TYPE, PdfName.FONT))
continue;
if (existsName(dic, PdfName.SUBTYPE, PdfName.TYPE1)
|| existsName(dic, PdfName.SUBTYPE, PdfName.MMTYPE1)
|| existsName(dic, PdfName.SUBTYPE, PdfName.TRUETYPE)) {
String s = getSubsetPrefix(dic);
if (s == null)
continue;
String ns = BaseFont.createSubsetPrefix() + s.substring(7);
PdfName newName = new PdfName(ns);
dic.put(PdfName.BASEFONT, newName);
setXrefPartialObject(k, dic);
++total;
PdfDictionary fd = dic.getAsDict(PdfName.FONTDESCRIPTOR);
if (fd == null)
continue;
fd.put(PdfName.FONTNAME, newName);
}
else if (existsName(dic, PdfName.SUBTYPE, PdfName.TYPE0)) {
String s = getSubsetPrefix(dic);
PdfArray arr = dic.getAsArray(PdfName.DESCENDANTFONTS);
if (arr == null)
continue;
if (arr.isEmpty())
continue;
PdfDictionary desc = arr.getAsDict(0);
String sde = getSubsetPrefix(desc);
if (sde == null)
continue;
String ns = BaseFont.createSubsetPrefix();
if (s != null)
dic.put(PdfName.BASEFONT, new PdfName(ns + s.substring(7)));
setXrefPartialObject(k, dic);
PdfName newName = new PdfName(ns + sde.substring(7));
desc.put(PdfName.BASEFONT, newName);
++total;
PdfDictionary fd = desc.getAsDict(PdfName.FONTDESCRIPTOR);
if (fd == null)
continue;
fd.put(PdfName.FONTNAME, newName);
}
}
return total;
}
/** Finds all the fonts not subset but embedded and marks them as subset.
* @return the number of fonts altered
*/
public int createFakeFontSubsets() {
int total = 0;
for (int k = 1; k < xrefObj.size(); ++k) {
PdfObject obj = getPdfObjectRelease(k);
if (obj == null || !obj.isDictionary())
continue;
PdfDictionary dic = (PdfDictionary)obj;
if (!existsName(dic, PdfName.TYPE, PdfName.FONT))
continue;
if (existsName(dic, PdfName.SUBTYPE, PdfName.TYPE1)
|| existsName(dic, PdfName.SUBTYPE, PdfName.MMTYPE1)
|| existsName(dic, PdfName.SUBTYPE, PdfName.TRUETYPE)) {
String s = getSubsetPrefix(dic);
if (s != null)
continue;
s = getFontName(dic);
if (s == null)
continue;
String ns = BaseFont.createSubsetPrefix() + s;
PdfDictionary fd = (PdfDictionary)getPdfObjectRelease(dic.get(PdfName.FONTDESCRIPTOR));
if (fd == null)
continue;
if (fd.get(PdfName.FONTFILE) == null && fd.get(PdfName.FONTFILE2) == null
&& fd.get(PdfName.FONTFILE3) == null)
continue;
fd = dic.getAsDict(PdfName.FONTDESCRIPTOR);
PdfName newName = new PdfName(ns);
dic.put(PdfName.BASEFONT, newName);
fd.put(PdfName.FONTNAME, newName);
setXrefPartialObject(k, dic);
++total;
}
}
return total;
}
private static PdfArray getNameArray(PdfObject obj) {
if (obj == null)
return null;
obj = getPdfObjectRelease(obj);
if (obj == null)
return null;
if (obj.isArray())
return (PdfArray)obj;
else if (obj.isDictionary()) {
PdfObject arr2 = getPdfObjectRelease(((PdfDictionary)obj).get(PdfName.D));
if (arr2 != null && arr2.isArray())
return (PdfArray)arr2;
}
return null;
}
/**
* Gets all the named destinations as an <CODE>HashMap</CODE>. The key is the name
* and the value is the destinations array.
* @return gets all the named destinations
*/
public HashMap getNamedDestination() {
return getNamedDestination(false);
}
/**
* Gets all the named destinations as an <CODE>HashMap</CODE>. The key is the name
* and the value is the destinations array.
* @param keepNames true if you want the keys to be real PdfNames instead of Strings
* @return gets all the named destinations
* @since 2.1.6
*/
public HashMap getNamedDestination(boolean keepNames) {
HashMap names = getNamedDestinationFromNames(keepNames);
names.putAll(getNamedDestinationFromStrings());
return names;
}
/**
* Gets the named destinations from the /Dests key in the catalog as an <CODE>HashMap</CODE>. The key is the name
* and the value is the destinations array.
* @return gets the named destinations
*/
public HashMap getNamedDestinationFromNames() {
return getNamedDestinationFromNames(false);
}
/**
* Gets the named destinations from the /Dests key in the catalog as an <CODE>HashMap</CODE>. The key is the name
* and the value is the destinations array.
* @param keepNames true if you want the keys to be real PdfNames instead of Strings
* @return gets the named destinations
* @since 2.1.6
*/
public HashMap getNamedDestinationFromNames(boolean keepNames) {
HashMap names = new HashMap();
if (catalog.get(PdfName.DESTS) != null) {
PdfDictionary dic = (PdfDictionary)getPdfObjectRelease(catalog.get(PdfName.DESTS));
if (dic == null)
return names;
Set keys = dic.getKeys();
for (Iterator it = keys.iterator(); it.hasNext();) {
PdfName key = (PdfName)it.next();
PdfArray arr = getNameArray(dic.get(key));
if (arr == null)
continue;
if (keepNames) {
names.put(key, arr);
}
else {
String name = PdfName.decodeName(key.toString());
names.put(name, arr);
}
}
}
return names;
}
/**
* Gets the named destinations from the /Names key in the catalog as an <CODE>HashMap</CODE>. The key is the name
* and the value is the destinations array.
* @return gets the named destinations
*/
public HashMap getNamedDestinationFromStrings() {
if (catalog.get(PdfName.NAMES) != null) {
PdfDictionary dic = (PdfDictionary)getPdfObjectRelease(catalog.get(PdfName.NAMES));
if (dic != null) {
dic = (PdfDictionary)getPdfObjectRelease(dic.get(PdfName.DESTS));
if (dic != null) {
HashMap names = PdfNameTree.readTree(dic);
for (Iterator it = names.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry)it.next();
PdfArray arr = getNameArray((PdfObject)entry.getValue());
if (arr != null)
entry.setValue(arr);
else
it.remove();
}
return names;
}
}
}
return new HashMap();
}
private boolean replaceNamedDestination(PdfObject obj, HashMap names) {
obj = getPdfObject(obj);
int objIdx = lastXrefPartial;
releaseLastXrefPartial();
if (obj != null && obj.isDictionary()) {
PdfObject ob2 = getPdfObjectRelease(((PdfDictionary)obj).get(PdfName.DEST));
Object name = null;
if (ob2 != null) {
if (ob2.isName())
name = ob2;
else if (ob2.isString())
name = ob2.toString();
PdfArray dest = (PdfArray)names.get(name);
if (dest != null) {
((PdfDictionary)obj).put(PdfName.DEST, dest);
setXrefPartialObject(objIdx, obj);
return true;
}
}
else if ((ob2 = getPdfObject(((PdfDictionary)obj).get(PdfName.A))) != null) {
int obj2Idx = lastXrefPartial;
releaseLastXrefPartial();
PdfDictionary dic = (PdfDictionary)ob2;
PdfName type = (PdfName)getPdfObjectRelease(dic.get(PdfName.S));
if (PdfName.GOTO.equals(type)) {
PdfObject ob3 = getPdfObjectRelease(dic.get(PdfName.D));
if (ob3 != null) {
if (ob3.isName())
name = ob3;
else if (ob3.isString())
name = ob3.toString();
}
PdfArray dest = (PdfArray)names.get(name);
if (dest != null) {
dic.put(PdfName.D, dest);
setXrefPartialObject(obj2Idx, ob2);
setXrefPartialObject(objIdx, obj);
return true;
}
}
}
}
return false;
}
/**
* Removes all the fields from the document.
*/
public void removeFields() {
pageRefs.resetReleasePage();
for (int k = 1; k <= pageRefs.size(); ++k) {
PdfDictionary page = pageRefs.getPageN(k);
PdfArray annots = page.getAsArray(PdfName.ANNOTS);
if (annots == null) {
pageRefs.releasePage(k);
continue;
}
for (int j = 0; j < annots.size(); ++j) {
PdfObject obj = getPdfObjectRelease(annots.getPdfObject(j));
if (obj == null || !obj.isDictionary())
continue;
PdfDictionary annot = (PdfDictionary)obj;
if (PdfName.WIDGET.equals(annot.get(PdfName.SUBTYPE)))
annots.remove(j--);
}
if (annots.isEmpty())
page.remove(PdfName.ANNOTS);
else
pageRefs.releasePage(k);
}
catalog.remove(PdfName.ACROFORM);
pageRefs.resetReleasePage();
}
/**
* Removes all the annotations and fields from the document.
*/
public void removeAnnotations() {
pageRefs.resetReleasePage();
for (int k = 1; k <= pageRefs.size(); ++k) {
PdfDictionary page = pageRefs.getPageN(k);
if (page.get(PdfName.ANNOTS) == null)
pageRefs.releasePage(k);
else
page.remove(PdfName.ANNOTS);
}
catalog.remove(PdfName.ACROFORM);
pageRefs.resetReleasePage();
}
public ArrayList getLinks(int page) {
pageRefs.resetReleasePage();
ArrayList result = new ArrayList();
PdfDictionary pageDic = pageRefs.getPageN(page);
if (pageDic.get(PdfName.ANNOTS) != null) {
PdfArray annots = pageDic.getAsArray(PdfName.ANNOTS);
for (int j = 0; j < annots.size(); ++j) {
PdfDictionary annot = (PdfDictionary)getPdfObjectRelease(annots.getPdfObject(j));
if (PdfName.LINK.equals(annot.get(PdfName.SUBTYPE))) {
result.add(new PdfAnnotation.PdfImportedLink(annot));
}
}
}
pageRefs.releasePage(page);
pageRefs.resetReleasePage();
return result;
}
private void iterateBookmarks(PdfObject outlineRef, HashMap names) {
while (outlineRef != null) {
replaceNamedDestination(outlineRef, names);
PdfDictionary outline = (PdfDictionary)getPdfObjectRelease(outlineRef);
PdfObject first = outline.get(PdfName.FIRST);
if (first != null) {
iterateBookmarks(first, names);
}
outlineRef = outline.get(PdfName.NEXT);
}
}
/** Replaces all the local named links with the actual destinations. */
public void consolidateNamedDestinations() {
if (consolidateNamedDestinations)
return;
consolidateNamedDestinations = true;
HashMap names = getNamedDestination(true);
if (names.isEmpty())
return;
for (int k = 1; k <= pageRefs.size(); ++k) {
PdfDictionary page = pageRefs.getPageN(k);
PdfObject annotsRef;
PdfArray annots = (PdfArray)getPdfObject(annotsRef = page.get(PdfName.ANNOTS));
int annotIdx = lastXrefPartial;
releaseLastXrefPartial();
if (annots == null) {
pageRefs.releasePage(k);
continue;
}
boolean commitAnnots = false;
for (int an = 0; an < annots.size(); ++an) {
PdfObject objRef = annots.getPdfObject(an);
if (replaceNamedDestination(objRef, names) && !objRef.isIndirect())
commitAnnots = true;
}
if (commitAnnots)
setXrefPartialObject(annotIdx, annots);
if (!commitAnnots || annotsRef.isIndirect())
pageRefs.releasePage(k);
}
PdfDictionary outlines = (PdfDictionary)getPdfObjectRelease(catalog.get(PdfName.OUTLINES));
if (outlines == null)
return;
iterateBookmarks(outlines.get(PdfName.FIRST), names);
}
protected static PdfDictionary duplicatePdfDictionary(PdfDictionary original, PdfDictionary copy, PdfReader newReader) {
if (copy == null)
copy = new PdfDictionary();
for (Iterator it = original.getKeys().iterator(); it.hasNext();) {
PdfName key = (PdfName)it.next();
copy.put(key, duplicatePdfObject(original.get(key), newReader));
}
return copy;
}
protected static PdfObject duplicatePdfObject(PdfObject original, PdfReader newReader) {
if (original == null)
return null;
switch (original.type()) {
case PdfObject.DICTIONARY: {
return duplicatePdfDictionary((PdfDictionary)original, null, newReader);
}
case PdfObject.STREAM: {
PRStream org = (PRStream)original;
PRStream stream = new PRStream(org, null, newReader);
duplicatePdfDictionary(org, stream, newReader);
return stream;
}
case PdfObject.ARRAY: {
PdfArray arr = new PdfArray();
for (Iterator it = ((PdfArray)original).listIterator(); it.hasNext();) {
arr.add(duplicatePdfObject((PdfObject)it.next(), newReader));
}
return arr;
}
case PdfObject.INDIRECT: {
PRIndirectReference org = (PRIndirectReference)original;
return new PRIndirectReference(newReader, org.getNumber(), org.getGeneration());
}
default:
return original;
}
}
/**
* Closes the reader
*/
public void close() {
if (!partial)
return;
try {
tokens.close();
}
catch (IOException e) {
throw new ExceptionConverter(e);
}
}
protected void removeUnusedNode(PdfObject obj, boolean hits[]) {
Stack state = new Stack();
state.push(obj);
while (!state.empty()) {
Object current = state.pop();
if (current == null)
continue;
ArrayList ar = null;
PdfDictionary dic = null;
PdfName[] keys = null;
Object[] objs = null;
int idx = 0;
if (current instanceof PdfObject) {
obj = (PdfObject)current;
switch (obj.type()) {
case PdfObject.DICTIONARY:
case PdfObject.STREAM:
dic = (PdfDictionary)obj;
keys = new PdfName[dic.size()];
dic.getKeys().toArray(keys);
break;
case PdfObject.ARRAY:
ar = ((PdfArray)obj).getArrayList();
break;
case PdfObject.INDIRECT:
PRIndirectReference ref = (PRIndirectReference)obj;
int num = ref.getNumber();
if (!hits[num]) {
hits[num] = true;
state.push(getPdfObjectRelease(ref));
}
continue;
default:
continue;
}
}
else {
objs = (Object[])current;
if (objs[0] instanceof ArrayList) {
ar = (ArrayList)objs[0];
idx = ((Integer)objs[1]).intValue();
}
else {
keys = (PdfName[])objs[0];
dic = (PdfDictionary)objs[1];
idx = ((Integer)objs[2]).intValue();
}
}
if (ar != null) {
for (int k = idx; k < ar.size(); ++k) {
PdfObject v = (PdfObject)ar.get(k);
if (v.isIndirect()) {
int num = ((PRIndirectReference)v).getNumber();
if (num >= xrefObj.size() || (!partial && xrefObj.get(num) == null)) {
ar.set(k, PdfNull.PDFNULL);
continue;
}
}
if (objs == null)
state.push(new Object[]{ar, new Integer(k + 1)});
else {
objs[1] = new Integer(k + 1);
state.push(objs);
}
state.push(v);
break;
}
}
else {
for (int k = idx; k < keys.length; ++k) {
PdfName key = keys[k];
PdfObject v = dic.get(key);
if (v.isIndirect()) {
int num = ((PRIndirectReference)v).getNumber();
if (num >= xrefObj.size() || (!partial && xrefObj.get(num) == null)) {
dic.put(key, PdfNull.PDFNULL);
continue;
}
}
if (objs == null)
state.push(new Object[]{keys, dic, new Integer(k + 1)});
else {
objs[2] = new Integer(k + 1);
state.push(objs);
}
state.push(v);
break;
}
}
}
}
/** Removes all the unreachable objects.
* @return the number of indirect objects removed
*/
public int removeUnusedObjects() {
boolean hits[] = new boolean[xrefObj.size()];
removeUnusedNode(trailer, hits);
int total = 0;
if (partial) {
for (int k = 1; k < hits.length; ++k) {
if (!hits[k]) {
xref[k * 2] = -1;
xref[k * 2 + 1] = 0;
xrefObj.set(k, null);
++total;
}
}
}
else {
for (int k = 1; k < hits.length; ++k) {
if (!hits[k]) {
xrefObj.set(k, null);
++total;
}
}
}
return total;
}
/** Gets a read-only version of <CODE>AcroFields</CODE>.
* @return a read-only version of <CODE>AcroFields</CODE>
*/
public AcroFields getAcroFields() {
return new AcroFields(this, null);
}
/**
* Gets the global document JavaScript.
* @param file the document file
* @throws IOException on error
* @return the global document JavaScript
*/
public String getJavaScript(RandomAccessFileOrArray file) throws IOException {
PdfDictionary names = (PdfDictionary)getPdfObjectRelease(catalog.get(PdfName.NAMES));
if (names == null)
return null;
PdfDictionary js = (PdfDictionary)getPdfObjectRelease(names.get(PdfName.JAVASCRIPT));
if (js == null)
return null;
HashMap jscript = PdfNameTree.readTree(js);
String sortedNames[] = new String[jscript.size()];
sortedNames = (String[])jscript.keySet().toArray(sortedNames);
Arrays.sort(sortedNames);
StringBuffer buf = new StringBuffer();
for (int k = 0; k < sortedNames.length; ++k) {
PdfDictionary j = (PdfDictionary)getPdfObjectRelease((PdfIndirectReference)jscript.get(sortedNames[k]));
if (j == null)
continue;
PdfObject obj = getPdfObjectRelease(j.get(PdfName.JS));
if (obj != null) {
if (obj.isString())
buf.append(((PdfString)obj).toUnicodeString()).append('\n');
else if (obj.isStream()) {
byte bytes[] = getStreamBytes((PRStream)obj, file);
if (bytes.length >= 2 && bytes[0] == (byte)254 && bytes[1] == (byte)255)
buf.append(PdfEncodings.convertToString(bytes, PdfObject.TEXT_UNICODE));
else
buf.append(PdfEncodings.convertToString(bytes, PdfObject.TEXT_PDFDOCENCODING));
buf.append('\n');
}
}
}
return buf.toString();
}
/**
* Gets the global document JavaScript.
* @throws IOException on error
* @return the global document JavaScript
*/
public String getJavaScript() throws IOException {
RandomAccessFileOrArray rf = getSafeFile();
try {
rf.reOpen();
return getJavaScript(rf);
}
finally {
try{rf.close();}catch(Exception e){}
}
}
/**
* Selects the pages to keep in the document. The pages are described as
* ranges. The page ordering can be changed but
* no page repetitions are allowed. Note that it may be very slow in partial mode.
* @param ranges the comma separated ranges as described in {@link SequenceList}
*/
public void selectPages(String ranges) {
selectPages(SequenceList.expand(ranges, getNumberOfPages()));
}
/**
* Selects the pages to keep in the document. The pages are described as a
* <CODE>List</CODE> of <CODE>Integer</CODE>. The page ordering can be changed but
* no page repetitions are allowed. Note that it may be very slow in partial mode.
* @param pagesToKeep the pages to keep in the document
*/
public void selectPages(List pagesToKeep) {
pageRefs.selectPages(pagesToKeep);
removeUnusedObjects();
}
/** Sets the viewer preferences as the sum of several constants.
* @param preferences the viewer preferences
* @see PdfViewerPreferences#setViewerPreferences
*/
public void setViewerPreferences(int preferences) {
this.viewerPreferences.setViewerPreferences(preferences);
setViewerPreferences(this.viewerPreferences);
}
/** Adds a viewer preference
* @param key a key for a viewer preference
* @param value a value for the viewer preference
* @see PdfViewerPreferences#addViewerPreference
*/
public void addViewerPreference(PdfName key, PdfObject value) {
this.viewerPreferences.addViewerPreference(key, value);
setViewerPreferences(this.viewerPreferences);
}
void setViewerPreferences(PdfViewerPreferencesImp vp) {
vp.addToCatalog(catalog);
}
/**
* Returns a bitset representing the PageMode and PageLayout viewer preferences.
* Doesn't return any information about the ViewerPreferences dictionary.
* @return an int that contains the Viewer Preferences.
*/
public int getSimpleViewerPreferences() {
return PdfViewerPreferencesImp.getViewerPreferences(catalog).getPageLayoutAndMode();
}
/**
* Getter for property appendable.
* @return Value of property appendable.
*/
public boolean isAppendable() {
return this.appendable;
}
/**
* Setter for property appendable.
* @param appendable New value of property appendable.
*/
public void setAppendable(boolean appendable) {
this.appendable = appendable;
if (appendable)
getPdfObject(trailer.get(PdfName.ROOT));
}
/**
* Getter for property newXrefType.
* @return Value of property newXrefType.
*/
public boolean isNewXrefType() {
return newXrefType;
}
/**
* Getter for property fileLength.
* @return Value of property fileLength.
*/
public int getFileLength() {
return fileLength;
}
/**
* Getter for property hybridXref.
* @return Value of property hybridXref.
*/
public boolean isHybridXref() {
return hybridXref;
}
static class PageRefs {
private PdfReader reader;
private IntHashtable refsp;
private ArrayList refsn;
private ArrayList pageInh;
private int lastPageRead = -1;
private int sizep;
private boolean keepPages;
private PageRefs(PdfReader reader) throws IOException {
this.reader = reader;
if (reader.partial) {
refsp = new IntHashtable();
PdfNumber npages = (PdfNumber)PdfReader.getPdfObjectRelease(reader.rootPages.get(PdfName.COUNT));
sizep = npages.intValue();
}
else {
readPages();
}
}
PageRefs(PageRefs other, PdfReader reader) {
this.reader = reader;
this.sizep = other.sizep;
if (other.refsn != null) {
refsn = new ArrayList(other.refsn);
for (int k = 0; k < refsn.size(); ++k) {
refsn.set(k, duplicatePdfObject((PdfObject)refsn.get(k), reader));
}
}
else
this.refsp = (IntHashtable)other.refsp.clone();
}
int size() {
if (refsn != null)
return refsn.size();
else
return sizep;
}
void readPages() throws IOException {
if (refsn != null)
return;
refsp = null;
refsn = new ArrayList();
pageInh = new ArrayList();
iteratePages((PRIndirectReference)reader.catalog.get(PdfName.PAGES));
pageInh = null;
reader.rootPages.put(PdfName.COUNT, new PdfNumber(refsn.size()));
}
void reReadPages() throws IOException {
refsn = null;
readPages();
}
/** Gets the dictionary that represents a page.
* @param pageNum the page number. 1 is the first
* @return the page dictionary
*/
public PdfDictionary getPageN(int pageNum) {
PRIndirectReference ref = getPageOrigRef(pageNum);
return (PdfDictionary)PdfReader.getPdfObject(ref);
}
/**
* @param pageNum
* @return a dictionary object
*/
public PdfDictionary getPageNRelease(int pageNum) {
PdfDictionary page = getPageN(pageNum);
releasePage(pageNum);
return page;
}
/**
* @param pageNum
* @return an indirect reference
*/
public PRIndirectReference getPageOrigRefRelease(int pageNum) {
PRIndirectReference ref = getPageOrigRef(pageNum);
releasePage(pageNum);
return ref;
}
/** Gets the page reference to this page.
* @param pageNum the page number. 1 is the first
* @return the page reference
*/
public PRIndirectReference getPageOrigRef(int pageNum) {
try {
--pageNum;
if (pageNum < 0 || pageNum >= size())
return null;
if (refsn != null)
return (PRIndirectReference)refsn.get(pageNum);
else {
int n = refsp.get(pageNum);
if (n == 0) {
PRIndirectReference ref = getSinglePage(pageNum);
if (reader.lastXrefPartial == -1)
lastPageRead = -1;
else
lastPageRead = pageNum;
reader.lastXrefPartial = -1;
refsp.put(pageNum, ref.getNumber());
if (keepPages)
lastPageRead = -1;
return ref;
}
else {
if (lastPageRead != pageNum)
lastPageRead = -1;
if (keepPages)
lastPageRead = -1;
return new PRIndirectReference(reader, n);
}
}
}
catch (Exception e) {
throw new ExceptionConverter(e);
}
}
void keepPages() {
if (refsp == null || keepPages)
return;
keepPages = true;
refsp.clear();
}
/**
* @param pageNum
*/
public void releasePage(int pageNum) {
if (refsp == null)
return;
--pageNum;
if (pageNum < 0 || pageNum >= size())
return;
if (pageNum != lastPageRead)
return;
lastPageRead = -1;
reader.lastXrefPartial = refsp.get(pageNum);
reader.releaseLastXrefPartial();
refsp.remove(pageNum);
}
/**
*
*/
public void resetReleasePage() {
if (refsp == null)
return;
lastPageRead = -1;
}
void insertPage(int pageNum, PRIndirectReference ref) {
--pageNum;
if (refsn != null) {
if (pageNum >= refsn.size())
refsn.add(ref);
else
refsn.add(pageNum, ref);
}
else {
++sizep;
lastPageRead = -1;
if (pageNum >= size()) {
refsp.put(size(), ref.getNumber());
}
else {
IntHashtable refs2 = new IntHashtable((refsp.size() + 1) * 2);
for (Iterator it = refsp.getEntryIterator(); it.hasNext();) {
IntHashtable.Entry entry = (IntHashtable.Entry)it.next();
int p = entry.getKey();
refs2.put(p >= pageNum ? p + 1 : p, entry.getValue());
}
refs2.put(pageNum, ref.getNumber());
refsp = refs2;
}
}
}
private void pushPageAttributes(PdfDictionary nodePages) {
PdfDictionary dic = new PdfDictionary();
if (!pageInh.isEmpty()) {
dic.putAll((PdfDictionary)pageInh.get(pageInh.size() - 1));
}
for (int k = 0; k < pageInhCandidates.length; ++k) {
PdfObject obj = nodePages.get(pageInhCandidates[k]);
if (obj != null)
dic.put(pageInhCandidates[k], obj);
}
pageInh.add(dic);
}
private void popPageAttributes() {
pageInh.remove(pageInh.size() - 1);
}
private void iteratePages(PRIndirectReference rpage) throws IOException {
PdfDictionary page = (PdfDictionary)getPdfObject(rpage);
PdfArray kidsPR = page.getAsArray(PdfName.KIDS);
if (kidsPR == null) {
page.put(PdfName.TYPE, PdfName.PAGE);
PdfDictionary dic = (PdfDictionary)pageInh.get(pageInh.size() - 1);
PdfName key;
for (Iterator i = dic.getKeys().iterator(); i.hasNext();) {
key = (PdfName)i.next();
if (page.get(key) == null)
page.put(key, dic.get(key));
}
if (page.get(PdfName.MEDIABOX) == null) {
PdfArray arr = new PdfArray(new float[]{0,0,PageSize.LETTER.getRight(),PageSize.LETTER.getTop()});
page.put(PdfName.MEDIABOX, arr);
}
refsn.add(rpage);
}
else {
page.put(PdfName.TYPE, PdfName.PAGES);
pushPageAttributes(page);
for (int k = 0; k < kidsPR.size(); ++k){
PdfObject obj = kidsPR.getPdfObject(k);
if (!obj.isIndirect()) {
while (k < kidsPR.size())
kidsPR.remove(k);
break;
}
iteratePages((PRIndirectReference)obj);
}
popPageAttributes();
}
}
protected PRIndirectReference getSinglePage(int n) {
PdfDictionary acc = new PdfDictionary();
PdfDictionary top = reader.rootPages;
int base = 0;
while (true) {
for (int k = 0; k < pageInhCandidates.length; ++k) {
PdfObject obj = top.get(pageInhCandidates[k]);
if (obj != null)
acc.put(pageInhCandidates[k], obj);
}
PdfArray kids = (PdfArray)PdfReader.getPdfObjectRelease(top.get(PdfName.KIDS));
for (Iterator it = kids.listIterator(); it.hasNext();) {
PRIndirectReference ref = (PRIndirectReference)it.next();
PdfDictionary dic = (PdfDictionary)getPdfObject(ref);
int last = reader.lastXrefPartial;
PdfObject count = getPdfObjectRelease(dic.get(PdfName.COUNT));
reader.lastXrefPartial = last;
int acn = 1;
if (count != null && count.type() == PdfObject.NUMBER)
acn = ((PdfNumber)count).intValue();
if (n < base + acn) {
if (count == null) {
dic.mergeDifferent(acc);
return ref;
}
reader.releaseLastXrefPartial();
top = dic;
break;
}
reader.releaseLastXrefPartial();
base += acn;
}
}
}
private void selectPages(List pagesToKeep) {
IntHashtable pg = new IntHashtable();
ArrayList finalPages = new ArrayList();
int psize = size();
for (Iterator it = pagesToKeep.iterator(); it.hasNext();) {
Integer pi = (Integer)it.next();
int p = pi.intValue();
if (p >= 1 && p <= psize && pg.put(p, 1) == 0)
finalPages.add(pi);
}
if (reader.partial) {
for (int k = 1; k <= psize; ++k) {
getPageOrigRef(k);
resetReleasePage();
}
}
PRIndirectReference parent = (PRIndirectReference)reader.catalog.get(PdfName.PAGES);
PdfDictionary topPages = (PdfDictionary)PdfReader.getPdfObject(parent);
ArrayList newPageRefs = new ArrayList(finalPages.size());
PdfArray kids = new PdfArray();
for (int k = 0; k < finalPages.size(); ++k) {
int p = ((Integer)finalPages.get(k)).intValue();
PRIndirectReference pref = getPageOrigRef(p);
resetReleasePage();
kids.add(pref);
newPageRefs.add(pref);
getPageN(p).put(PdfName.PARENT, parent);
}
AcroFields af = reader.getAcroFields();
boolean removeFields = (af.getFields().size() > 0);
for (int k = 1; k <= psize; ++k) {
if (!pg.containsKey(k)) {
if (removeFields)
af.removeFieldsFromPage(k);
PRIndirectReference pref = getPageOrigRef(k);
int nref = pref.getNumber();
reader.xrefObj.set(nref, null);
if (reader.partial) {
reader.xref[nref * 2] = -1;
reader.xref[nref * 2 + 1] = 0;
}
}
}
topPages.put(PdfName.COUNT, new PdfNumber(finalPages.size()));
topPages.put(PdfName.KIDS, kids);
refsp = null;
refsn = newPageRefs;
}
}
PdfIndirectReference getCryptoRef() {
if (cryptoRef == null)
return null;
return new PdfIndirectReference(0, cryptoRef.getNumber(), cryptoRef.getGeneration());
}
/**
* Removes any usage rights that this PDF may have. Only Adobe can grant usage rights
* and any PDF modification with iText will invalidate them. Invalidated usage rights may
* confuse Acrobat and it's advisable to remove them altogether.
*/
public void removeUsageRights() {
PdfDictionary perms = catalog.getAsDict(PdfName.PERMS);
if (perms == null)
return;
perms.remove(PdfName.UR);
perms.remove(PdfName.UR3);
if (perms.size() == 0)
catalog.remove(PdfName.PERMS);
}
/**
* Gets the certification level for this document. The return values can be <code>PdfSignatureAppearance.NOT_CERTIFIED</code>,
* <code>PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED</code>,
* <code>PdfSignatureAppearance.CERTIFIED_FORM_FILLING</code> and
* <code>PdfSignatureAppearance.CERTIFIED_FORM_FILLING_AND_ANNOTATIONS</code>.
* <p>
* No signature validation is made, use the methods available for that in <CODE>AcroFields</CODE>.
* </p>
* @return gets the certification level for this document
*/
public int getCertificationLevel() {
PdfDictionary dic = catalog.getAsDict(PdfName.PERMS);
if (dic == null)
return PdfSignatureAppearance.NOT_CERTIFIED;
dic = dic.getAsDict(PdfName.DOCMDP);
if (dic == null)
return PdfSignatureAppearance.NOT_CERTIFIED;
PdfArray arr = dic.getAsArray(PdfName.REFERENCE);
if (arr == null || arr.size() == 0)
return PdfSignatureAppearance.NOT_CERTIFIED;
dic = arr.getAsDict(0);
if (dic == null)
return PdfSignatureAppearance.NOT_CERTIFIED;
dic = dic.getAsDict(PdfName.TRANSFORMPARAMS);
if (dic == null)
return PdfSignatureAppearance.NOT_CERTIFIED;
PdfNumber p = dic.getAsNumber(PdfName.P);
if (p == null)
return PdfSignatureAppearance.NOT_CERTIFIED;
return p.intValue();
}
/**
* Checks if the document was opened with the owner password so that the end application
* can decide what level of access restrictions to apply. If the document is not encrypted
* it will return <CODE>true</CODE>.
* @return <CODE>true</CODE> if the document was opened with the owner password or if it's not encrypted,
* <CODE>false</CODE> if the document was opened with the user password
*/
public final boolean isOpenedWithFullPermissions() {
return !encrypted || ownerPasswordUsed;
}
public int getCryptoMode() {
if (decrypt == null)
return -1;
else
return decrypt.getCryptoMode();
}
public boolean isMetadataEncrypted() {
if (decrypt == null)
return false;
else
return decrypt.isMetadataEncrypted();
}
public byte[] computeUserPassword() {
if (!encrypted || !ownerPasswordUsed) return null;
return decrypt.computeUserPassword(password);
}
}
|