File size: 100,810 Bytes
3a3c77b | 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 | # Copyright (c) 2006, Mathieu Fenniak
# Copyright (c) 2007, Ashish Kulkarni <kulkarni.ashish@gmail.com>
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * The name of the author may not be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import math
from collections.abc import Iterable, Iterator, Sequence
from copy import deepcopy
from dataclasses import asdict, dataclass
from decimal import Decimal
from io import BytesIO
from pathlib import Path
from typing import (
Any,
Callable,
Literal,
Optional,
Union,
cast,
overload,
)
from ._font import Font
from ._protocols import PdfCommonDocProtocol
from ._text_extraction import (
_layout_mode,
)
from ._text_extraction._text_extractor import TextExtraction
from ._utils import (
CompressedTransformationMatrix,
TransformationMatrixType,
_human_readable_bytes,
_TraversalState,
deprecate,
deprecate_no_replacement,
deprecate_with_replacement,
logger_warning,
matrix_multiply,
)
from .actions import Action, PageTrigger
from .constants import (
_INLINE_IMAGE_KEY_MAPPING,
_INLINE_IMAGE_VALUE_MAPPING,
AnnotationDictionaryAttributes,
ImageAttributes,
)
from .constants import PageAttributes as PG
from .constants import Resources as RES
from .errors import PageSizeNotDefinedError, PdfReadError
from .generic import (
ArrayObject,
ContentStream,
DictionaryObject,
EncodedStreamObject,
FloatObject,
IndirectObject,
NameObject,
NullObject,
NumberObject,
PdfObject,
RectangleObject,
StreamObject,
is_null_or_none,
)
try:
from PIL.Image import Image
pil_not_imported = False
except ImportError:
Image = object # type: ignore[assignment,misc,unused-ignore] # TODO: Remove unused-ignore on Python 3.10
pil_not_imported = True # error will be raised only when using images
MERGE_CROP_BOX = "cropbox" # pypdf <= 3.4.0 used "trimbox"
# TODO: Make configurable.
MAX_XFORM_INVOCATIONS_PER_EXTRACTION = 5_000
def _get_rectangle(self: Any, name: str, defaults: Iterable[str]) -> RectangleObject:
retval: Union[RectangleObject, ArrayObject, IndirectObject, None] = self.get(name)
if isinstance(retval, RectangleObject):
return retval
if is_null_or_none(retval):
for d in defaults:
retval = self.get(d)
if retval is not None:
break
if isinstance(retval, IndirectObject):
retval = self.pdf.get_object(retval)
if isinstance(retval, ArrayObject) and (length := len(retval)) != 4:
if length > 4:
# Keep backwards-compatibility with files previously written in a
# broken way by pypdf, which carried more than four values.
logger_warning(
"Expected four values, got %(length)d: %(retval)s",
source=__name__,
length=length,
retval=retval,
)
retval = RectangleObject(tuple(retval[:4]))
else:
raise ValueError(
f"Expected four values for {name}, got {length}: {retval}"
)
else:
retval = RectangleObject(retval) # type: ignore[arg-type]
_set_rectangle(self, name, retval)
return retval
def _set_rectangle(self: Any, name: str, value: Union[RectangleObject, float]) -> None:
self[NameObject(name)] = value
def _delete_rectangle(self: Any, name: str) -> None:
del self[name]
def _create_rectangle_accessor(name: str, fallback: Iterable[str]) -> property:
return property(
lambda self: _get_rectangle(self, name, fallback),
lambda self, value: _set_rectangle(self, name, value),
lambda self: _delete_rectangle(self, name),
)
class Transformation:
"""
Represent a 2D transformation.
The transformation between two coordinate systems is represented by a 3-by-3
transformation matrix with the following form::
a b 0
c d 0
e f 1
Because a transformation matrix has only six elements that can be changed,
it is usually specified in PDF as the six-element array [ a b c d e f ].
Coordinate transformations are expressed as matrix multiplications::
a b 0
[ x′ y′ 1 ] = [ x y 1 ] × c d 0
e f 1
Example:
>>> from pypdf import PdfWriter, Transformation
>>> page = PdfWriter().add_blank_page(800, 600)
>>> op = Transformation().scale(sx=2, sy=3).translate(tx=10, ty=20)
>>> page.add_transformation(op)
"""
def __init__(self, ctm: CompressedTransformationMatrix = (1, 0, 0, 1, 0, 0)) -> None:
self.ctm = ctm
@property
def matrix(self) -> TransformationMatrixType:
"""
Return the transformation matrix as a tuple of tuples in the form:
((a, b, 0), (c, d, 0), (e, f, 1))
"""
return (
(self.ctm[0], self.ctm[1], 0),
(self.ctm[2], self.ctm[3], 0),
(self.ctm[4], self.ctm[5], 1),
)
@staticmethod
def compress(matrix: TransformationMatrixType) -> CompressedTransformationMatrix:
"""
Compresses the transformation matrix into a tuple of (a, b, c, d, e, f).
Args:
matrix: The transformation matrix as a tuple of tuples.
Returns:
A tuple representing the transformation matrix as (a, b, c, d, e, f)
"""
return (
matrix[0][0],
matrix[0][1],
matrix[1][0],
matrix[1][1],
matrix[2][0],
matrix[2][1],
)
def _to_cm(self) -> str:
# Returns the cm operation string for the given transformation matrix
return (
f"{self.ctm[0]:.4f} {self.ctm[1]:.4f} {self.ctm[2]:.4f} "
f"{self.ctm[3]:.4f} {self.ctm[4]:.4f} {self.ctm[5]:.4f} cm"
)
def transform(self, m: "Transformation") -> "Transformation":
"""
Apply one transformation to another.
Args:
m: a Transformation to apply.
Returns:
A new ``Transformation`` instance
Example:
>>> from pypdf import PdfWriter, Transformation
>>> height, width = 40, 50
>>> page = PdfWriter().add_blank_page(800, 600)
>>> op = Transformation((1, 0, 0, -1, 0, height)) # vertical mirror
>>> op = Transformation().transform(Transformation((-1, 0, 0, 1, width, 0))) # horizontal mirror
>>> page.add_transformation(op)
"""
ctm = Transformation.compress(matrix_multiply(self.matrix, m.matrix))
return Transformation(ctm)
def translate(self, tx: float = 0, ty: float = 0) -> "Transformation":
"""
Translate the contents of a page.
Args:
tx: The translation along the x-axis.
ty: The translation along the y-axis.
Returns:
A new ``Transformation`` instance
"""
m = self.ctm
return Transformation(ctm=(m[0], m[1], m[2], m[3], m[4] + tx, m[5] + ty))
def scale(
self, sx: Optional[float] = None, sy: Optional[float] = None
) -> "Transformation":
"""
Scale the contents of a page towards the origin of the coordinate system.
Typically, that is the lower-left corner of the page. That can be
changed by translating the contents / the page boxes.
Args:
sx: The scale factor along the x-axis.
sy: The scale factor along the y-axis.
Returns:
A new Transformation instance with the scaled matrix.
"""
if sx is None and sy is None:
raise ValueError("Either sx or sy must be specified")
if sx is None:
sx = sy
if sy is None:
sy = sx
assert sx is not None
assert sy is not None
op: TransformationMatrixType = ((sx, 0, 0), (0, sy, 0), (0, 0, 1))
ctm = Transformation.compress(matrix_multiply(self.matrix, op))
return Transformation(ctm)
def rotate(self, rotation: float) -> "Transformation":
"""
Rotate the contents of a page.
Args:
rotation: The angle of rotation in degrees.
Returns:
A new ``Transformation`` instance with the rotated matrix.
"""
rotation = math.radians(rotation)
op: TransformationMatrixType = (
(math.cos(rotation), math.sin(rotation), 0),
(-math.sin(rotation), math.cos(rotation), 0),
(0, 0, 1),
)
ctm = Transformation.compress(matrix_multiply(self.matrix, op))
return Transformation(ctm)
def __repr__(self) -> str:
return f"Transformation(ctm={self.ctm})"
@overload
def apply_on(self, pt: list[float], as_object: bool = False) -> list[float]:
...
@overload
def apply_on(
self, pt: tuple[float, float], as_object: bool = False
) -> tuple[float, float]:
...
def apply_on(
self,
pt: Union[tuple[float, float], list[float]],
as_object: bool = False,
) -> Union[tuple[float, float], list[float]]:
"""
Apply the transformation matrix on the given point.
Args:
pt: A tuple or list representing the point in the form (x, y).
as_object: If True, return items as FloatObject, otherwise as plain floats.
Returns:
A tuple or list representing the transformed point in the form (x', y')
"""
typ = FloatObject if as_object else float
pt1 = (
typ(float(pt[0]) * self.ctm[0] + float(pt[1]) * self.ctm[2] + self.ctm[4]),
typ(float(pt[0]) * self.ctm[1] + float(pt[1]) * self.ctm[3] + self.ctm[5]),
)
return list(pt1) if isinstance(pt, list) else pt1
@dataclass
class ImageFile:
"""
Image within the PDF file. *This object is not designed to be built.*
This object should not be modified except using :func:`ImageFile.replace` to replace the image with a new one.
"""
name: str = ""
"""
Filename as identified within the PDF file.
.. warning::
This value can contain arbitrary characters. Please make sure to sanitize it before
using it to write the file content to the disk for example.
"""
data: bytes = b""
"""
Data as bytes.
"""
image: Optional[Image] = None
"""
Data as PIL image.
"""
indirect_reference: Optional[IndirectObject] = None
"""
Reference to the object storing the stream.
"""
is_inline: bool = False
"""
True if this is an inline image (~0~, ~1~, etc.).
"""
is_displayed: bool = False
"""
True if this image is displayed in the page content stream.
"""
def replace(self, new_image: Image, **kwargs: Any) -> None:
"""
Replace the image with a new PIL image.
Args:
new_image (PIL.Image.Image): The new PIL image to replace the existing image.
**kwargs: Additional keyword arguments to pass to `Image.save()`.
Raises:
TypeError: If the image is inline or in a PdfReader.
TypeError: If the image does not belong to a PdfWriter.
TypeError: If `new_image` is not a PIL Image.
Note:
This method replaces the existing image with a new image.
It is not allowed for inline images or images within a PdfReader.
The `kwargs` parameter allows passing additional parameters
to `Image.save()`, such as quality.
"""
if pil_not_imported:
raise ImportError(
"pillow is required to do image extraction. "
"It can be installed via 'pip install pypdf[image]'"
)
from ._reader import PdfReader # noqa: PLC0415
from .generic import DictionaryObject, PdfObject # noqa: PLC0415
from .generic._image_xobject import _xobj_to_image # noqa: PLC0415
if self.indirect_reference is None:
raise TypeError("Cannot update an inline image.")
if not hasattr(self.indirect_reference.pdf, "_id_translated"):
raise TypeError("Cannot update an image not belonging to a PdfWriter.")
if not isinstance(new_image, Image):
raise TypeError("new_image shall be a PIL Image")
b = BytesIO()
new_image.save(b, "PDF", **kwargs)
reader = PdfReader(b)
page_image = reader.pages[0].images[0]
assert page_image.indirect_reference is not None
self.indirect_reference.pdf._objects[self.indirect_reference.idnum - 1] = (
page_image.indirect_reference.get_object()
)
cast(
PdfObject, self.indirect_reference.get_object()
).indirect_reference = self.indirect_reference
# change the object attributes
extension, byte_stream, img = _xobj_to_image(
cast(DictionaryObject, self.indirect_reference.get_object()),
pillow_parameters=kwargs,
)
assert extension is not None
self.name = self.name[: self.name.rfind(".")] + extension
self.data = byte_stream
self.image = img
def __str__(self) -> str:
return f"{self.__class__.__name__}(name={self.name}, data: {_human_readable_bytes(len(self.data))})"
def __repr__(self) -> str:
return self.__str__()[:-1] + f", hash: {hash(self.data)})"
class VirtualListImages(Sequence[ImageFile]):
"""
Provides access to images referenced within a page.
Only one copy will be returned if the usage is used on the same page multiple times.
See :func:`PageObject.images` for more details.
"""
def __init__(
self,
ids_function: Callable[[], list[Union[str, list[str]]]],
get_function: Callable[[Union[str, list[str], tuple[str]]], ImageFile],
) -> None:
self.ids_function = ids_function
self.get_function = get_function
self.current = -1
def __len__(self) -> int:
return len(self.ids_function())
def keys(self) -> list[Union[str, list[str]]]:
return self.ids_function()
def items(self) -> list[tuple[Union[str, list[str]], ImageFile]]:
return [(x, self[x]) for x in self.ids_function()]
@overload
def __getitem__(self, index: Union[int, str, list[str]]) -> ImageFile:
...
@overload
def __getitem__(self, index: slice) -> Sequence[ImageFile]:
...
def __getitem__(
self, index: Union[int, slice, str, list[str], tuple[str]]
) -> Union[ImageFile, Sequence[ImageFile]]:
lst = self.ids_function()
if isinstance(index, slice):
indices = range(*index.indices(len(self)))
lst = [lst[x] for x in indices]
cls = type(self)
return cls((lambda: lst), self.get_function)
if isinstance(index, (str, list, tuple)):
return self.get_function(index)
if not isinstance(index, int):
raise TypeError("Invalid sequence indices type")
len_self = len(lst)
if index < 0:
# support negative indexes
index += len_self
if not (0 <= index < len_self):
raise IndexError("Sequence index out of range")
return self.get_function(lst[index])
def __iter__(self) -> Iterator[ImageFile]:
for i in range(len(self)):
yield self[i]
def __str__(self) -> str:
p = [f"Image_{i}={n}" for i, n in enumerate(self.ids_function())]
return f"[{', '.join(p)}]"
class PageObject(DictionaryObject):
"""
PageObject represents a single page within a PDF file.
Typically these objects will be created by accessing the
:attr:`pages<pypdf.PdfReader.pages>` property of the
:class:`PdfReader<pypdf.PdfReader>` class, but it is
also possible to create an empty page with the
:meth:`create_blank_page()<pypdf._page.PageObject.create_blank_page>` static method.
Args:
pdf: PDF file the page belongs to.
indirect_reference: Stores the original indirect reference to
this object in its source PDF
"""
original_page: "PageObject" # very local use in writer when appending
def __init__(
self,
pdf: Optional[PdfCommonDocProtocol] = None,
indirect_reference: Optional[IndirectObject] = None,
) -> None:
DictionaryObject.__init__(self)
self.pdf = pdf
self._content_stream_images: Optional[dict[str, Optional[ImageFile]]] = None
self.indirect_reference = indirect_reference
if not is_null_or_none(indirect_reference):
assert indirect_reference is not None, "mypy"
self.update(cast(DictionaryObject, indirect_reference.get_object()))
def hash_bin(self) -> int:
"""
Used to detect modified object.
Note: this function is overloaded to return the same results
as a DictionaryObject.
Returns:
Hash considering type and value.
"""
return hash(
(DictionaryObject, tuple(((k, v.hash_bin()) for k, v in self.items())))
)
def hash_value_data(self) -> bytes:
data = super().hash_value_data()
data += f"{id(self)}".encode()
return data
@property
def user_unit(self) -> float:
"""
A read-only positive number giving the size of user space units.
It is in multiples of 1/72 inch. Hence a value of 1 means a user
space unit is 1/72 inch, and a value of 3 means that a user
space unit is 3/72 inch.
"""
return cast(float, self.get(PG.USER_UNIT, 1))
@staticmethod
def create_blank_page(
pdf: Optional[PdfCommonDocProtocol] = None,
width: Union[float, Decimal, None] = None,
height: Union[float, Decimal, None] = None,
) -> "PageObject":
"""
Return a new blank page.
If ``width`` or ``height`` is ``None``, try to get the page size
from the last page of *pdf*.
Args:
pdf: PDF file the page is within.
width: The width of the new page expressed in default user
space units.
height: The height of the new page expressed in default user
space units.
Returns:
The new blank page
Raises:
PageSizeNotDefinedError: if ``pdf`` is ``None`` or contains
no page
"""
page = PageObject(pdf)
# Creates a new page (cf PDF Reference §7.7.3.3)
page.__setitem__(NameObject(PG.TYPE), NameObject("/Page"))
page.__setitem__(NameObject(PG.PARENT), NullObject())
page.__setitem__(NameObject(PG.RESOURCES), DictionaryObject())
if width is None or height is None:
if pdf is not None and len(pdf.pages) > 0:
lastpage = pdf.pages[len(pdf.pages) - 1]
width = lastpage.mediabox.width
height = lastpage.mediabox.height
else:
raise PageSizeNotDefinedError
page.__setitem__(
NameObject(PG.MEDIABOX), RectangleObject((0, 0, width, height))
)
return page
def _get_ids_image(
self,
obj: Optional[DictionaryObject] = None,
ancest: Optional[list[str]] = None,
call_stack: Optional[list[Any]] = None,
) -> list[Union[str, list[str]]]:
if call_stack is None:
call_stack = []
_i = getattr(obj, "indirect_reference", None)
if _i in call_stack:
return []
call_stack.append(_i)
if self._content_stream_images is None:
self._content_stream_images = self._parse_images_from_content_stream()
if obj is None:
obj = self
if ancest is None:
ancest = []
lst: list[Union[str, list[str]]] = []
if (
PG.RESOURCES not in obj or
is_null_or_none(resources := obj[PG.RESOURCES]) or
RES.XOBJECT not in cast(DictionaryObject, resources)
):
# Forms without XObject resources have no images inside them
if len(ancest) > 0:
return []
# for inline images, cache dict entries are not None
return [image_name for image_name, image_value in self._content_stream_images.items() if image_value]
x_object = resources[RES.XOBJECT].get_object() # type: ignore
# Iterate through all XObject resources
for o in x_object:
# Skip non-stream objects (only process StreamObject)
if not isinstance(x_object[o], StreamObject):
continue
if x_object[o][ImageAttributes.SUBTYPE] == "/Image":
# If it's an image, add it to lst for further processing
lst.append(o if len(ancest) == 0 else [*ancest, o])
else:
# If it's a form, recursively search for images inside it
# Forms may contain images that are Do-referenced in their content stream
lst.extend(self._get_ids_image(x_object[o], [*ancest, o], call_stack))
# Removes duplicates and preserves order
deduplicated = lst.copy()
# Add inline images from _content_stream_images
for object_name, object_value in self._content_stream_images.items():
# inline images have cache populated
if object_name not in deduplicated and object_value:
deduplicated.append(object_name)
return deduplicated
def _get_image(
self,
id: Union[str, list[str], tuple[str]],
obj: Optional[DictionaryObject] = None,
) -> ImageFile:
if obj is None:
obj = cast(DictionaryObject, self)
if isinstance(id, tuple):
id = list(id)
if isinstance(id, list) and len(id) == 1:
id = id[0]
xobjs: Optional[DictionaryObject] = None
try:
xobjs = cast(
DictionaryObject, cast(DictionaryObject, obj[PG.RESOURCES])[RES.XOBJECT]
)
except KeyError as exc:
if not (id[0] == "~" and id[-1] == "~"):
raise KeyError(
f"Cannot access image object {id} without XObject resources"
) from exc
if isinstance(id, str):
if id[0] == "~" and id[-1] == "~":
if self._content_stream_images is None:
self._content_stream_images = self._parse_images_from_content_stream()
if id not in self._content_stream_images:
raise KeyError(f"Image {id} not found")
image_file = self._content_stream_images[id]
assert image_file is not None
return image_file
# Do-referenced image name (non-inline string keys like /Im0)
assert xobjs is not None
if id not in xobjs:
raise KeyError(f"Image {id} not found")
xobj = cast(DictionaryObject, xobjs[id])
if xobj.get(ImageAttributes.SUBTYPE, "") != "/Image":
raise KeyError(f"XObject {id} is not an image")
# Check if displayed (in content stream)
is_displayed = self._content_stream_images is not None and id in self._content_stream_images
from .generic._image_xobject import _xobj_to_image # noqa: PLC0415
extension, byte_stream, img = _xobj_to_image(xobj)
return ImageFile(
name=f"{id[1:]}{extension}",
data=byte_stream,
image=img,
indirect_reference=xobj.indirect_reference,
is_inline=False,
is_displayed=is_displayed,
)
# in a subobject
assert xobjs is not None
ids = id[1:]
return self._get_image(ids, cast(DictionaryObject, xobjs[id[0]]))
@property
def images(self) -> VirtualListImages:
"""
Read-only property emulating a list of images on a page.
Get a list of all images on the page. The key can be:
- A string (for the top object)
- A tuple (for images within XObject forms)
- An integer
Examples:
* `reader.pages[0].images[0]` # return first image
* `reader.pages[0].images['/I0']` # return image '/I0'
* `reader.pages[0].images['/TP1','/Image1']` # return image '/Image1' within '/TP1' XObject form
* `for img in reader.pages[0].images:` # loops through all objects
Example usage:
>>> from pypdf import PdfWriter
>>> writer = PdfWriter()
>>> page = writer.add_blank_page(800, 600)
>>> images = page.images
"""
return VirtualListImages(self._get_ids_image, self._get_image)
@property
def inline_images(self) -> Optional[dict[str, ImageFile]]:
"""
Return only inline images from the page.
.. deprecated::
Use :attr:`images` and filter by :attr:`ImageFile.is_inline` instead.
This property will be removed in pypdf 7.0.
Examples:
>>> from pypdf import PdfWriter
>>> writer = PdfWriter()
>>> page = writer.add_blank_page(800,600)
>>> for image_name, image_file in page.images.items():
... if image_file.is_inline:
... print(f"{image_name} is inline")
"""
deprecate_with_replacement(
"PageObject.inline_images",
"PageObject.images",
"7.0.0",
)
if self._content_stream_images is None:
return None
return {
image_name: image_file
for image_name, image_file in self._content_stream_images.items()
if image_file and image_file.is_inline # for inline images, image_file is populated
}
@inline_images.setter
def inline_images(self, value: Optional[dict[str, ImageFile]]) -> None:
deprecate_no_replacement(
"PageObject.inline_images",
"7.0.0",
)
if value is None:
self._content_stream_images = None
else:
assert self._content_stream_images is not None, "Can't edit inline_images before accessing images"
self._content_stream_images.update(value)
def _translate_value_inline_image(self, k: str, v: PdfObject) -> PdfObject:
"""Translate values used in inline image"""
try:
v = NameObject(_INLINE_IMAGE_VALUE_MAPPING[cast(str, v)])
except (TypeError, KeyError):
if isinstance(v, NameObject):
# It is a custom name, thus we have to look in resources.
# The only applicable case is for ColorSpace.
try:
res = cast(DictionaryObject, self["/Resources"])["/ColorSpace"]
v = cast(DictionaryObject, res)[v]
except KeyError: # for res and v
raise PdfReadError(f"Cannot find resource entry {v} for {k}")
return v
def _parse_images_from_content_stream(self) -> dict[str, Optional[ImageFile]]:
"""Load images from content stream. Includes both inline images and Do-referenced images.
This method scans the page content stream and extracts:
1. **Inline images** (~0~, ~1~...): Embedded directly in content stream via BI/EI operators
- is_inline=True, is_displayed=True, indirect_reference=None
2. **Do-referenced objects** (/Im0, /Im1..., /Form1...): Referenced via "Do" operator
- is_inline=False, is_displayed=True, indirect_reference=<image object>
3. **Pure XObject images** (/I0, /Image1...): Defined in Resources only (not in content stream)
- is_inline=False, is_displayed=False, indirect_reference=<image object>
Returns:
Dictionary mapping names to ImageFile instances (inline) or None (Do-referenced).
"""
content = self.get_contents()
if is_null_or_none(content):
return {}
imgs_data = []
do_image_names: list[bytes] = []
assert content is not None, "mypy"
for param, ope in content.operations:
if ope == b"INLINE IMAGE":
imgs_data.append(
{"settings": param["settings"], "__streamdata__": param["data"]}
)
elif ope == b"Do" and param:
do_image_names.append(param[0]) # First operand is the XObject name
elif ope in (b"BI", b"EI", b"ID"): # pragma: no cover
raise PdfReadError(
f"{ope!r} operator met whereas not expected, "
"please share use case with pypdf dev team"
)
files: dict[str, Optional[ImageFile]] = {}
# Process Do-referenced objects first (images + forms, no subtype check)
files = dict.fromkeys(list(map(str, do_image_names)), None)
# Then process inline images
for num, ii in enumerate(imgs_data):
init = {
"__streamdata__": ii["__streamdata__"],
"/Length": len(ii["__streamdata__"]),
}
for k, v in ii["settings"].items():
if k in {"/Length", "/L"}: # no length is expected
continue
if isinstance(v, list):
v = ArrayObject(
[self._translate_value_inline_image(k, x) for x in v]
)
else:
v = self._translate_value_inline_image(k, v)
if k in _INLINE_IMAGE_KEY_MAPPING:
k = NameObject(_INLINE_IMAGE_KEY_MAPPING[k])
else:
logger_warning(
"Unknown inline image key %(key)s, keeping it as-is.",
source=__name__,
key=k,
)
k = NameObject(k)
if k not in init:
init[k] = v
ii["object"] = EncodedStreamObject.initialize_from_dictionary(init)
from .generic._image_xobject import _xobj_to_image # noqa: PLC0415
extension, byte_stream, img = _xobj_to_image(ii["object"])
files[f"~{num}~"] = ImageFile(
name=f"~{num}~{extension}",
data=byte_stream,
image=img,
indirect_reference=None,
is_inline=True,
is_displayed=True,
)
return files
@property
def rotation(self) -> int:
"""
The visual rotation of the page.
This number has to be a multiple of 90 degrees: 0, 90, 180, or 270 are
valid values. This property does not affect ``/Contents``.
"""
rotate_obj = self.get(PG.ROTATE, 0)
return rotate_obj if isinstance(rotate_obj, int) else rotate_obj.get_object()
@rotation.setter
def rotation(self, r: float) -> None:
self[NameObject(PG.ROTATE)] = NumberObject((((int(r) + 45) // 90) * 90) % 360)
def transfer_rotation_to_content(self) -> None:
"""
Apply the rotation of the page to the content and the media/crop/...
boxes.
It is recommended to apply this function before page merging.
"""
r = -self.rotation # rotation to apply is in the otherway
self.rotation = 0
mb = RectangleObject(self.mediabox)
trsf = (
Transformation()
.translate(
-float(mb.left + mb.width / 2), -float(mb.bottom + mb.height / 2)
)
.rotate(r)
)
pt1 = trsf.apply_on(mb.lower_left)
pt2 = trsf.apply_on(mb.upper_right)
trsf = trsf.translate(-min(pt1[0], pt2[0]), -min(pt1[1], pt2[1]))
self.add_transformation(trsf, False)
for b in ["/MediaBox", "/CropBox", "/BleedBox", "/TrimBox", "/ArtBox"]:
if b in self:
rr = RectangleObject(self[b]) # type: ignore[arg-type]
pt1 = trsf.apply_on(rr.lower_left)
pt2 = trsf.apply_on(rr.upper_right)
self[NameObject(b)] = RectangleObject(
(
min(pt1[0], pt2[0]),
min(pt1[1], pt2[1]),
max(pt1[0], pt2[0]),
max(pt1[1], pt2[1]),
)
)
def rotate(self, angle: int) -> "PageObject":
"""
Rotate a page clockwise by increments of 90 degrees.
Args:
angle: Angle to rotate the page. Must be an increment of 90 deg.
Returns:
The rotated PageObject
"""
if angle % 90 != 0:
raise ValueError("Rotation angle must be a multiple of 90")
self[NameObject(PG.ROTATE)] = NumberObject(self.rotation + angle)
return self
def _merge_resources(
self,
res1: DictionaryObject,
res2: DictionaryObject,
resource: Any,
new_res1: bool = True,
) -> tuple[dict[str, Any], dict[str, Any]]:
try:
assert isinstance(self.indirect_reference, IndirectObject)
pdf = self.indirect_reference.pdf
is_pdf_writer = hasattr(
pdf, "_add_object"
) # expect isinstance(pdf, PdfWriter)
except (AssertionError, AttributeError):
pdf = None
is_pdf_writer = False
def compute_unique_key(base_key: str) -> tuple[str, bool]:
"""
Find a key that either doesn't already exist or has the same value
(indicated by the bool)
Args:
base_key: An index is added to this to get the computed key
Returns:
A tuple (computed key, bool) where the boolean indicates
if there is a resource of the given computed_key with the same
value.
"""
value = page2res.raw_get(base_key)
# TODO: a possible improvement for writer, the indirect_reference
# cannot be found because translated
# try the current key first (e.g. "foo"), but otherwise iterate
# through "foo-0", "foo-1", etc. new_res can contain only finitely
# many keys, thus this'll eventually end, even if it's been crafted
# to be maximally annoying.
computed_key = base_key
idx = 0
while computed_key in new_res:
if new_res.raw_get(computed_key) == value:
# there's already a resource of this name, with the exact
# same value
return computed_key, True
computed_key = f"{base_key}-{idx}"
idx += 1
return computed_key, False
if new_res1:
new_res = DictionaryObject()
new_res.update(res1.get(resource, DictionaryObject()).get_object())
else:
new_res = cast(DictionaryObject, res1[resource])
page2res = cast(
DictionaryObject, res2.get(resource, DictionaryObject()).get_object()
)
rename_res = {}
for key in page2res:
unique_key, same_value = compute_unique_key(key)
newname = NameObject(unique_key)
if key != unique_key:
# we have to use a different name for this
rename_res[key] = newname
if not same_value:
if is_pdf_writer:
new_res[newname] = page2res.raw_get(key).clone(pdf)
try:
new_res[newname] = new_res[newname].indirect_reference
except AttributeError:
pass
else:
new_res[newname] = page2res.raw_get(key)
lst = sorted(new_res.items())
new_res.clear()
for el in lst:
new_res[el[0]] = el[1]
return new_res, rename_res
@staticmethod
def _content_stream_rename(
stream: ContentStream,
rename: dict[Any, Any],
pdf: Optional[PdfCommonDocProtocol],
) -> ContentStream:
if not rename:
return stream
stream = ContentStream(stream, pdf)
for operands, _operator in stream.operations:
if isinstance(operands, list):
for i, op in enumerate(operands):
if isinstance(op, NameObject):
operands[i] = rename.get(op, op)
elif isinstance(operands, dict):
for i, op in operands.items():
if isinstance(op, NameObject):
operands[i] = rename.get(op, op)
else:
raise KeyError(f"Type of operands is {type(operands)}")
return stream
@staticmethod
def _add_transformation_matrix(
contents: Any,
pdf: Optional[PdfCommonDocProtocol],
ctm: CompressedTransformationMatrix,
) -> ContentStream:
"""Add transformation matrix at the beginning of the given contents stream."""
content_stream = ContentStream(contents, pdf)
content_stream.operations.insert(
0,
(
[FloatObject(x) for x in ctm],
b"cm",
),
)
return content_stream
def _get_contents_as_bytes(self) -> Optional[bytes]:
"""
Return the page contents as bytes.
Returns:
The ``/Contents`` object as bytes, or ``None`` if it doesn't exist.
"""
if PG.CONTENTS in self:
obj = self[PG.CONTENTS].get_object()
if isinstance(obj, list):
return b"".join(x.get_object().get_data() for x in obj)
return cast(EncodedStreamObject, obj).get_data()
return None
def get_contents(self) -> Optional[ContentStream]:
"""
Access the page contents.
Returns:
The ``/Contents`` object, or ``None`` if it does not exist.
``/Contents`` is optional, as described in §7.7.3.3 of the PDF Reference.
"""
if PG.CONTENTS in self:
try:
pdf = cast(IndirectObject, self.indirect_reference).pdf
except AttributeError:
pdf = None
obj = self[PG.CONTENTS]
if is_null_or_none(obj):
return None
resolved_object = obj.get_object()
return ContentStream(resolved_object, pdf)
return None
def replace_contents(
self, content: Union[ContentStream, EncodedStreamObject, ArrayObject, None]
) -> None:
"""
Replace the page contents with the new content and nullify old objects
Args:
content: new content; if None delete the content field.
"""
if not hasattr(self, "indirect_reference") or self.indirect_reference is None:
# the page is not attached : the content is directly attached.
self[NameObject(PG.CONTENTS)] = content
return
from pypdf._writer import PdfWriter # noqa: PLC0415
if not isinstance(self.indirect_reference.pdf, PdfWriter):
deprecate(
"Calling `PageObject.replace_contents()` for pages not assigned to a writer is deprecated "
"and will be removed in pypdf 7.0.0. Attach the page to the writer first or use "
"`PdfWriter(clone_from=...)` directly. The existing approach has proved being unreliable."
)
writer = self.indirect_reference.pdf
if isinstance(self.get(PG.CONTENTS, None), ArrayObject):
content_array = cast(ArrayObject, self[PG.CONTENTS])
for reference in content_array:
try:
writer._replace_object(indirect_reference=reference.indirect_reference, obj=NullObject())
except ValueError:
# Occurs when called on PdfReader.
pass
if isinstance(content, ArrayObject):
content = ArrayObject(writer._add_object(obj) for obj in content)
if is_null_or_none(content):
if PG.CONTENTS not in self:
return
assert self[PG.CONTENTS].indirect_reference is not None
writer._replace_object(indirect_reference=self[PG.CONTENTS].indirect_reference, obj=NullObject())
del self[PG.CONTENTS]
elif not hasattr(self.get(PG.CONTENTS, None), "indirect_reference"):
try:
self[NameObject(PG.CONTENTS)] = writer._add_object(content)
except AttributeError:
# applies at least for page not in writer
# as a backup solution, we put content as an object although not in accordance with pdf ref
# this will be fixed with the _add_object
self[NameObject(PG.CONTENTS)] = content
else:
assert content is not None, "mypy"
content.indirect_reference = self[
PG.CONTENTS
].indirect_reference # TODO: in the future may require generation management
try:
writer._replace_object(indirect_reference=content.indirect_reference, obj=content)
except AttributeError:
# applies at least for page not in writer
# as a backup solution, we put content as an object although not in accordance with pdf ref
# this will be fixed with the _add_object
self[NameObject(PG.CONTENTS)] = content
# forces recalculation of images
self._content_stream_images = None
def merge_page(
self, page2: "PageObject", expand: bool = False, over: bool = True
) -> None:
"""
Merge the content streams of two pages into one.
Resource references (e.g. fonts) are maintained from both pages.
The mediabox, cropbox, etc of this page are not altered.
The parameter page's content stream will
be added to the end of this page's content stream,
meaning that it will be drawn after, or "on top" of this page.
Args:
page2: The page to be merged into this one. Should be
an instance of :class:`PageObject<PageObject>`.
over: set the page2 content over page1 if True (default) else under
expand: If True, the current page dimensions will be
expanded to accommodate the dimensions of the page to be merged.
"""
self._merge_page(page2, over=over, expand=expand)
def _merge_page(
self,
page2: "PageObject",
page2_transformation: Optional[Callable[[Any], ContentStream]] = None,
ctm: Optional[CompressedTransformationMatrix] = None,
over: bool = True,
expand: bool = False,
) -> None:
# First we work on merging the resource dictionaries. This allows us
# to find out what symbols in the content streams we might need to
# rename.
try:
assert isinstance(self.indirect_reference, IndirectObject)
if hasattr(self.indirect_reference.pdf, "_add_object"): # to detect PdfWriter
return self._merge_page_writer(
page2, page2_transformation, ctm, over, expand
)
except (AssertionError, AttributeError):
pass
new_resources = DictionaryObject()
rename: dict[str, Any] = {}
original_resources = cast(DictionaryObject, self.get(PG.RESOURCES, DictionaryObject()).get_object())
page2_resources = cast(DictionaryObject, page2.get(PG.RESOURCES, DictionaryObject()).get_object())
new_annots = ArrayObject()
for page in (self, page2):
if PG.ANNOTS in page:
annots = page[PG.ANNOTS]
if isinstance(annots, ArrayObject):
new_annots.extend(annots)
self[NameObject(PG.ANNOTS)] = new_annots
for res in (
RES.EXT_G_STATE,
RES.COLOR_SPACE,
RES.PATTERN,
RES.SHADING,
RES.XOBJECT,
RES.FONT,
RES.PROPERTIES,
):
new, new_resource_name = self._merge_resources(
original_resources, page2_resources, res
)
if new:
new_resources[NameObject(res)] = new
rename.update(new_resource_name)
# Combine /ProcSet sets, making sure there is a consistent order
new_resources[NameObject(RES.PROC_SET)] = ArrayObject(
sorted(
set(
original_resources.get(RES.PROC_SET, ArrayObject()).get_object()
).union(
set(page2_resources.get(RES.PROC_SET, ArrayObject()).get_object())
)
)
)
new_content_array = ArrayObject()
original_content = self.get_contents()
if original_content is not None:
original_content.isolate_graphics_state()
new_content_array.append(original_content)
page2_content = page2.get_contents()
if page2_content is not None:
rect = getattr(page2, MERGE_CROP_BOX)
page2_content.operations.insert(
0,
(
map(
FloatObject,
[
rect.left,
rect.bottom,
rect.width,
rect.height,
],
),
b"re",
),
)
page2_content.operations.insert(1, ([], b"W"))
page2_content.operations.insert(2, ([], b"n"))
if page2_transformation is not None:
page2_content = page2_transformation(page2_content)
page2_content = PageObject._content_stream_rename(
page2_content, rename, self.pdf
)
page2_content.isolate_graphics_state()
if over:
new_content_array.append(page2_content)
else:
new_content_array.insert(0, page2_content)
# if expanding the page to fit a new page, calculate the new media box size
if expand:
self._expand_mediabox(page2, ctm)
self.replace_contents(ContentStream(new_content_array, self.pdf))
self[NameObject(PG.RESOURCES)] = new_resources
return None
def _merge_page_writer(
self,
page2: "PageObject",
page2transformation: Optional[Callable[[Any], ContentStream]] = None,
ctm: Optional[CompressedTransformationMatrix] = None,
over: bool = True,
expand: bool = False,
) -> None:
# First we work on merging the resource dictionaries. This allows us
# to find which symbols in the content streams we might need to
# rename.
assert isinstance(self.indirect_reference, IndirectObject)
pdf = self.indirect_reference.pdf
if PG.RESOURCES not in self:
self[NameObject(PG.RESOURCES)] = DictionaryObject()
original_resources = cast(DictionaryObject, self[PG.RESOURCES].get_object())
if PG.RESOURCES not in page2:
page2resources = DictionaryObject()
else:
page2resources = cast(DictionaryObject, page2[PG.RESOURCES].get_object())
rename = {}
for res in (
RES.EXT_G_STATE,
RES.COLOR_SPACE,
RES.PATTERN,
RES.SHADING,
RES.XOBJECT,
RES.FONT,
RES.PROPERTIES,
):
if res in page2resources:
if res not in original_resources:
original_resources[NameObject(res)] = DictionaryObject()
_, newrename = self._merge_resources(
original_resources, page2resources, res, False
)
rename.update(newrename)
# Combine /ProcSet sets
if RES.PROC_SET in page2resources:
if RES.PROC_SET not in original_resources:
original_resources[NameObject(RES.PROC_SET)] = ArrayObject()
arr = cast(ArrayObject, original_resources[RES.PROC_SET])
for x in cast(ArrayObject, page2resources[RES.PROC_SET]):
if x not in arr:
arr.append(x)
arr.sort()
if not is_null_or_none(page2.get(PG.ANNOTS, None)):
if PG.ANNOTS not in self:
self[NameObject(PG.ANNOTS)] = ArrayObject()
annots = cast(ArrayObject, self[PG.ANNOTS].get_object())
if ctm is None:
trsf = Transformation()
else:
trsf = Transformation(ctm)
# Ensure we are working on a copy of the list. Otherwise, if both pages
# are the same object, we might run into an infinite loop.
for a in cast(ArrayObject, deepcopy(page2[PG.ANNOTS])):
a = a.get_object()
aa = a.clone(
pdf,
ignore_fields=("/P", "/StructParent", "/Parent"),
force_duplicate=True,
)
r = cast(ArrayObject, a["/Rect"])
pt1 = trsf.apply_on((r[0], r[1]), True)
pt2 = trsf.apply_on((r[2], r[3]), True)
aa[NameObject("/Rect")] = ArrayObject(
(
min(pt1[0], pt2[0]),
min(pt1[1], pt2[1]),
max(pt1[0], pt2[0]),
max(pt1[1], pt2[1]),
)
)
if "/QuadPoints" in a:
q = cast(ArrayObject, a["/QuadPoints"])
aa[NameObject("/QuadPoints")] = ArrayObject(
trsf.apply_on((q[0], q[1]), True)
+ trsf.apply_on((q[2], q[3]), True)
+ trsf.apply_on((q[4], q[5]), True)
+ trsf.apply_on((q[6], q[7]), True)
)
# The /Rect update above only repositions and resizes the
# annotation's bounding box; it does not touch the
# appearance stream's own coordinate system. See
# transform_annotation_appearance for why that matters.
from pypdf.generic._appearance_stream import ( # noqa: PLC0415
transform_annotation_appearance,
)
transform_annotation_appearance(aa, trsf)
try:
aa["/Popup"][NameObject("/Parent")] = aa.indirect_reference
except KeyError:
pass
try:
aa[NameObject("/P")] = self.indirect_reference
annots.append(aa.indirect_reference)
except AttributeError:
pass
new_content_array = ArrayObject()
original_content = self.get_contents()
if original_content is not None:
original_content.isolate_graphics_state()
new_content_array.append(original_content)
page2content = page2.get_contents()
if page2content is not None:
rect = getattr(page2, MERGE_CROP_BOX)
page2content.operations.insert(
0,
(
map(
FloatObject,
[
rect.left,
rect.bottom,
rect.width,
rect.height,
],
),
b"re",
),
)
page2content.operations.insert(1, ([], b"W"))
page2content.operations.insert(2, ([], b"n"))
if page2transformation is not None:
page2content = page2transformation(page2content)
page2content = PageObject._content_stream_rename(
page2content, rename, self.pdf
)
page2content.isolate_graphics_state()
if over:
new_content_array.append(page2content)
else:
new_content_array.insert(0, page2content)
# if expanding the page to fit a new page, calculate the new media box size
if expand:
self._expand_mediabox(page2, ctm)
self.replace_contents(new_content_array)
def _expand_mediabox(
self, page2: "PageObject", ctm: Optional[CompressedTransformationMatrix]
) -> None:
corners1 = (
self.mediabox.left.as_numeric(),
self.mediabox.bottom.as_numeric(),
self.mediabox.right.as_numeric(),
self.mediabox.top.as_numeric(),
)
corners2 = (
page2.mediabox.left.as_numeric(),
page2.mediabox.bottom.as_numeric(),
page2.mediabox.left.as_numeric(),
page2.mediabox.top.as_numeric(),
page2.mediabox.right.as_numeric(),
page2.mediabox.top.as_numeric(),
page2.mediabox.right.as_numeric(),
page2.mediabox.bottom.as_numeric(),
)
if ctm is not None:
ctm = tuple(float(x) for x in ctm) # type: ignore[assignment]
new_x = tuple(
ctm[0] * corners2[i] + ctm[2] * corners2[i + 1] + ctm[4]
for i in range(0, 8, 2)
)
new_y = tuple(
ctm[1] * corners2[i] + ctm[3] * corners2[i + 1] + ctm[5]
for i in range(0, 8, 2)
)
else:
new_x = corners2[0:8:2]
new_y = corners2[1:8:2]
lowerleft = (min(new_x), min(new_y))
upperright = (max(new_x), max(new_y))
lowerleft = (min(corners1[0], lowerleft[0]), min(corners1[1], lowerleft[1]))
upperright = (
max(corners1[2], upperright[0]),
max(corners1[3], upperright[1]),
)
self.mediabox.lower_left = lowerleft
self.mediabox.upper_right = upperright
def merge_transformed_page(
self,
page2: "PageObject",
ctm: Union[CompressedTransformationMatrix, Transformation],
over: bool = True,
expand: bool = False,
) -> None:
"""
Similar to :meth:`~pypdf._page.PageObject.merge_page`, but a transformation
matrix is applied to the merged stream.
Args:
page2: The page to be merged into this one.
ctm: a 6-element tuple containing the operands of the
transformation matrix
over: set the page2 content over page1 if True (default) else under
expand: Whether the page should be expanded to fit the dimensions
of the page to be merged.
"""
if isinstance(ctm, Transformation):
ctm = ctm.ctm
self._merge_page(
page2,
lambda page2_content: PageObject._add_transformation_matrix(
page2_content, page2.pdf, ctm
),
ctm,
over,
expand,
)
def merge_scaled_page(
self, page2: "PageObject", scale: float, over: bool = True, expand: bool = False
) -> None:
"""
Similar to :meth:`~pypdf._page.PageObject.merge_page`, but the stream to be merged
is scaled by applying a transformation matrix.
Args:
page2: The page to be merged into this one.
scale: The scaling factor
over: set the page2 content over page1 if True (default) else under
expand: Whether the page should be expanded to fit the
dimensions of the page to be merged.
"""
op = Transformation().scale(scale, scale)
self.merge_transformed_page(page2, op, over, expand)
def merge_rotated_page(
self,
page2: "PageObject",
rotation: float,
over: bool = True,
expand: bool = False,
) -> None:
"""
Similar to :meth:`~pypdf._page.PageObject.merge_page`, but the stream to be merged
is rotated by applying a transformation matrix.
Args:
page2: The page to be merged into this one.
rotation: The angle of the rotation, in degrees
over: set the page2 content over page1 if True (default) else under
expand: Whether the page should be expanded to fit the
dimensions of the page to be merged.
"""
op = Transformation().rotate(rotation)
self.merge_transformed_page(page2, op, over, expand)
def merge_translated_page(
self,
page2: "PageObject",
tx: float,
ty: float,
over: bool = True,
expand: bool = False,
) -> None:
"""
Similar to :meth:`~pypdf._page.PageObject.merge_page`, but the stream to be
merged is translated by applying a transformation matrix.
Args:
page2: the page to be merged into this one.
tx: The translation on X axis
ty: The translation on Y axis
over: set the page2 content over page1 if True (default) else under
expand: Whether the page should be expanded to fit the
dimensions of the page to be merged.
"""
op = Transformation().translate(tx, ty)
self.merge_transformed_page(page2, op, over, expand)
def add_transformation(
self,
ctm: Union[Transformation, CompressedTransformationMatrix],
expand: bool = False,
) -> None:
"""
Apply a transformation matrix to the page.
Args:
ctm: A 6-element tuple containing the operands of the
transformation matrix. Alternatively, a
:py:class:`Transformation<pypdf.Transformation>`
object can be passed.
See :doc:`/user/cropping-and-transforming`.
"""
if isinstance(ctm, Transformation):
ctm = ctm.ctm
content = self.get_contents()
if content is not None:
content = PageObject._add_transformation_matrix(content, self.pdf, ctm)
content.isolate_graphics_state()
self.replace_contents(content)
# if expanding the page to fit a new page, calculate the new media box size
if expand:
corners = [
self.mediabox.left.as_numeric(),
self.mediabox.bottom.as_numeric(),
self.mediabox.left.as_numeric(),
self.mediabox.top.as_numeric(),
self.mediabox.right.as_numeric(),
self.mediabox.top.as_numeric(),
self.mediabox.right.as_numeric(),
self.mediabox.bottom.as_numeric(),
]
ctm = tuple(float(x) for x in ctm) # type: ignore[assignment]
new_x = [
ctm[0] * corners[i] + ctm[2] * corners[i + 1] + ctm[4]
for i in range(0, 8, 2)
]
new_y = [
ctm[1] * corners[i] + ctm[3] * corners[i + 1] + ctm[5]
for i in range(0, 8, 2)
]
self.mediabox.lower_left = (min(new_x), min(new_y))
self.mediabox.upper_right = (max(new_x), max(new_y))
def scale(self, sx: float, sy: float) -> None:
"""
Scale a page by the given factors by applying a transformation matrix
to its content and updating the page size.
This updates the various page boundaries (bleedbox, trimbox, etc.)
and the contents of the page.
Args:
sx: The scaling factor on horizontal axis.
sy: The scaling factor on vertical axis.
"""
self.add_transformation((sx, 0, 0, sy, 0, 0))
self.bleedbox = self.bleedbox.scale(sx, sy)
self.trimbox = self.trimbox.scale(sx, sy)
self.artbox = self.artbox.scale(sx, sy)
self.cropbox = self.cropbox.scale(sx, sy)
self.mediabox = self.mediabox.scale(sx, sy)
if PG.ANNOTS in self:
annotations = self[PG.ANNOTS]
if isinstance(annotations, ArrayObject):
for annotation in annotations:
annotation_obj = annotation.get_object()
if AnnotationDictionaryAttributes.Rect in annotation_obj:
rectangle = annotation_obj[AnnotationDictionaryAttributes.Rect]
if isinstance(rectangle, ArrayObject):
rectangle[0] = FloatObject(float(rectangle[0]) * sx)
rectangle[1] = FloatObject(float(rectangle[1]) * sy)
rectangle[2] = FloatObject(float(rectangle[2]) * sx)
rectangle[3] = FloatObject(float(rectangle[3]) * sy)
if PG.VP in self:
viewport = self[PG.VP]
if isinstance(viewport, ArrayObject):
bbox = viewport[0]["/BBox"]
else:
bbox = viewport["/BBox"] # type: ignore[index]
scaled_bbox = RectangleObject(
(
float(bbox[0]) * sx,
float(bbox[1]) * sy,
float(bbox[2]) * sx,
float(bbox[3]) * sy,
)
)
if isinstance(viewport, ArrayObject):
self[NameObject(PG.VP)][NumberObject(0)][ # type: ignore[index]
NameObject("/BBox")
] = scaled_bbox
else:
self[NameObject(PG.VP)][NameObject("/BBox")] = scaled_bbox # type: ignore[index]
def scale_by(self, factor: float) -> None:
"""
Scale a page by the given factor by applying a transformation matrix to
its content and updating the page size.
Args:
factor: The scaling factor (for both X and Y axis).
"""
self.scale(factor, factor)
def scale_to(self, width: float, height: float) -> None:
"""
Scale a page to the specified dimensions by applying a transformation
matrix to its content and updating the page size.
Args:
width: The new width.
height: The new height.
"""
sx = width / float(self.mediabox.width)
sy = height / float(self.mediabox.height)
self.scale(sx, sy)
def compress_content_streams(self, level: int = -1) -> None:
"""
Compress the size of this page by joining all content streams and
applying a FlateDecode filter.
However, it is possible that this function will perform no action if
content stream compression becomes "automatic".
"""
content = self.get_contents()
if content is not None:
content_obj = content.flate_encode(level)
try:
content.indirect_reference.pdf._objects[ # type: ignore[union-attr]
content.indirect_reference.idnum - 1 # type: ignore[union-attr]
] = content_obj
except AttributeError:
if self.indirect_reference is not None and hasattr(
self.indirect_reference.pdf, "_add_object"
):
self.replace_contents(content_obj)
else:
raise ValueError("Page must be part of a PdfWriter")
@property
def page_number(self) -> Optional[int]:
"""
Read-only property which returns the page number within the PDF file.
Returns:
Page number; None if the page is not attached to a PDF.
"""
if self.indirect_reference is None:
return None
try:
lst = self.indirect_reference.pdf.pages
return int(lst.index(self))
except ValueError:
return None
def _debug_for_extract(self) -> str: # pragma: no cover
out = ""
for ope, op in ContentStream(
self["/Contents"].get_object(), self.pdf, "bytes"
).operations:
if op == b"TJ":
s = [x for x in ope[0] if isinstance(x, str)]
else:
s = []
out += op.decode("utf-8") + " " + "".join(s) + ope.__repr__() + "\n"
out += "\n=============================\n"
try:
for fo in self[PG.RESOURCES]["/Font"]: # type:ignore
out += fo + "\n"
out += self[PG.RESOURCES]["/Font"][fo].__repr__() + "\n" # type:ignore
try:
enc_repr = self[PG.RESOURCES]["/Font"][fo][ # type:ignore
"/Encoding"
].__repr__()
out += enc_repr + "\n"
except Exception:
pass
try:
out += (
self[PG.RESOURCES]["/Font"][fo][ # type:ignore
"/ToUnicode"
]
.get_data()
.decode()
+ "\n"
)
except Exception:
pass
except KeyError:
out += "No Font\n"
return out
def _extract_text(
self,
obj: DictionaryObject,
pdf: Any,
orientations: tuple[int, ...] = (0, 90, 180, 270),
space_width: float = 200.0,
content_key: Optional[str] = PG.CONTENTS,
visitor_operand_before: Optional[Callable[[Any, Any, Any, Any], None]] = None,
visitor_operand_after: Optional[Callable[[Any, Any, Any, Any], None]] = None,
visitor_text: Optional[Callable[[Any, Any, Any, Any, Any], None]] = None,
*,
known_ids: Optional[set[int]] = None,
traversal_state: Optional[_TraversalState] = None
) -> str:
"""
See extract_text for most arguments.
Args:
content_key: indicate the default key where to extract data
None = the object; this allows reusing the function on an XObject
default = "/Content"
"""
if known_ids is None:
known_ids = set()
if traversal_state is None:
traversal_state = _TraversalState()
extractor = TextExtraction()
font_resources: dict[str, DictionaryObject] = {}
fonts: dict[str, Font] = {}
resources_dict = cast(
Optional[DictionaryObject],
obj.get_inherited(key=PG.RESOURCES, default=DictionaryObject())
)
if is_null_or_none(resources_dict) or not resources_dict:
# No resources means no text is possible (no font); we consider the
# file as not damaged, no need to check for TJ or Tj
return ""
if (
"/Font" in resources_dict
and (font_resources_dict := cast(DictionaryObject, resources_dict["/Font"]))
):
for font_resource in font_resources_dict:
try:
font_resource_object = cast(DictionaryObject, font_resources_dict[font_resource].get_object())
font_resources[font_resource] = font_resource_object
fonts[font_resource] = Font.from_font_resource(font_resource_object)
# Override space width, if applicable
if fonts[font_resource].character_widths.get(fonts[font_resource].space_char, 0) == 0:
fonts[font_resource].space_width = space_width
except (AttributeError, TypeError):
pass
try:
content = (
obj[content_key].get_object() if isinstance(content_key, str) else obj
)
if not isinstance(content, ContentStream):
content = ContentStream(content, pdf, "bytes")
except (AttributeError, KeyError): # no content can be extracted (certainly empty page)
return ""
# We check all strings are TextStringObjects. ByteStringObjects
# are strings where the byte->string encoding was unknown, so adding
# them to the text here would be gibberish.
# Initialize the extractor with the necessary parameters
extractor.initialize_extraction(orientations, visitor_text, font_resources, fonts)
for operands, operator in content.operations:
if visitor_operand_before is not None:
visitor_operand_before(operator, operands, extractor.cm_matrix, extractor.tm_matrix)
# Multiple operators are handled here
if operator == b"'":
extractor.process_operation(b"T*", [])
extractor.process_operation(b"Tj", operands)
elif operator == b'"' and len(operands) >= 3:
extractor.process_operation(b"Tw", [operands[0]])
extractor.process_operation(b"Tc", [operands[1]])
extractor.process_operation(b"T*", [])
extractor.process_operation(b"Tj", operands[2:])
elif operator == b"TJ":
# The space width may be smaller than the font width, so the width should be 95%.
_confirm_space_width = extractor._space_width * 0.95
if operands:
for op in operands[0]:
if isinstance(op, (str, bytes)):
extractor.process_operation(b"Tj", [op])
if isinstance(op, (int, float, NumberObject, FloatObject)) and (
abs(float(op)) >= _confirm_space_width
and extractor.text
and extractor.text[-1] != " "
):
extractor.process_operation(b"Tj", [" "])
elif operator == b"TD" and len(operands) >= 2:
extractor.process_operation(b"TL", [-operands[1]])
extractor.process_operation(b"Td", operands)
elif operator == b"Do":
extractor.output += extractor.text
if visitor_text is not None:
visitor_text(
extractor.text,
extractor.memo_cm,
extractor.memo_tm,
extractor.font_resource,
extractor.font_size,
)
try:
if extractor.output[-1] != "\n":
extractor.output += "\n"
if visitor_text is not None:
visitor_text(
"\n",
extractor.memo_cm,
extractor.memo_tm,
extractor.font_resource,
extractor.font_size,
)
except IndexError:
pass
try:
xform_text = self._extract_text__xform(
resources_dict=resources_dict,
operands=operands,
orientations=orientations,
space_width=space_width,
visitor_operand_before=visitor_operand_before,
visitor_operand_after=visitor_operand_after,
visitor_text=visitor_text,
known_ids=known_ids,
traversal_state=traversal_state
)
if xform_text is not None:
text = xform_text
extractor.output += text
if visitor_text is not None:
visitor_text(
text,
extractor.memo_cm,
extractor.memo_tm,
extractor.font_resource,
extractor.font_size,
)
except Exception as exception:
logger_warning(
"Impossible to decode XFormObject %(operand)s: %(exception)s",
source=__name__,
operand=operands[0],
exception=exception,
)
finally:
extractor.text = ""
extractor.memo_cm = extractor.cm_matrix.copy()
extractor.memo_tm = extractor.tm_matrix.copy()
else:
extractor.process_operation(operator, operands)
if visitor_operand_after is not None:
visitor_operand_after(operator, operands, extractor.cm_matrix, extractor.tm_matrix)
extractor.output += extractor.text # just in case
if extractor.text != "" and visitor_text is not None:
visitor_text(
extractor.text,
extractor.memo_cm,
extractor.memo_tm,
extractor.font_resource,
extractor.font_size,
)
return extractor.output
def _extract_text__xform(
self,
*,
resources_dict: DictionaryObject,
operands: Any,
orientations: tuple[int, ...] = (0, 90, 180, 270),
space_width: float = 200.0,
visitor_operand_before: Optional[Callable[[Any, Any, Any, Any], None]] = None,
visitor_operand_after: Optional[Callable[[Any, Any, Any, Any], None]] = None,
visitor_text: Optional[Callable[[Any, Any, Any, Any, Any], None]] = None,
known_ids: set[int],
traversal_state: _TraversalState
) -> Optional[str]:
xobj = cast(DictionaryObject, resources_dict["/XObject"])
xform = cast(EncodedStreamObject, xobj[operands[0]])
if xform["/Subtype"] == NameObject("/Image"):
return None
xform_id = id(xform)
if xform_id in known_ids:
logger_warning(
"Detected cyclic form XObject reference, skipping %(operand)s.",
source=__name__,
operand=operands[0]
)
return ""
if traversal_state.entry_count >= MAX_XFORM_INVOCATIONS_PER_EXTRACTION:
if not traversal_state.has_logged:
traversal_state.has_logged = True
logger_warning(
(
"Exceeded %(limit)d form XObject invocations while extracting text; "
"further form content is skipped."
),
source=__name__,
limit=MAX_XFORM_INVOCATIONS_PER_EXTRACTION
)
return ""
traversal_state.entry_count += 1
known_ids.add(xform_id)
try:
text = self.extract_xform_text(
xform,
orientations,
space_width,
visitor_operand_before,
visitor_operand_after,
visitor_text,
known_ids=known_ids,
traversal_state=traversal_state,
)
finally:
known_ids.discard(xform_id)
return text
def _layout_mode_fonts(self) -> dict[str, Font]:
"""
Get fonts formatted for "layout" mode text extraction.
Returns:
Dict[str, Font]: dictionary of Font instances keyed by font name
"""
# Font retrieval logic adapted from pypdf.PageObject._extract_text()
obj: Any = self
fonts: dict[str, Font] = {}
visited: set[int] = set()
while True:
obj_id = id(obj)
if obj_id in visited:
logger_warning("Detected cycle in /Parent hierarchy when retrieving fonts.", source=__name__)
break
visited.add(obj_id)
resources_dict: Any = obj.get(PG.RESOURCES, {})
if "/Font" in resources_dict and self.pdf is not None:
for font_name in resources_dict["/Font"]:
fonts[font_name] = Font.from_font_resource(resources_dict["/Font"][font_name])
if "/Parent" not in obj:
break
obj = obj["/Parent"].get_object()
return fonts
def _layout_mode_text(
self,
space_vertically: bool = True,
scale_weight: float = 1.25,
strip_rotated: bool = True,
debug_path: Optional[Path] = None,
font_height_weight: float = 1,
) -> str:
"""
Get text preserving fidelity to source PDF text layout.
Args:
space_vertically: include blank lines inferred from y distance + font
height. Defaults to True.
scale_weight: multiplier for string length when calculating weighted
average character width. Defaults to 1.25.
strip_rotated: Removes text that is rotated w.r.t. to the page from
layout mode output. Defaults to True.
debug_path (Path | None): if supplied, must target a directory.
creates the following files with debug information for layout mode
functions if supplied:
- fonts.json: output of self._layout_mode_fonts
- tjs.json: individual text render ops with corresponding transform matrices
- bts.json: text render ops left justified and grouped by BT/ET operators
- bt_groups.json: BT/ET operations grouped by rendered y-coord (aka lines)
Defaults to None.
font_height_weight: multiplier for font height when calculating
blank lines. Defaults to 1.
Returns:
str: multiline string containing page text in a fixed width format that
closely adheres to the rendered layout in the source pdf.
"""
fonts = self._layout_mode_fonts()
if debug_path: # pragma: no cover
import json # noqa: PLC0415
debug_path.joinpath("fonts.json").write_text(
json.dumps(fonts, indent=2, default=asdict),
"utf-8"
)
ops = iter(
ContentStream(self["/Contents"].get_object(), self.pdf, "bytes").operations
)
bt_groups = _layout_mode.text_show_operations(
ops, fonts, strip_rotated, debug_path
)
if not bt_groups:
return ""
ty_groups = _layout_mode.y_coordinate_groups(bt_groups, debug_path)
char_width = _layout_mode.fixed_char_width(bt_groups, scale_weight)
return _layout_mode.fixed_width_page(ty_groups, char_width, space_vertically, font_height_weight)
def extract_text(
self,
*args: Any,
orientations: Union[int, tuple[int, ...]] = (0, 90, 180, 270),
space_width: float = 200.0,
visitor_operand_before: Optional[Callable[[Any, Any, Any, Any], None]] = None,
visitor_operand_after: Optional[Callable[[Any, Any, Any, Any], None]] = None,
visitor_text: Optional[Callable[[Any, Any, Any, Any, Any], None]] = None,
extraction_mode: Literal["plain", "layout"] = "plain",
**kwargs: Any,
) -> str:
"""
Locate all text drawing commands, in the order they are provided in the
content stream, and extract the text.
This works well for some PDF files, but poorly for others, depending on
the generator used. This will be refined in the future.
Do not rely on the order of text coming out of this function, as it
will change if this function is made more sophisticated.
Arabic and Hebrew are extracted in the correct order.
If required a custom RTL range of characters can be defined;
see function set_custom_rtl.
Additionally you can provide visitor methods to get informed on all
operations and all text objects.
For example in some PDF files this can be useful to parse tables.
Args:
orientations: list of orientations extract_text will look for
default = (0, 90, 180, 270)
note: currently only 0 (up),90 (turned left), 180 (upside down),
270 (turned right)
Silently ignored in "layout" mode.
space_width: force default space width
if not extracted from font (default: 200)
Silently ignored in "layout" mode.
visitor_operand_before: function to be called before processing an operation.
It has four arguments: operator, operand-arguments,
current transformation matrix and text matrix.
Ignored with a warning in "layout" mode.
visitor_operand_after: function to be called after processing an operation.
It has four arguments: operator, operand-arguments,
current transformation matrix and text matrix.
Ignored with a warning in "layout" mode.
visitor_text: function to be called when extracting some text at some position.
It has five arguments: text, current transformation matrix,
text matrix, font-dictionary and font-size.
The font-dictionary may be None in case of unknown fonts.
If not None it may e.g. contain key "/BaseFont" with value "/Arial,Bold".
Ignored with a warning in "layout" mode.
extraction_mode (Literal["plain", "layout"]): "plain" for legacy functionality,
"layout" for experimental layout mode functionality.
NOTE: orientations, space_width, and visitor_* parameters are NOT respected
in "layout" mode.
kwargs:
layout_mode_space_vertically (bool): include blank lines inferred from
y distance + font height. Defaults to True.
layout_mode_scale_weight (float): multiplier for string length when calculating
weighted average character width. Defaults to 1.25.
layout_mode_strip_rotated (bool): layout mode does not support rotated text.
Set to False to include rotated text anyway. If rotated text is discovered,
layout will be degraded and a warning will result. Defaults to True.
layout_mode_debug_path (Path | None): if supplied, must target a directory.
creates the following files with debug information for layout mode
functions if supplied:
- fonts.json: output of self._layout_mode_fonts
- tjs.json: individual text render ops with corresponding transform matrices
- bts.json: text render ops left justified and grouped by BT/ET operators
- bt_groups.json: BT/ET operations grouped by rendered y-coord (aka lines)
layout_mode_font_height_weight (float): multiplier for font height when calculating
blank lines. Defaults to 1.
Returns:
The extracted text
"""
if extraction_mode not in ["plain", "layout"]:
raise ValueError(f"Invalid text extraction mode '{extraction_mode}'")
if extraction_mode == "layout":
for visitor in (
"visitor_operand_before",
"visitor_operand_after",
"visitor_text",
):
if locals()[visitor]:
logger_warning(
"Argument %(visitor)s is ignored in layout mode",
source=__name__,
visitor=visitor,
)
return self._layout_mode_text(
space_vertically=kwargs.get("layout_mode_space_vertically", True),
scale_weight=kwargs.get("layout_mode_scale_weight", 1.25),
strip_rotated=kwargs.get("layout_mode_strip_rotated", True),
debug_path=kwargs.get("layout_mode_debug_path"),
font_height_weight=kwargs.get("layout_mode_font_height_weight", 1)
)
if len(args) >= 1:
if isinstance(args[0], str):
if len(args) >= 3:
if isinstance(args[2], (tuple, int)):
orientations = args[2]
else:
raise TypeError(f"Invalid positional parameter {args[2]}")
if len(args) >= 4:
if isinstance(args[3], (float, int)):
space_width = args[3]
else:
raise TypeError(f"Invalid positional parameter {args[3]}")
elif isinstance(args[0], (tuple, int)):
orientations = args[0]
if len(args) >= 2:
if isinstance(args[1], (float, int)):
space_width = args[1]
else:
raise TypeError(f"Invalid positional parameter {args[1]}")
else:
raise TypeError(f"Invalid positional parameter {args[0]}")
if isinstance(orientations, int):
orientations = (orientations,)
return self._extract_text(
self,
self.pdf,
orientations,
space_width,
PG.CONTENTS,
visitor_operand_before,
visitor_operand_after,
visitor_text,
)
def extract_xform_text(
self,
xform: EncodedStreamObject,
orientations: tuple[int, ...] = (0, 90, 270, 360),
space_width: float = 200.0,
visitor_operand_before: Optional[Callable[[Any, Any, Any, Any], None]] = None,
visitor_operand_after: Optional[Callable[[Any, Any, Any, Any], None]] = None,
visitor_text: Optional[Callable[[Any, Any, Any, Any, Any], None]] = None,
*,
known_ids: Optional[set[int]] = None,
traversal_state: Optional[Any] = None
) -> str:
"""
Extract text from an XObject.
Args:
xform:
orientations:
space_width: force default space width (if not extracted from font (default 200)
visitor_operand_before:
visitor_operand_after:
visitor_text:
known_ids:
traversal_state:
Returns:
The extracted text
"""
# The type hint would have to use an internal type otherwise, which is not desired.
assert traversal_state is None or isinstance(traversal_state, _TraversalState)
return self._extract_text(
xform,
self.pdf,
orientations,
space_width,
None,
visitor_operand_before,
visitor_operand_after,
visitor_text,
known_ids=known_ids,
traversal_state=traversal_state,
)
def _get_fonts(self) -> tuple[set[str], set[str]]:
"""
Get the names of embedded fonts and unembedded fonts.
Returns:
A tuple (set of embedded fonts, set of unembedded fonts)
"""
obj = self.get_object()
assert isinstance(obj, DictionaryObject)
fonts: set[str] = set()
embedded: set[str] = set()
fonts, embedded = _get_fonts_walk(obj, fonts, embedded)
unembedded = fonts - embedded
return embedded, unembedded
mediabox = _create_rectangle_accessor(PG.MEDIABOX, ())
"""A :class:`RectangleObject<pypdf.generic.RectangleObject>`, expressed in
default user space units, defining the boundaries of the physical medium on
which the page is intended to be displayed or printed."""
cropbox = _create_rectangle_accessor("/CropBox", (PG.MEDIABOX,))
"""
A :class:`RectangleObject<pypdf.generic.RectangleObject>`, expressed in
default user space units, defining the visible region of default user
space.
When the page is displayed or printed, its contents are to be clipped
(cropped) to this rectangle and then imposed on the output medium in some
implementation-defined manner. Default value: same as
:attr:`mediabox<mediabox>`.
"""
bleedbox = _create_rectangle_accessor("/BleedBox", ("/CropBox", PG.MEDIABOX))
"""A :class:`RectangleObject<pypdf.generic.RectangleObject>`, expressed in
default user space units, defining the region to which the contents of the
page should be clipped when output in a production environment."""
trimbox = _create_rectangle_accessor("/TrimBox", ("/CropBox", PG.MEDIABOX))
"""A :class:`RectangleObject<pypdf.generic.RectangleObject>`, expressed in
default user space units, defining the intended dimensions of the finished
page after trimming."""
artbox = _create_rectangle_accessor("/ArtBox", ("/CropBox", PG.MEDIABOX))
"""A :class:`RectangleObject<pypdf.generic.RectangleObject>`, expressed in
default user space units, defining the extent of the page's meaningful
content as intended by the page's creator."""
@property
def annotations(self) -> Optional[ArrayObject]:
if "/Annots" not in self:
return None
return cast(ArrayObject, self["/Annots"])
@annotations.setter
def annotations(self, value: Optional[ArrayObject]) -> None:
"""
Set the annotations array of the page.
Typically you do not want to set this value, but append to it.
If you append to it, remember to add the object first to the writer
and only add the indirect object.
"""
if value is None:
if "/Annots" not in self:
return
del self[NameObject("/Annots")]
else:
self[NameObject("/Annots")] = value
def add_action(self, trigger: PageTrigger, action: Action) -> None:
"""
Add an action which will launch on the given trigger event of this page.
Args:
trigger: The action trigger to use.
action: The action to be done.
Example:
>>> from pypdf import PdfWriter
>>> from pypdf.actions import JavaScript, PageTrigger
>>> writer = PdfWriter()
>>> page = writer.add_blank_page(595, 842)
>>> # Display the page number when the page is opened
>>> page.add_action(PageTrigger("open"), JavaScript("app.alert('This is page ' + this.pageNum);"))
>>> # Display the page number when the page is closed
>>> page.add_action(PageTrigger("close"), JavaScript("app.alert('This is page ' + this.pageNum);"))
"""
return Action._create_new(self, trigger, action)
def delete_action(self, trigger: PageTrigger) -> None:
"""
Delete all actions associated with an open or close trigger event of this page.
Args:
trigger: An open or close trigger.
Example:
>>> from pypdf import PdfWriter
>>> from pypdf.actions import JavaScript, PageTrigger
>>> writer = PdfWriter()
>>> page = writer.add_blank_page(595, 842)
>>> page.add_action(PageTrigger("open"), JavaScript("app.alert('This is page ' + this.pageNum);"))
>>> page.add_action(PageTrigger("close"), JavaScript("app.alert('This is page ' + this.pageNum);"))
>>> # Delete all actions triggered by a page open
>>> page.delete_action(PageTrigger("open"))
>>> # Delete all actions triggered by a page close
>>> page.delete_action(PageTrigger("close"))
"""
return Action._delete(self, trigger)
class _VirtualList(Sequence[PageObject]):
def __init__(
self,
length_function: Callable[[], int],
get_function: Callable[[int], PageObject],
) -> None:
self.length_function = length_function
self.get_function = get_function
self.current = -1
def __len__(self) -> int:
return self.length_function()
@overload
def __getitem__(self, index: int) -> PageObject:
...
@overload
def __getitem__(self, index: slice) -> Sequence[PageObject]:
...
def __getitem__(
self, index: Union[int, slice]
) -> Union[PageObject, Sequence[PageObject]]:
if isinstance(index, slice):
indices = range(*index.indices(len(self)))
cls = type(self)
return cls(indices.__len__, lambda idx: self[indices[idx]])
if not isinstance(index, int):
raise TypeError("Sequence indices must be integers")
len_self = len(self)
if index < 0:
# support negative indexes
index += len_self
if not (0 <= index < len_self):
raise IndexError("Sequence index out of range")
return self.get_function(index)
def __delitem__(self, index: Union[int, slice]) -> None:
if isinstance(index, slice):
r = list(range(*index.indices(len(self))))
# pages have to be deleted from last to first
r.sort()
r.reverse()
for p in r:
del self[p] # recursive call
return
if not isinstance(index, int):
raise TypeError("Index must be integers")
len_self = len(self)
if index < 0:
# support negative indexes
index += len_self
if not (0 <= index < len_self):
raise IndexError("Index out of range")
ind = self[index].indirect_reference
assert ind is not None
parent: Optional[PdfObject] = cast(DictionaryObject, ind.get_object()).get(
"/Parent", None
)
first = True
while parent is not None:
parent = cast(DictionaryObject, parent.get_object())
try:
i = cast(ArrayObject, parent["/Kids"]).index(ind)
del cast(ArrayObject, parent["/Kids"])[i]
first = False
try:
assert ind is not None
del ind.pdf.flattened_pages[index] # case of page in a Reader
except Exception: # pragma: no cover
pass
if "/Count" in parent:
parent[NameObject("/Count")] = NumberObject(
cast(int, parent["/Count"]) - 1
)
if len(cast(ArrayObject, parent["/Kids"])) == 0:
# No more objects in this part of this subtree
ind = parent.indirect_reference
parent = parent.get("/Parent", None)
except ValueError: # from index
if first:
raise PdfReadError(f"Page not found in page tree: {ind}")
break
def __iter__(self) -> Iterator[PageObject]:
for i in range(len(self)):
yield self[i]
def __str__(self) -> str:
p = [f"PageObject({i})" for i in range(self.length_function())]
return f"[{', '.join(p)}]"
def _get_fonts_walk(
obj: DictionaryObject,
fnt: set[str],
emb: set[str],
) -> tuple[set[str], set[str]]:
"""
Get the set of all fonts and all embedded fonts.
Args:
obj: Page resources dictionary
fnt: font
emb: embedded fonts
Returns:
A tuple (fnt, emb)
If there is a key called 'BaseFont', that is a font that is used in the document.
If there is a key called 'FontName' and another key in the same dictionary object
that is called 'FontFilex' (where x is null, 2, or 3), then that fontname is
embedded.
We create and add to two sets, fnt = fonts used and emb = fonts embedded.
"""
fontkeys = ("/FontFile", "/FontFile2", "/FontFile3")
def process_font(f: PdfObject) -> None:
nonlocal fnt, emb
f = cast(DictionaryObject, f.get_object()) # to be sure
if "/BaseFont" in f:
fnt.add(cast(str, f["/BaseFont"]))
if (
("/CharProcs" in f)
or (
"/FontDescriptor" in f
and any(
x in cast(DictionaryObject, f["/FontDescriptor"]) for x in fontkeys
)
)
or (
"/DescendantFonts" in f
and "/FontDescriptor"
in cast(
DictionaryObject,
cast(ArrayObject, f["/DescendantFonts"])[0].get_object(),
)
and any(
x
in cast(
DictionaryObject,
cast(
DictionaryObject,
cast(ArrayObject, f["/DescendantFonts"])[0].get_object(),
)["/FontDescriptor"],
)
for x in fontkeys
)
)
):
# the list comprehension ensures there is FontFile
try:
emb.add(cast(str, f["/BaseFont"]))
except KeyError:
emb.add("(" + cast(str, f["/Subtype"]) + ")")
if "/DR" in obj and "/Font" in cast(DictionaryObject, obj["/DR"]):
for f in cast(
DictionaryObject, cast(DictionaryObject, obj["/DR"])["/Font"]
).values():
process_font(f)
if "/Resources" in obj:
if "/Font" in cast(DictionaryObject, obj["/Resources"]):
for f in cast(
DictionaryObject, cast(DictionaryObject, obj["/Resources"])["/Font"]
).values():
process_font(f)
if "/XObject" in cast(DictionaryObject, obj["/Resources"]):
for x in cast(
DictionaryObject, cast(DictionaryObject, obj["/Resources"])["/XObject"]
).values():
_get_fonts_walk(cast(DictionaryObject, x.get_object()), fnt, emb)
if "/Annots" in obj:
for a in cast(ArrayObject, obj["/Annots"]):
_get_fonts_walk(cast(DictionaryObject, a.get_object()), fnt, emb)
if "/AP" in obj:
if (
cast(DictionaryObject, cast(DictionaryObject, obj["/AP"])["/N"]).get(
"/Type"
)
== "/XObject"
):
_get_fonts_walk(
cast(DictionaryObject, cast(DictionaryObject, obj["/AP"])["/N"]),
fnt,
emb,
)
else:
for a in cast(DictionaryObject, cast(DictionaryObject, obj["/AP"])["/N"]):
_get_fonts_walk(cast(DictionaryObject, a), fnt, emb)
return fnt, emb # return the sets for each page
|