File size: 59,357 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 | # Copyright (c) 2006, Mathieu Fenniak
# Copyright (c) 2007, Ashish Kulkarni <kulkarni.ashish@gmail.com>
# Copyright (c) 2024, Pubpub-ZZ
#
# 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 struct
from abc import ABC, abstractmethod
from collections.abc import Generator, Iterable, Iterator, Mapping, Sequence
from datetime import datetime
from typing import (
Any,
NoReturn,
Optional,
Union,
cast,
)
from ._encryption import Encryption
from ._page import PageObject, _VirtualList
from ._page_labels import index2label as page_index2page_label
from ._utils import (
_TraversalState,
deprecation_with_replacement,
logger_warning,
parse_iso8824_date,
)
from .constants import CatalogAttributes as CA
from .constants import (
CheckboxRadioButtonAttributes,
Core,
GoToActionArguments,
PagesAttributes,
UserAccessPermissions,
)
from .constants import DocumentInformationAttributes as DI
from .constants import FieldDictionaryAttributes as FA
from .constants import PageAttributes as PG
from .errors import LimitReachedError, PdfReadError, PyPdfError
from .filters import _decompress_with_limit
from .generic import (
ArrayObject,
BooleanObject,
ByteStringObject,
Destination,
DictionaryObject,
EncodedStreamObject,
Field,
Fit,
FloatObject,
IndirectObject,
NameObject,
NullObject,
NumberObject,
PdfObject,
TextStringObject,
TreeObject,
ViewerPreferences,
create_string_object,
is_null_or_none,
)
from .generic._files import EmbeddedFile
from .types import OutlineType, PagemodeType
from .xmp import XmpInformation
# TODO: Make configurable.
OUTLINE_MAX_ENTRIES = 100_000
OUTLINE_MAX_DEPTH = 100
PAGE_TREE_MAX_ENTRIES = 100_000
PAGE_TREE_MAX_DEPTH = 100
def convert_to_int(d: bytes, size: int) -> Union[int, tuple[Any, ...]]:
if size > 8:
raise PdfReadError("Invalid size in convert_to_int")
d = b"\x00\x00\x00\x00\x00\x00\x00\x00" + d
d = d[-8:]
return cast(int, struct.unpack(">Q", d)[0])
class DocumentInformation(DictionaryObject):
"""
A class representing the basic document metadata provided in a PDF File.
This class is accessible through
:py:class:`PdfReader.metadata<pypdf.PdfReader.metadata>`.
All text properties of the document metadata have
*two* properties, e.g. author and author_raw. The non-raw property will
always return a ``TextStringObject``, making it ideal for a case where the
metadata is being displayed. The raw property can sometimes return a
``ByteStringObject``, if pypdf was unable to decode the string's text
encoding; this requires additional safety in the caller and therefore is not
as commonly accessed.
"""
def __init__(self) -> None:
DictionaryObject.__init__(self)
def _get_text(self, key: str) -> Optional[str]:
retval = self.get(key, None)
if isinstance(retval, TextStringObject):
return retval
if isinstance(retval, ByteStringObject):
return str(retval)
return None
@property
def title(self) -> Optional[str]:
"""
Read-only property accessing the document's title.
Returns a ``TextStringObject`` or ``None`` if the title is not
specified.
"""
return (
self._get_text(DI.TITLE) or self.get(DI.TITLE).get_object() # type: ignore[union-attr]
if self.get(DI.TITLE)
else None
)
@property
def title_raw(self) -> Optional[str]:
"""The "raw" version of title; can return a ``ByteStringObject``."""
return self.get(DI.TITLE)
@property
def author(self) -> Optional[str]:
"""
Read-only property accessing the document's author.
Returns a ``TextStringObject`` or ``None`` if the author is not
specified.
"""
return self._get_text(DI.AUTHOR)
@property
def author_raw(self) -> Optional[str]:
"""The "raw" version of author; can return a ``ByteStringObject``."""
return self.get(DI.AUTHOR)
@property
def subject(self) -> Optional[str]:
"""
Read-only property accessing the document's subject.
Returns a ``TextStringObject`` or ``None`` if the subject is not
specified.
"""
return self._get_text(DI.SUBJECT)
@property
def subject_raw(self) -> Optional[str]:
"""The "raw" version of subject; can return a ``ByteStringObject``."""
return self.get(DI.SUBJECT)
@property
def creator(self) -> Optional[str]:
"""
Read-only property accessing the document's creator.
If the document was converted to PDF from another format, this is the
name of the application (e.g. OpenOffice) that created the original
document from which it was converted. Returns a ``TextStringObject`` or
``None`` if the creator is not specified.
"""
return self._get_text(DI.CREATOR)
@property
def creator_raw(self) -> Optional[str]:
"""The "raw" version of creator; can return a ``ByteStringObject``."""
return self.get(DI.CREATOR)
@property
def producer(self) -> Optional[str]:
"""
Read-only property accessing the document's producer.
If the document was converted to PDF from another format, this is the
name of the application (for example, macOS Quartz) that converted it to
PDF. Returns a ``TextStringObject`` or ``None`` if the producer is not
specified.
"""
return self._get_text(DI.PRODUCER)
@property
def producer_raw(self) -> Optional[str]:
"""The "raw" version of producer; can return a ``ByteStringObject``."""
return self.get(DI.PRODUCER)
@property
def creation_date(self) -> Optional[datetime]:
"""Read-only property accessing the document's creation date."""
return parse_iso8824_date(self._get_text(DI.CREATION_DATE))
@property
def creation_date_raw(self) -> Optional[str]:
"""
The "raw" version of creation date; can return a ``ByteStringObject``.
Typically in the format ``D:YYYYMMDDhhmmss[+Z-]hh'mm`` where the suffix
is the offset from UTC.
"""
return self.get(DI.CREATION_DATE)
@property
def modification_date(self) -> Optional[datetime]:
"""
Read-only property accessing the document's modification date.
The date and time the document was most recently modified.
"""
return parse_iso8824_date(self._get_text(DI.MOD_DATE))
@property
def modification_date_raw(self) -> Optional[str]:
"""
The "raw" version of modification date; can return a
``ByteStringObject``.
Typically, in the format ``D:YYYYMMDDhhmmss[+Z-]hh'mm`` where the suffix
is the offset from UTC.
"""
return self.get(DI.MOD_DATE)
@property
def keywords(self) -> Optional[str]:
"""
Read-only property accessing the document's keywords.
Returns a ``TextStringObject`` or ``None`` if keywords are not
specified.
"""
return self._get_text(DI.KEYWORDS)
@property
def keywords_raw(self) -> Optional[str]:
"""The "raw" version of keywords; can return a ``ByteStringObject``."""
return self.get(DI.KEYWORDS)
class PdfDocCommon(ABC):
"""
Common functions from PdfWriter and PdfReader objects.
This root class is strongly abstracted.
"""
strict: bool = False # default
flattened_pages: Optional[list[PageObject]] = None
_encryption: Optional[Encryption] = None
_readonly: bool = False
@property
@abstractmethod
def root_object(self) -> DictionaryObject:
... # pragma: no cover
@property
@abstractmethod
def pdf_header(self) -> str:
... # pragma: no cover
@abstractmethod
def get_object(
self, indirect_reference: Union[int, IndirectObject]
) -> Optional[PdfObject]:
... # pragma: no cover
@abstractmethod
def _replace_object(self, indirect: IndirectObject, obj: PdfObject) -> PdfObject:
... # pragma: no cover
@property
@abstractmethod
def _info(self) -> Optional[DictionaryObject]:
... # pragma: no cover
@property
def metadata(self) -> Optional[DocumentInformation]:
"""
Retrieve the PDF file's document information dictionary, if it exists.
Note that some PDF files use metadata streams instead of document
information dictionaries, and these metadata streams will not be
accessed by this function.
"""
retval = DocumentInformation()
if self._info is None:
return None
retval.update(self._info)
return retval
@property
@abstractmethod
def xmp_metadata(self) -> Optional[XmpInformation]:
... # pragma: no cover
@property
def viewer_preferences(self) -> Optional[ViewerPreferences]:
"""Returns the existing ViewerPreferences as an overloaded dictionary."""
o = self.root_object.get(CA.VIEWER_PREFERENCES, None)
if o is None:
return None
o = o.get_object()
if not isinstance(o, ViewerPreferences):
o = ViewerPreferences(o)
if hasattr(o, "indirect_reference") and o.indirect_reference is not None:
self._replace_object(o.indirect_reference, o)
else:
self.root_object[NameObject(CA.VIEWER_PREFERENCES)] = o
return o
def get_num_pages(self) -> int:
"""
Calculate the number of pages in this PDF file.
Returns:
The number of pages of the parsed PDF file.
Raises:
PdfReadError: If restrictions prevent this action.
"""
# Flattened pages will not work on an encrypted PDF;
# the PDF file's page count is used in this case. Otherwise,
# the original method (flattened page count) is used.
if self.is_encrypted:
return self.root_object["/Pages"]["/Count"] # type: ignore[no-any-return, index]
if self.flattened_pages is None:
self._flatten(self._readonly)
assert self.flattened_pages is not None
return len(self.flattened_pages)
def get_page(self, page_number: int) -> PageObject:
"""
Retrieve a page by number from this PDF file.
Most of the time ``.pages[page_number]`` is preferred.
Args:
page_number: The page number to retrieve
(pages begin at zero)
Returns:
A :class:`PageObject<pypdf._page.PageObject>` instance.
"""
if self.flattened_pages is None:
self._flatten(self._readonly)
assert self.flattened_pages is not None, "mypy"
return self.flattened_pages[page_number]
def _get_page_in_node(
self,
page_number: int,
) -> tuple[DictionaryObject, int]:
"""
Retrieve the node and position within the /Kids containing the page.
If page_number is greater than the number of pages, it returns the top node, -1.
"""
top = cast(DictionaryObject, self.root_object["/Pages"])
visited: set[int] = set()
def recursive_call(
_node: DictionaryObject, mi: int
) -> tuple[Optional[PdfObject], int]:
_node_id = id(_node)
if _node_id in visited:
raise LimitReachedError("Detected cycle in /Pages hierarchy when retrieving page.")
visited.add(_node_id)
ma = cast(int, _node.get("/Count", 1)) # default 1 for /Page types
if _node.get("/Type") == "/Page":
if page_number == mi:
return _node, -1
return None, mi + 1
if (page_number - mi) >= ma: # not in nodes below
if _node == top:
return top, -1
return None, mi + ma
for _idx, kid in enumerate(cast(ArrayObject, _node["/Kids"])):
kid = cast(DictionaryObject, kid.get_object())
n, i = recursive_call(kid, mi)
if n is not None: # page has just been found ...
if i < 0: # ... just below!
return _node, _idx
# ... at lower levels
return n, i
mi = i
raise PyPdfError("Unexpectedly cannot find the node.")
node, idx = recursive_call(top, 0)
assert isinstance(node, DictionaryObject), "mypy"
return node, idx
@property
def named_destinations(self) -> dict[str, Destination]:
"""A read-only dictionary which maps names to destinations."""
return self._get_named_destinations()
def get_named_dest_root(self) -> ArrayObject:
named_dest = ArrayObject()
if CA.NAMES in self.root_object and isinstance(
self.root_object[CA.NAMES], DictionaryObject
):
names = cast(DictionaryObject, self.root_object[CA.NAMES])
if CA.DESTS in names and isinstance(names[CA.DESTS], DictionaryObject):
# §3.6.3 Name Dictionary (PDF spec 1.7)
dests = cast(DictionaryObject, names[CA.DESTS])
dests_ref = dests.indirect_reference
if CA.NAMES in dests:
# §7.9.6, entries in a name tree node dictionary
named_dest = cast(ArrayObject, dests[CA.NAMES])
else:
named_dest = ArrayObject()
dests[NameObject(CA.NAMES)] = named_dest
elif hasattr(self, "_add_object"):
dests = DictionaryObject()
dests_ref = self._add_object(dests)
names[NameObject(CA.DESTS)] = dests_ref
dests[NameObject(CA.NAMES)] = named_dest
elif hasattr(self, "_add_object"):
names = DictionaryObject()
names_ref = self._add_object(names)
self.root_object[NameObject(CA.NAMES)] = names_ref
dests = DictionaryObject()
dests_ref = self._add_object(dests)
names[NameObject(CA.DESTS)] = dests_ref
dests[NameObject(CA.NAMES)] = named_dest
return named_dest
## common
def _get_named_destinations(
self,
*,
tree: Union[TreeObject, None] = None,
retval: Optional[dict[str, Destination]] = None,
visited: Optional[set[int]] = None,
) -> dict[str, Destination]:
"""
Retrieve the named destinations present in the document.
Args:
tree: The current tree.
retval: The previously retrieved destinations for nested calls.
visited: Already known/visited objects.
Returns:
A dictionary which maps names to destinations.
"""
if visited is None:
visited = set()
if retval is None:
retval = {}
catalog = self.root_object
# get the name tree
if CA.DESTS in catalog:
tree = cast(TreeObject, catalog[CA.DESTS])
elif CA.NAMES in catalog:
names = cast(DictionaryObject, catalog[CA.NAMES])
if CA.DESTS in names:
tree = cast(TreeObject, names[CA.DESTS])
if is_null_or_none(tree):
return retval
assert tree is not None, "mypy"
tree_id = id(tree)
if tree_id in visited:
logger_warning("Detected cycle in destination tree.", source=__name__)
return retval
visited.add(tree_id)
if PagesAttributes.KIDS in tree:
# recurse down the tree
for kid in cast(ArrayObject, tree[PagesAttributes.KIDS]):
self._get_named_destinations(tree=kid.get_object(), retval=retval, visited=visited)
# §7.9.6, entries in a name tree node dictionary
elif CA.NAMES in tree: # /Kids and /Names are exclusives (§7.9.6)
names = cast(DictionaryObject, tree[CA.NAMES])
i = 0
while i < len(names):
key = names[i].get_object()
i += 1
if not isinstance(key, (bytes, str)):
continue
try:
value = names[i].get_object()
except IndexError:
break
i += 1
if isinstance(value, DictionaryObject):
if "/D" in value:
value = value["/D"]
else:
continue
dest = self._build_destination(key, value)
if dest is not None:
retval[cast(str, dest["/Title"])] = dest
# Remain backwards-compatible.
retval[str(key)] = dest
else: # case where /Dests is in the document's catalog dictionary (PDF 1.7 specs, §2 about PDF 1.1)
for k__, v__ in tree.items():
val = v__.get_object()
if isinstance(val, DictionaryObject):
if "/D" in val:
val = val["/D"].get_object()
else:
continue
dest = self._build_destination(k__, val)
if dest is not None:
retval[k__] = dest
return retval
# A select group of relevant field attributes. For the complete list,
# see §12.3.2 of the PDF 1.7 or PDF 2.0 specification.
def get_fields(
self,
tree: Optional[TreeObject] = None,
retval: Optional[dict[Any, Any]] = None,
fileobj: Optional[Any] = None,
stack: Optional[list[PdfObject]] = None,
) -> Optional[dict[str, Any]]:
"""
Extract field data if this PDF contains interactive form fields.
The *tree*, *retval*, *stack* parameters are for recursive use.
Args:
tree: Current object to parse.
retval: In-progress list of fields.
fileobj: A file object (usually a text file) to write
a report to on all interactive form fields found.
stack: List of already parsed objects.
Returns:
A dictionary where each key is a field name, and each
value is a :class:`Field<pypdf.generic.Field>` object. By
default, the mapping name is used for keys.
``None`` if form data could not be located.
"""
field_attributes = FA.attributes_dict()
field_attributes.update(CheckboxRadioButtonAttributes.attributes_dict())
if retval is None:
retval = {}
catalog = self.root_object
stack = []
# get the AcroForm tree
if CA.ACRO_FORM in catalog:
tree = cast(Optional[TreeObject], catalog[CA.ACRO_FORM])
else:
return None
if tree is None:
return retval
assert stack is not None
if "/Fields" in tree:
fields = cast(ArrayObject, tree["/Fields"])
for f in fields:
field = f.get_object()
self._build_field(field, retval, fileobj, field_attributes, stack)
elif any(attr in tree for attr in field_attributes):
# Tree is a field
self._build_field(tree, retval, fileobj, field_attributes, stack)
return retval
def _get_qualified_field_name(
self,
*,
parent: DictionaryObject,
visited: Optional[set[int]] = None
) -> str:
if visited is None:
visited = set()
parent_id = id(parent)
if parent_id in visited:
raise LimitReachedError("Detected cycle in /Parent hierarchy when retrieving qualified field name.")
visited.add(parent_id)
if "/TM" in parent:
return cast(str, parent["/TM"])
if "/Parent" in parent:
return (
self._get_qualified_field_name(
parent=cast(DictionaryObject, parent["/Parent"]),
visited=visited,
)
+ "."
+ cast(str, parent.get("/T", ""))
)
return cast(str, parent.get("/T", ""))
@staticmethod
def _normal_appearance(appearance: Any) -> DictionaryObject:
"""Return the /N normal-appearance sub-dictionary of an /AP entry."""
appearance = appearance.get_object()
if not isinstance(appearance, DictionaryObject):
raise PdfReadError(f"Expected appearance dictionary, got {appearance!r}")
normal = appearance.get("/N")
if normal is not None:
normal = normal.get_object()
if not isinstance(normal, DictionaryObject):
raise PdfReadError(f"Expected /N appearance dictionary, got {normal!r}")
return normal
def _build_field(
self,
field: Union[TreeObject, DictionaryObject],
retval: dict[Any, Any],
fileobj: Any,
field_attributes: Any,
stack: list[PdfObject],
) -> None:
if all(attr not in field for attr in ("/T", "/TM")):
return
key = self._get_qualified_field_name(parent=field)
if fileobj:
self._write_field(fileobj, field, field_attributes)
fileobj.write("\n")
retval[key] = Field(field)
obj = retval[key].indirect_reference.get_object() # to get the full object
if obj.get(FA.FT, "") == "/Ch" and obj.get(NameObject(FA.Opt)):
retval[key][NameObject("/_States_")] = obj[NameObject(FA.Opt)]
if obj.get(FA.FT, "") == "/Btn" and "/AP" in obj:
# Checkbox
normal = self._normal_appearance(obj["/AP"])
retval[key][NameObject("/_States_")] = ArrayObject(list(normal.keys()))
if "/Off" not in retval[key]["/_States_"]:
retval[key][NameObject("/_States_")].append(NameObject("/Off"))
elif obj.get(FA.FT, "") == "/Btn" and obj.get(FA.Ff, 0) & FA.FfBits.Radio != 0:
states: list[str] = []
retval[key][NameObject("/_States_")] = ArrayObject(states)
for k in obj.get(FA.Kids, {}):
k = k.get_object()
if "/AP" not in k:
raise PdfReadError(f"Button field kid missing /AP: {k!r}")
normal = self._normal_appearance(k["/AP"])
for s in list(normal.keys()):
if s not in states:
states.append(s)
retval[key][NameObject("/_States_")] = ArrayObject(states)
if (
obj.get(FA.Ff, 0) & FA.FfBits.NoToggleToOff != 0
and "/Off" in retval[key]["/_States_"]
):
del retval[key]["/_States_"][retval[key]["/_States_"].index("/Off")]
# at last for order
self._check_kids(field, retval, fileobj, stack)
def _check_kids(
self,
tree: Union[TreeObject, DictionaryObject],
retval: Any,
fileobj: Any,
stack: list[PdfObject],
) -> None:
if tree in stack:
logger_warning(
"%(field_name)s already parsed",
source=__name__,
field_name=self._get_qualified_field_name(parent=tree),
)
return
stack.append(tree)
if PagesAttributes.KIDS in tree:
# recurse down the tree
for kid in tree[PagesAttributes.KIDS]: # type: ignore[attr-defined]
kid = kid.get_object()
self.get_fields(kid, retval, fileobj, stack)
def _write_field(self, fileobj: Any, field: Any, field_attributes: Any) -> None:
field_attributes_tuple = FA.attributes()
field_attributes_tuple = (
field_attributes_tuple + CheckboxRadioButtonAttributes.attributes()
)
for attr in field_attributes_tuple:
if attr in (
FA.Kids,
FA.AA,
):
continue
attr_name = field_attributes[attr]
try:
if attr == FA.FT:
# Make the field type value clearer
types = {
"/Btn": "Button",
"/Tx": "Text",
"/Ch": "Choice",
"/Sig": "Signature",
}
if field[attr] in types:
fileobj.write(f"{attr_name}: {types[field[attr]]}\n")
elif attr == FA.Parent:
# Let's just write the name of the parent
try:
name = field[attr][FA.TM]
except KeyError:
name = field[attr][FA.T]
fileobj.write(f"{attr_name}: {name}\n")
else:
fileobj.write(f"{attr_name}: {field[attr]}\n")
except KeyError:
# Field attribute is N/A or unknown, so don't write anything
pass
def get_form_text_fields(self, full_qualified_name: bool = False) -> dict[str, Any]:
"""
Retrieve form fields from the document with textual data.
Args:
full_qualified_name: to get full name
Returns:
A dictionary. The key is the name of the form field,
the value is the content of the field.
If the document contains multiple form fields with the same name, the
second and following will get the suffix .2, .3, ...
"""
def indexed_key(k: str, fields: dict[Any, Any]) -> str:
if k not in fields:
return k
return (
k
+ "."
+ str(sum(1 for kk in fields if kk.startswith(k + ".")) + 2)
)
# Retrieve document form fields
form_fields = self.get_fields()
if form_fields is None:
return {}
ff = {}
for field, value in form_fields.items():
if value.get("/FT") == "/Tx":
if full_qualified_name:
ff[field] = value.get("/V")
else:
ff[indexed_key(cast(str, value.get("/T", field)), ff)] = value.get("/V")
return ff
def get_pages_showing_field(
self, field: Union[Field, PdfObject, IndirectObject]
) -> list[PageObject]:
"""
Provides list of pages where the field is called.
Args:
field: Field Object, PdfObject or IndirectObject referencing a Field
Returns:
List of pages:
- Empty list:
The field has no widgets attached
(either hidden field or ancestor field).
- Single page list:
Page where the widget is present
(most common).
- Multi-page list:
Field with multiple kids widgets
(example: radio buttons, field repeated on multiple pages).
"""
try:
# to cope with all types
field = cast(DictionaryObject, field.indirect_reference.get_object()) # type: ignore[union-attr]
except Exception as exc:
raise ValueError("Field type is invalid") from exc
if is_null_or_none(field.get_inherited(key="/FT", default=None)):
raise ValueError("Field is not valid")
ret = []
if field.get("/Subtype", "") == "/Widget":
if "/P" in field:
ret = [field["/P"].get_object()]
else:
ret = [
p
for p in self.pages
if field.indirect_reference in p.get("/Annots", "")
]
else:
kids = field.get("/Kids", ())
for k in kids:
k = k.get_object()
if (k.get("/Subtype", "") == "/Widget") and ("/T" not in k):
# Kid that is just a widget, not a field:
if "/P" in k:
ret += [k["/P"].get_object()]
else:
ret += [
p
for p in self.pages
if k.indirect_reference in p.get("/Annots", "")
]
return [
x
if isinstance(x, PageObject)
else (self.pages[self._get_page_number_by_indirect(x.indirect_reference)]) # type: ignore[index, union-attr]
for x in ret
]
@property
def open_destination(
self,
) -> Union[Destination, TextStringObject, ByteStringObject, None]:
"""
Property to access the opening destination (``/OpenAction`` entry in
the PDF catalog). It returns ``None`` if the entry does not exist
or is not set.
Raises:
Exception: If a destination is invalid.
"""
if "/OpenAction" not in self.root_object:
return None
oa: Any = self.root_object["/OpenAction"]
if isinstance(oa, bytes): # pragma: no cover
oa = oa.decode()
if isinstance(oa, str):
return create_string_object(oa)
if isinstance(oa, ArrayObject):
try:
page, typ, *array = oa
fit = Fit(typ, tuple(array))
return Destination("OpenAction", page, fit)
except Exception as exc:
raise Exception(f"Invalid Destination {oa}: {exc}")
else:
return None
@open_destination.setter
def open_destination(self, dest: Union[str, Destination, PageObject, None]) -> None:
raise NotImplementedError("No setter for open_destination")
@property
def outline(self) -> OutlineType:
"""
Read-only property for the outline present in the document
(i.e., a collection of 'outline items' which are also known as
'bookmarks').
"""
return self._get_outline()
def _get_outline(
self,
*,
node: Optional[DictionaryObject] = None,
outline: Optional[Any] = None,
visited: Optional[set[int]] = None,
depth: int = 0,
traversal_state: Optional[_TraversalState] = None
) -> OutlineType:
if traversal_state is None:
traversal_state = _TraversalState()
if outline is None:
outline = []
catalog = self.root_object
# get the outline dictionary and named destinations
if Core.OUTLINES in catalog:
lines = cast(DictionaryObject, catalog[Core.OUTLINES])
if isinstance(lines, NullObject):
return outline
# §12.3.3 Document outline, entries in the outline dictionary
if not is_null_or_none(lines) and "/First" in lines:
node = cast(DictionaryObject, lines["/First"])
self._named_destinations = self._get_named_destinations()
if node is None:
return outline
if depth > OUTLINE_MAX_DEPTH:
raise LimitReachedError(f"Maximum outline depth reached: {depth} > {OUTLINE_MAX_DEPTH}.")
# see if there are any more outline items
if visited is None:
visited = set()
while True:
node_id = id(node)
if node_id in visited:
logger_warning("Detected cycle in outline structure for %(node)s", source=__name__, node=node)
break
visited.add(node_id)
traversal_state.entry_count += 1
if traversal_state.entry_count > OUTLINE_MAX_ENTRIES:
raise LimitReachedError(
f"Maximum outline entry limit reached: {traversal_state.entry_count} > {OUTLINE_MAX_ENTRIES}."
)
outline_obj = self._build_outline_item(node)
if outline_obj:
outline.append(outline_obj)
# check for sub-outline
if "/First" in node:
sub_outline: list[Any] = []
# Pass a copy to allow multiple outer entries to reference the same inner one.
inner_visited = visited.copy()
self._get_outline(
node=cast(DictionaryObject, node["/First"]),
outline=sub_outline,
visited=inner_visited,
depth=depth + 1,
traversal_state=traversal_state,
)
if sub_outline:
outline.append(sub_outline)
if "/Next" not in node:
break
node = cast(DictionaryObject, node["/Next"])
return outline
@property
def threads(self) -> Optional[ArrayObject]:
"""
Read-only property for the list of threads.
See §12.4.3 from the PDF 1.7 or 2.0 specification.
It is an array of dictionaries with "/F" (the first bead in the thread)
and "/I" (a thread information dictionary containing information about
the thread, such as its title, author, and creation date) properties or
None if there are no articles.
Since PDF 2.0 it can also contain an indirect reference to a metadata
stream containing information about the thread, such as its title,
author, and creation date.
"""
catalog = self.root_object
if Core.THREADS in catalog:
return cast("ArrayObject", catalog[Core.THREADS])
return None
@abstractmethod
def _get_page_number_by_indirect(
self, indirect_reference: Union[int, NullObject, IndirectObject, None]
) -> Optional[int]:
... # pragma: no cover
def get_page_number(self, page: PageObject) -> Optional[int]:
"""
Retrieve page number of a given PageObject.
Args:
page: The page to get page number. Should be
an instance of :class:`PageObject<pypdf._page.PageObject>`
Returns:
The page number or None if page is not found
"""
return self._get_page_number_by_indirect(page.indirect_reference)
def get_destination_page_number(self, destination: Destination) -> Optional[int]:
"""
Retrieve page number of a given Destination object.
Args:
destination: The destination to get page number.
Returns:
The page number or None if page is not found
"""
return self._get_page_number_by_indirect(destination.page)
def _build_destination(
self,
title: Union[str, bytes],
array: Optional[
list[
Union[NumberObject, IndirectObject, NullObject, DictionaryObject, None]
]
],
) -> Destination:
page, typ = None, None
# handle outline items with missing or invalid destination
if (
isinstance(array, (NullObject, str))
or (isinstance(array, ArrayObject) and len(array) < 2)
or array is None
):
page = NullObject()
return Destination(title, page, Fit.fit())
page, typ, *array = array # type: ignore[assignment]
try:
return Destination(title, page, Fit(fit_type=typ, fit_args=array)) # type: ignore[arg-type]
except PdfReadError:
logger_warning("Unknown destination: %(title)r %(array)s", source=__name__, title=title, array=array)
if self.strict:
raise
# create a link to first Page
tmp = self.pages[0].indirect_reference
indirect_reference = NullObject() if tmp is None else tmp
return Destination(title, indirect_reference, Fit.fit())
def _build_outline_item(self, node: DictionaryObject) -> Optional[Destination]:
dest, title, outline_item = None, None, None
# title required for valid outline
# §12.3.3, entries in an outline item dictionary
try:
title = cast("str", node["/Title"])
except KeyError:
if self.strict:
raise PdfReadError(f"Outline Entry Missing /Title attribute: {node!r}")
title = ""
if "/A" in node:
# Action, PDF 1.7 and PDF 2.0 §12.6 (only type GoTo supported)
action = cast(DictionaryObject, node["/A"])
action_type = cast(NameObject, action[GoToActionArguments.S])
if action_type == "/GoTo":
if GoToActionArguments.D in action:
dest = action[GoToActionArguments.D]
elif self.strict:
raise PdfReadError(f"Outline Action Missing /D attribute: {node!r}")
elif "/Dest" in node:
# Destination, PDF 1.7 and PDF 2.0 §12.3.2
dest = node["/Dest"]
# if array was referenced in another object, will be a dict w/ key "/D"
if isinstance(dest, DictionaryObject) and "/D" in dest:
dest = dest["/D"]
if isinstance(dest, ArrayObject):
outline_item = self._build_destination(title, dest)
elif isinstance(dest, str):
# named destination, addresses NameObject Issue #193
# TODO: Keep named destination instead of replacing it?
try:
outline_item = self._build_destination(
title, self._named_destinations[dest].dest_array
)
except KeyError:
# named destination not found in Name Dict
outline_item = self._build_destination(title, None)
elif dest is None:
# outline item not required to have destination or action
# PDFv1.7 Table 153
outline_item = self._build_destination(title, dest)
else:
if self.strict:
raise PdfReadError(f"Unexpected destination {dest!r}")
logger_warning(
"Removed unexpected destination %(dest)r from destination",
source=__name__,
dest=dest,
)
outline_item = self._build_destination(title, None)
# if outline item created, add color, format, and child count if present
if outline_item:
if "/C" in node:
# Color of outline item font in (R, G, B) with values ranging 0.0-1.0
color = node["/C"]
if isinstance(color, list):
outline_item[NameObject("/C")] = ArrayObject(FloatObject(c) for c in color)
else:
logger_warning(
"Ignoring non-array outline color %(color)r",
source=__name__,
color=color,
)
if "/F" in node:
# specifies style characteristics bold and/or italic
# with 1=italic, 2=bold, 3=both
outline_item[NameObject("/F")] = node["/F"]
if "/Count" in node:
# absolute value = num. visible children
# with positive = open/unfolded, negative = closed/folded
outline_item[NameObject("/Count")] = node["/Count"]
# if count is 0 we will consider it as open (to have available is_open)
outline_item[NameObject("/%is_open%")] = BooleanObject(
node.get("/Count", 0) >= 0
)
outline_item.node = node
try:
outline_item.indirect_reference = node.indirect_reference
except AttributeError:
pass
return outline_item
@property
def pages(self) -> Sequence[PageObject]:
"""
Property that emulates a list of :class:`PageObject<pypdf._page.PageObject>`.
This property allows to get a page or a range of pages.
The returned object supports indexing, slicing, ``len()``, iteration and
(for PdfWriter) ``del``, but it is not a :class:`list` - pages are looked
up on demand rather than materialised up front, so list-only operations
such as ``append()`` or concatenation with ``+`` are not available.
Note:
For PdfWriter only: Provides the capability to remove a page/range of
page from the list (using the del operator). Remember: Only the page
entry is removed, as the objects beneath can be used elsewhere. A
solution to completely remove them - if they are not used anywhere - is
to write to a buffer/temporary file and then load it into a new
PdfWriter.
"""
return _VirtualList(self.get_num_pages, self.get_page)
@property
def page_labels(self) -> list[str]:
"""
A list of labels for the pages in this document.
This property is read-only. The labels are in the order that the pages
appear in the document.
"""
return [page_index2page_label(self, i) for i in range(len(self.pages))]
@property
def page_layout(self) -> Optional[str]:
"""
Get the page layout currently being used.
.. list-table:: Valid ``layout`` values
:widths: 50 200
* - /NoLayout
- Layout explicitly not specified
* - /SinglePage
- Show one page at a time
* - /OneColumn
- Show one column at a time
* - /TwoColumnLeft
- Show pages in two columns, odd-numbered pages on the left
* - /TwoColumnRight
- Show pages in two columns, odd-numbered pages on the right
* - /TwoPageLeft
- Show two pages at a time, odd-numbered pages on the left
* - /TwoPageRight
- Show two pages at a time, odd-numbered pages on the right
"""
try:
return cast(NameObject, self.root_object[CA.PAGE_LAYOUT])
except KeyError:
return None
@property
def page_mode(self) -> Optional[PagemodeType]:
"""
Get the page mode currently being used.
.. list-table:: Valid ``mode`` values
:widths: 50 200
* - /UseNone
- Do not show outline or thumbnails panels
* - /UseOutlines
- Show outline (aka bookmarks) panel
* - /UseThumbs
- Show page thumbnails panel
* - /FullScreen
- Fullscreen view
* - /UseOC
- Show Optional Content Group (OCG) panel
* - /UseAttachments
- Show attachments panel
"""
try:
return self.root_object["/PageMode"] # type: ignore[return-value]
except KeyError:
return None
def _flatten(
self,
list_only: bool = False,
pages: Union[DictionaryObject, PageObject, None] = None,
inherit: Optional[dict[str, Any]] = None,
indirect_reference: Optional[IndirectObject] = None,
visited: Optional[set[int]] = None,
depth: int = 0,
traversal_state: Optional[_TraversalState] = None,
) -> None:
"""
Process the document pages to ease searching.
Attributes of a page may inherit from ancestor nodes
in the page tree. Flattening means moving
any inheritance data into descendant nodes,
effectively removing the inheritance dependency.
Note: It is distinct from another use of "flattening" applied to PDFs.
Flattening a PDF also means combining all the contents into one single layer
and making the file less editable.
Args:
list_only: Will only list the pages within _flatten_pages.
pages:
inherit:
indirect_reference: Used recursively to flatten the /Pages object.
visited: Set of id() values on the active page-tree traversal path.
Detects multi-hop cycles such as A→B→C→A that the single-parent
check misses.
depth: Current page-tree traversal depth.
traversal_state: State shared across the complete traversal.
"""
inheritable_page_attributes = (
NameObject(PG.RESOURCES),
NameObject(PG.MEDIABOX),
NameObject(PG.CROPBOX),
NameObject(PG.ROTATE),
)
if inherit is None:
inherit = {}
if visited is None:
visited = set()
if traversal_state is None:
traversal_state = _TraversalState()
if depth > PAGE_TREE_MAX_DEPTH:
raise LimitReachedError(f"Maximum page tree depth reached: {depth} > {PAGE_TREE_MAX_DEPTH}.")
if is_null_or_none(pages):
# Fix issue 327: set flattened_pages attribute only for
# decrypted file
catalog = self.root_object
pages = catalog.get("/Pages").get_object() # type: ignore[union-attr]
if not isinstance(pages, DictionaryObject):
raise PdfReadError("Invalid object in /Pages")
self.flattened_pages = []
assert pages is not None, "mypy"
if PagesAttributes.TYPE in pages:
t = cast(str, pages[PagesAttributes.TYPE])
# if the page tree node has no /Type, consider as a page if /Kids is also missing
elif PagesAttributes.KIDS not in pages:
# Without /Type, only accept it as a page if it carries a structural page key.
if self.strict and not any(
key in pages for key in (PG.CONTENTS, PG.MEDIABOX, PG.PARENT)
):
raise PdfReadError(f"Non-page object reached through /Kids: {pages!r}")
t = "/Page"
else:
t = "/Pages"
if t == "/Pages":
for attr in inheritable_page_attributes:
if attr in pages:
inherit[attr] = pages[attr]
pages_reference = getattr(pages, "indirect_reference", object())
kids = pages.get(PagesAttributes.KIDS, ArrayObject()).get_object()
if isinstance(kids, NullObject):
kids = ArrayObject()
elif not isinstance(kids, ArrayObject):
raise PdfReadError(
f"Expected /Kids to be an array, got {type(kids).__name__}."
)
for page in kids:
if getattr(page, "indirect_reference", object()) == pages_reference:
raise PdfReadError("Detected cyclic page references.")
additional_arguments = {}
if isinstance(page, IndirectObject):
additional_arguments["indirect_reference"] = page
obj = page.get_object()
if obj:
# damaged file may have invalid child in /Pages
obj_id = id(obj)
if obj_id in visited:
raise PdfReadError("Detected cyclic page references.")
traversal_state.entry_count += 1
if traversal_state.entry_count > PAGE_TREE_MAX_ENTRIES:
raise LimitReachedError(
"Maximum page tree entry limit reached: "
f"{traversal_state.entry_count} > {PAGE_TREE_MAX_ENTRIES}."
)
visited.add(obj_id)
try:
self._flatten(
list_only,
obj,
inherit.copy(),
visited=visited,
depth=depth + 1,
traversal_state=traversal_state,
**additional_arguments,
)
finally:
visited.remove(obj_id)
elif t == "/Page":
page_obj = PageObject(self, indirect_reference)
if not list_only:
page_obj.update(pages)
for attr_in, value in inherit.items():
# if the page has its own value, it does not inherit the
# parent's value
if attr_in not in page_obj:
page_obj[attr_in] = value
# TODO: Could flattened_pages be None at this point?
self.flattened_pages.append(page_obj) # type: ignore[union-attr]
def remove_page(
self,
page: Union[int, PageObject, IndirectObject],
clean: bool = False,
) -> None:
"""
Remove page from pages list.
Args:
page:
* :class:`int`: Page number to be removed.
* :class:`~pypdf._page.PageObject`: page to be removed. If the page appears many times
only the first one will be removed.
* :class:`~pypdf.generic.IndirectObject`: Reference to page to be removed.
clean: replace PageObject with NullObject to prevent annotations
or destinations to reference a detached page.
"""
if self.flattened_pages is None:
self._flatten(self._readonly)
assert self.flattened_pages is not None
if isinstance(page, IndirectObject):
p = page.get_object()
if not isinstance(p, PageObject):
logger_warning("IndirectObject is not referencing a page", source=__name__)
return
page = p
if not isinstance(page, int):
try:
page = self.flattened_pages.index(page)
except ValueError:
logger_warning("Cannot find page in pages", source=__name__)
return
if not (0 <= page < len(self.flattened_pages)):
logger_warning("Page number is out of range", source=__name__)
return
ind = self.pages[page].indirect_reference
# `pages` is typed as a Sequence because it is not a list, but the
# concrete _VirtualList does implement deletion.
del cast(_VirtualList, self.pages)[page]
if clean and ind is not None:
self._replace_object(ind, NullObject())
def _get_indirect_object(self, num: int, gen: int) -> Optional[PdfObject]:
"""
Used to ease development.
This is equivalent to generic.IndirectObject(num,gen,self).get_object()
Args:
num: The object number of the indirect object.
gen: The generation number of the indirect object.
Returns:
A PdfObject
"""
return IndirectObject(num, gen, self).get_object()
def decode_permissions(
self, permissions_code: int
) -> NoReturn: # pragma: no cover
"""Take the permissions as an integer, return the allowed access."""
deprecation_with_replacement(
old_name="decode_permissions",
new_name="user_access_permissions",
removed_in="5.0.0",
)
@property
def user_access_permissions(self) -> Optional[UserAccessPermissions]:
"""
Get the user access permissions for encrypted documents.
Returns None if not encrypted.
.. warning::
For AES-256 encrypted documents (R=5/R=6), the returned
permissions are derived from the ``/P`` field, which is
only trustworthy if the ``/Perms`` integrity check passed.
Check :attr:`are_permissions_valid` to verify.
"""
if self._encryption is None:
return None
return UserAccessPermissions(self._encryption.P)
@property
def are_permissions_valid(self) -> Optional[bool]:
"""
Whether the ``/Perms`` integrity check passed for this document.
For AES-256 encrypted documents (R=5/R=6), the ``/Perms`` field
is an encrypted copy of the permissions that can be verified
independently. Returns ``False`` if this check fails (the ``/P``
permissions may have been tampered with).
Returns ``None`` if the document is not encrypted or has not yet
been decrypted via :meth:`decrypt()<pypdf.PdfReader.decrypt>`.
Returns ``True`` for non-AES-256 encryption (no ``/Perms`` to check).
"""
if self._encryption is None:
return None
if not self._encryption.is_decrypted():
return None
return self._encryption._are_permissions_valid
@property
@abstractmethod
def is_encrypted(self) -> bool:
"""
Read-only boolean property showing whether this PDF file is encrypted.
Note that this property, if true, will remain true even after the
:meth:`decrypt()<pypdf.PdfReader.decrypt>` method is called.
"""
... # pragma: no cover
@property
def xfa(self) -> Optional[dict[str, Any]]:
retval: dict[str, Any] = {}
catalog = self.root_object
if "/AcroForm" not in catalog or not catalog["/AcroForm"]:
return None
tree = cast(TreeObject, catalog["/AcroForm"])
if "/XFA" in tree:
fields = cast(ArrayObject, tree["/XFA"])
i = iter(fields)
for f in i:
tag = f
f = next(i)
if isinstance(f, IndirectObject):
field = cast(Optional[EncodedStreamObject], f.get_object())
if field:
es = _decompress_with_limit(field._data)
retval[tag] = es
return retval
@property
def attachments(self) -> Mapping[str, list[bytes]]:
"""Mapping of attachment filenames to their content."""
return LazyDict(
{
name: (self._get_attachment_list, name)
for name in self._list_attachments()
}
)
@property
def attachment_list(self) -> Generator[EmbeddedFile, None, None]:
"""Iterable of attachment objects."""
yield from EmbeddedFile._load(self.root_object)
def _list_attachments(self) -> list[str]:
"""
Retrieves the list of filenames of file attachments.
Returns:
list of filenames
"""
names = []
for entry in self.attachment_list:
names.append(entry.name)
if (name := entry.alternative_name) != entry.name and name:
names.append(name)
return names
def _get_attachment_list(self, name: str) -> list[bytes]:
out = self._get_attachments(name)[name]
if isinstance(out, list):
return out
return [out]
def _get_attachments(
self, filename: Optional[str] = None
) -> dict[str, Union[bytes, list[bytes]]]:
"""
Retrieves all or selected file attachments of the PDF as a dictionary of file names
and the file data as a bytestring.
Args:
filename: If filename is None, then a dictionary of all attachments
will be returned, where the key is the filename and the value
is the content. Otherwise, a dictionary with just a single key
- the filename - and its content will be returned.
Returns:
dictionary of filename -> Union[bytestring or List[ByteString]]
If the filename exists multiple times a list of the different versions will be provided.
"""
attachments: dict[str, Union[bytes, list[bytes]]] = {}
for entry in self.attachment_list:
names = set()
alternative_name = entry.alternative_name
if filename is not None:
if filename in {entry.name, alternative_name}:
name = entry.name if filename == entry.name else alternative_name
names.add(name)
else:
continue
else:
names = {entry.name, alternative_name}
for name in names:
if name is None:
continue
if name in attachments:
if not isinstance(attachments[name], list):
attachments[name] = [attachments[name]] # type:ignore
attachments[name].append(entry.content) # type:ignore
else:
attachments[name] = entry.content
return attachments
@abstractmethod
def _repr_mimebundle_(
self,
include: Union[Iterable[str], None] = None,
exclude: Union[Iterable[str], None] = None,
) -> dict[str, Any]:
"""
Integration into Jupyter Notebooks.
This method returns a dictionary that maps a mime-type to its
representation.
.. seealso::
https://ipython.readthedocs.io/en/stable/config/integrating.html
"""
... # pragma: no cover
class LazyDict(Mapping[Any, Any]):
def __init__(self, *args: Any, **kwargs: Any) -> None:
self._raw_dict = dict(*args, **kwargs)
def __getitem__(self, key: str) -> Any:
func, arg = self._raw_dict.__getitem__(key)
return func(arg)
def __iter__(self) -> Iterator[Any]:
return iter(self._raw_dict)
def __len__(self) -> int:
return len(self._raw_dict)
def __str__(self) -> str:
return f"LazyDict(keys={list(self.keys())})"
|