Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/pypdf/_doc_common.py: 19%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# Copyright (c) 2006, Mathieu Fenniak
2# Copyright (c) 2007, Ashish Kulkarni <kulkarni.ashish@gmail.com>
3# Copyright (c) 2024, Pubpub-ZZ
4#
5# All rights reserved.
6#
7# Redistribution and use in source and binary forms, with or without
8# modification, are permitted provided that the following conditions are
9# met:
10#
11# * Redistributions of source code must retain the above copyright notice,
12# this list of conditions and the following disclaimer.
13# * Redistributions in binary form must reproduce the above copyright notice,
14# this list of conditions and the following disclaimer in the documentation
15# and/or other materials provided with the distribution.
16# * The name of the author may not be used to endorse or promote products
17# derived from this software without specific prior written permission.
18#
19# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
23# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29# POSSIBILITY OF SUCH DAMAGE.
31import contextlib
32import struct
33from abc import ABC, abstractmethod
34from collections.abc import Iterable, Iterator, Mapping, Sequence
35from datetime import datetime
36from typing import (
37 Any,
38 NamedTuple,
39 cast,
40)
42from ._configuration import get_configuration
43from ._encryption import Encryption
44from ._page import PageObject, _VirtualList
45from ._page_labels import index2labels
46from ._utils import (
47 _TraversalState,
48 deprecation_no_replacement,
49 logger_warning,
50 parse_iso8824_date,
51)
52from .constants import (
53 CatalogAttributes,
54 CheckboxRadioButtonAttributes,
55 Core,
56 DocumentInformationAttributes,
57 FieldDictionaryAttributes,
58 GoToActionArguments,
59 PageAttributes,
60 PagesAttributes,
61 UserAccessPermissions,
62)
63from .errors import LimitReachedError, PdfReadError, PyPdfError
64from .generic import (
65 ArrayObject,
66 BooleanObject,
67 ByteStringObject,
68 Destination,
69 DictionaryObject,
70 Field,
71 Fit,
72 FloatObject,
73 IndirectObject,
74 NameObject,
75 NullObject,
76 PdfObject,
77 StreamObject,
78 TextStringObject,
79 TreeObject,
80 ViewerPreferences,
81 create_string_object,
82 is_null_or_none,
83)
84from .generic._data_structures import _flatten_name_tree
85from .generic._files import EmbeddedFile
86from .types import OutlineType, PagemodeType
87from .xmp import XmpInformation
90def convert_to_int(d: bytes, size: int) -> int | tuple[Any, ...]:
91 if size > 8:
92 raise PdfReadError("Invalid size in convert_to_int")
93 d = b"\x00\x00\x00\x00\x00\x00\x00\x00" + d
94 d = d[-8:]
95 return cast(int, struct.unpack(">Q", d)[0])
98# Attributes a page inherits from its ancestors in the page tree.
99_INHERITABLE_PAGE_ATTRIBUTES = (
100 NameObject(PageAttributes.RESOURCES),
101 NameObject(PageAttributes.MEDIABOX),
102 NameObject(PageAttributes.CROPBOX),
103 NameObject(PageAttributes.ROTATE),
104)
107class _PageTreeItem(NamedTuple):
108 """A page tree node waiting to be flattened by :meth:`PdfDocCommon._flatten`."""
110 node: DictionaryObject
111 #: Inherited attributes. Shared read-only between the kids of one node.
112 inherit: dict[str, Any]
113 indirect_reference: IndirectObject | None
114 depth: int
117class _DottedNameNode:
118 """Counts the field names which continue with "." after one part of a dotted name."""
120 __slots__ = ("children", "count")
122 def __init__(self) -> None:
123 self.count = 0
124 self.children: dict[str, _DottedNameNode] = {}
127#: A ``/Pages`` node currently being walked: the node - carrying the attributes its
128#: kids inherit - and the part of its ``/Kids`` which has not been reached yet.
129_PageTreeFrame = tuple[_PageTreeItem, Iterator[PdfObject]]
131_UNSET = object()
134class DocumentInformation(DictionaryObject):
135 """
136 A class representing the basic document metadata provided in a PDF File.
137 This class is accessible through
138 :py:class:`PdfReader.metadata<pypdf.PdfReader.metadata>`.
140 All text properties of the document metadata have
141 *two* properties, e.g. author and author_raw. The non-raw property will
142 always return a ``TextStringObject``, making it ideal for a case where the
143 metadata is being displayed. The raw property can sometimes return a
144 ``ByteStringObject``, if pypdf was unable to decode the string's text
145 encoding; this requires additional safety in the caller and therefore is not
146 as commonly accessed.
147 """
149 def __init__(self) -> None:
150 DictionaryObject.__init__(self)
152 def _get_text(self, key: str) -> str | None:
153 retval = self.get(key, None)
154 if isinstance(retval, TextStringObject):
155 return retval
156 if isinstance(retval, ByteStringObject):
157 return str(retval)
158 return None
160 @property
161 def title(self) -> str | None:
162 """
163 Read-only property accessing the document's title.
165 Returns a ``TextStringObject`` or ``None`` if the title is not
166 specified.
167 """
168 return (
169 self._get_text(DocumentInformationAttributes.TITLE)
170 or self.get(DocumentInformationAttributes.TITLE).get_object() # type: ignore[union-attr]
171 if self.get(DocumentInformationAttributes.TITLE)
172 else None
173 )
175 @property
176 def title_raw(self) -> str | None:
177 """The "raw" version of title; can return a ``ByteStringObject``."""
178 return self.get(DocumentInformationAttributes.TITLE)
180 @property
181 def author(self) -> str | None:
182 """
183 Read-only property accessing the document's author.
185 Returns a ``TextStringObject`` or ``None`` if the author is not
186 specified.
187 """
188 return self._get_text(DocumentInformationAttributes.AUTHOR)
190 @property
191 def author_raw(self) -> str | None:
192 """The "raw" version of author; can return a ``ByteStringObject``."""
193 return self.get(DocumentInformationAttributes.AUTHOR)
195 @property
196 def subject(self) -> str | None:
197 """
198 Read-only property accessing the document's subject.
200 Returns a ``TextStringObject`` or ``None`` if the subject is not
201 specified.
202 """
203 return self._get_text(DocumentInformationAttributes.SUBJECT)
205 @property
206 def subject_raw(self) -> str | None:
207 """The "raw" version of subject; can return a ``ByteStringObject``."""
208 return self.get(DocumentInformationAttributes.SUBJECT)
210 @property
211 def creator(self) -> str | None:
212 """
213 Read-only property accessing the document's creator.
215 If the document was converted to PDF from another format, this is the
216 name of the application (e.g. OpenOffice) that created the original
217 document from which it was converted. Returns a ``TextStringObject`` or
218 ``None`` if the creator is not specified.
219 """
220 return self._get_text(DocumentInformationAttributes.CREATOR)
222 @property
223 def creator_raw(self) -> str | None:
224 """The "raw" version of creator; can return a ``ByteStringObject``."""
225 return self.get(DocumentInformationAttributes.CREATOR)
227 @property
228 def producer(self) -> str | None:
229 """
230 Read-only property accessing the document's producer.
232 If the document was converted to PDF from another format, this is the
233 name of the application (for example, macOS Quartz) that converted it to
234 PDF. Returns a ``TextStringObject`` or ``None`` if the producer is not
235 specified.
236 """
237 return self._get_text(DocumentInformationAttributes.PRODUCER)
239 @property
240 def producer_raw(self) -> str | None:
241 """The "raw" version of producer; can return a ``ByteStringObject``."""
242 return self.get(DocumentInformationAttributes.PRODUCER)
244 @property
245 def creation_date(self) -> datetime | None:
246 """Read-only property accessing the document's creation date."""
247 return parse_iso8824_date(self._get_text(DocumentInformationAttributes.CREATION_DATE))
249 @property
250 def creation_date_raw(self) -> str | None:
251 """
252 The "raw" version of creation date; can return a ``ByteStringObject``.
254 Typically in the format ``D:YYYYMMDDhhmmss[+Z-]hh'mm`` where the suffix
255 is the offset from UTC.
256 """
257 return self.get(DocumentInformationAttributes.CREATION_DATE)
259 @property
260 def modification_date(self) -> datetime | None:
261 """
262 Read-only property accessing the document's modification date.
264 The date and time the document was most recently modified.
265 """
266 return parse_iso8824_date(self._get_text(DocumentInformationAttributes.MOD_DATE))
268 @property
269 def modification_date_raw(self) -> str | None:
270 """
271 The "raw" version of modification date; can return a
272 ``ByteStringObject``.
274 Typically, in the format ``D:YYYYMMDDhhmmss[+Z-]hh'mm`` where the suffix
275 is the offset from UTC.
276 """
277 return self.get(DocumentInformationAttributes.MOD_DATE)
279 @property
280 def keywords(self) -> str | None:
281 """
282 Read-only property accessing the document's keywords.
284 Returns a ``TextStringObject`` or ``None`` if keywords are not
285 specified.
286 """
287 return self._get_text(DocumentInformationAttributes.KEYWORDS)
289 @property
290 def keywords_raw(self) -> str | None:
291 """The "raw" version of keywords; can return a ``ByteStringObject``."""
292 return self.get(DocumentInformationAttributes.KEYWORDS)
295class PdfDocCommon(ABC):
296 """
297 Common functions from PdfWriter and PdfReader objects.
299 This root class is strongly abstracted.
300 """
302 strict: bool = False # default
304 flattened_pages: list[PageObject] | None = None
306 _encryption: Encryption | None = None
308 _readonly: bool = False
310 @property
311 @abstractmethod
312 def root_object(self) -> DictionaryObject:
313 ... # pragma: no cover
315 @property
316 @abstractmethod
317 def pdf_header(self) -> str:
318 ... # pragma: no cover
320 @abstractmethod
321 def get_object(
322 self, indirect_reference: int | IndirectObject
323 ) -> PdfObject | None:
324 ... # pragma: no cover
326 @abstractmethod
327 def _replace_object(self, indirect_reference: IndirectObject, obj: PdfObject) -> PdfObject:
328 ... # pragma: no cover
330 @property
331 @abstractmethod
332 def _info(self) -> DictionaryObject | None:
333 ... # pragma: no cover
335 @property
336 def metadata(self) -> DocumentInformation | None:
337 """
338 Retrieve the PDF file's document information dictionary, if it exists.
340 Note that some PDF files use metadata streams instead of document
341 information dictionaries, and these metadata streams will not be
342 accessed by this function.
343 """
344 retval = DocumentInformation()
345 if self._info is None:
346 return None
347 retval.update(self._info)
348 return retval
350 @property
351 @abstractmethod
352 def xmp_metadata(self) -> XmpInformation | None:
353 ... # pragma: no cover
355 @property
356 def viewer_preferences(self) -> ViewerPreferences | None:
357 """Returns the existing ViewerPreferences as an overloaded dictionary."""
358 o = self.root_object.get(CatalogAttributes.VIEWER_PREFERENCES, None)
359 if o is None:
360 return None
361 o = o.get_object()
362 if not isinstance(o, DictionaryObject):
363 logger_warning(
364 "Viewer preferences are not a dictionary: %(preferences)s",
365 source=__name__,
366 preferences=o,
367 )
368 return None
369 if not isinstance(o, ViewerPreferences):
370 o = ViewerPreferences(o)
371 if hasattr(o, "indirect_reference") and o.indirect_reference is not None:
372 self._replace_object(o.indirect_reference, o)
373 else:
374 self.root_object[NameObject(CatalogAttributes.VIEWER_PREFERENCES)] = o
375 return o
377 def get_num_pages(self) -> int:
378 """
379 Calculate the number of pages in this PDF file.
381 Returns:
382 The number of pages of the parsed PDF file.
384 Raises:
385 PdfReadError: If restrictions prevent this action.
387 """
388 # The page tree cannot be walked while the document is still encrypted;
389 # the PDF file's page count is used in this case. Once the document has
390 # been decrypted (or if it is not encrypted at all), the flattened page
391 # tree is used instead, as the /Count value might be wrong.
392 encryption = self._encryption
393 if self.is_encrypted and (encryption is None or not encryption.is_decrypted()):
394 return self.root_object["/Pages"]["/Count"] # type: ignore[no-any-return, index]
395 if self.flattened_pages is None:
396 self._flatten(self._readonly)
397 assert self.flattened_pages is not None
398 return len(self.flattened_pages)
400 def get_page(self, page_number: int) -> PageObject:
401 """
402 Retrieve a page by number from this PDF file.
403 Most of the time ``.pages[page_number]`` is preferred.
405 Args:
406 page_number: The page number to retrieve
407 (pages begin at zero)
409 Returns:
410 A :class:`PageObject<pypdf._page.PageObject>` instance.
412 """
413 if self.flattened_pages is None:
414 self._flatten(self._readonly)
415 assert self.flattened_pages is not None, "mypy"
416 return self.flattened_pages[page_number]
418 def _get_page_in_node(
419 self,
420 page_number: int,
421 ) -> tuple[DictionaryObject, int]:
422 """
423 Retrieve the node and position within the /Kids containing the page.
424 If page_number is greater than the number of pages, it returns the top node, -1.
425 """
426 top = cast(DictionaryObject, self.root_object["/Pages"])
427 visited: set[int] = set()
429 def recursive_call(
430 _node: DictionaryObject, mi: int
431 ) -> tuple[PdfObject | None, int]:
432 _node_id = id(_node)
433 if _node_id in visited:
434 raise LimitReachedError("Detected cycle in /Pages hierarchy when retrieving page.")
435 visited.add(_node_id)
436 ma = cast(int, _node.get("/Count", 1)) # default 1 for /Page types
437 if _node.get("/Type") == "/Page":
438 if page_number == mi:
439 return _node, -1
440 return None, mi + 1
441 if (page_number - mi) >= ma: # not in nodes below
442 if _node == top:
443 return top, -1
444 return None, mi + ma
445 for _idx, kid in enumerate(cast(ArrayObject, _node["/Kids"])):
446 kid = cast(DictionaryObject, kid.get_object())
447 n, i = recursive_call(kid, mi)
448 if n is not None: # page has just been found ...
449 if i < 0: # ... just below!
450 return _node, _idx
451 # ... at lower levels
452 return n, i
453 mi = i
454 raise PyPdfError("Unexpectedly cannot find the node.")
456 node, idx = recursive_call(top, 0)
457 assert isinstance(node, DictionaryObject), "mypy"
458 return node, idx
460 @property
461 def named_destinations(self) -> dict[str, Destination]:
462 """A read-only dictionary which maps names to destinations."""
463 return self._get_named_destinations()
465 def get_named_dest_root(self) -> ArrayObject:
466 named_dest = ArrayObject()
467 if CatalogAttributes.NAMES in self.root_object and isinstance(
468 self.root_object[CatalogAttributes.NAMES], DictionaryObject
469 ):
470 names = cast(DictionaryObject, self.root_object[CatalogAttributes.NAMES])
471 if CatalogAttributes.DESTS in names and isinstance(names[CatalogAttributes.DESTS], DictionaryObject):
472 # §3.6.3 Name Dictionary (PDF spec 1.7)
473 dests = cast(DictionaryObject, names[CatalogAttributes.DESTS])
474 if CatalogAttributes.NAMES in dests:
475 # §7.9.6, entries in a name tree node dictionary
476 named_dest = cast(ArrayObject, dests[CatalogAttributes.NAMES])
477 else:
478 named_dest = _flatten_name_tree(dests)
479 elif hasattr(self, "_add_object"):
480 dests = DictionaryObject()
481 dests_ref = self._add_object(dests)
482 names[NameObject(CatalogAttributes.DESTS)] = dests_ref
483 dests[NameObject(CatalogAttributes.NAMES)] = named_dest
485 elif hasattr(self, "_add_object"):
486 names = DictionaryObject()
487 names_ref = self._add_object(names)
488 self.root_object[NameObject(CatalogAttributes.NAMES)] = names_ref
489 dests = DictionaryObject()
490 dests_ref = self._add_object(dests)
491 names[NameObject(CatalogAttributes.DESTS)] = dests_ref
492 dests[NameObject(CatalogAttributes.NAMES)] = named_dest
494 return named_dest
496 ## common
497 def _get_named_destinations(
498 self,
499 *,
500 tree: DictionaryObject | None = None,
501 retval: dict[str, Destination] | None = None,
502 visited: set[int] | None = None,
503 depth: int = 0,
504 traversal_state: _TraversalState | None = None,
505 ) -> dict[str, Destination]:
506 """
507 Retrieve the named destinations present in the document.
509 Args:
510 tree: The current tree.
511 retval: The previously retrieved destinations for nested calls.
512 visited: Already known/visited objects.
513 depth: Current name tree nesting depth.
514 traversal_state: Shared visitor counters.
516 Returns:
517 A dictionary which maps names to destinations.
519 """
520 if traversal_state is None:
521 traversal_state = _TraversalState()
523 if visited is None:
524 visited = set()
525 if retval is None:
526 retval = {}
527 catalog = self.root_object
529 # get the name tree
530 candidate: PdfObject | None = None
531 if CatalogAttributes.DESTS in catalog:
532 candidate = catalog[CatalogAttributes.DESTS].get_object()
533 elif CatalogAttributes.NAMES in catalog:
534 names = catalog[CatalogAttributes.NAMES].get_object()
535 if isinstance(names, DictionaryObject) and CatalogAttributes.DESTS in names:
536 candidate = names[CatalogAttributes.DESTS].get_object()
537 if candidate is not None and not isinstance(candidate, DictionaryObject):
538 logger_warning(
539 "Destination tree is not a dictionary: %(tree)s",
540 source=__name__,
541 tree=candidate,
542 )
543 return retval
544 if candidate is not None:
545 tree = candidate
547 if is_null_or_none(tree):
548 return retval
549 assert tree is not None, "mypy"
551 configuration = get_configuration()
552 if depth > configuration.named_destinations_maximum_depth:
553 raise LimitReachedError(
554 f"Maximum named destination depth exceeded: "
555 f"{depth} > {configuration.named_destinations_maximum_depth}."
556 )
558 tree_id = id(tree)
559 if tree_id in visited:
560 logger_warning("Detected cycle in destination tree.", source=__name__)
561 return retval
562 visited.add(tree_id)
564 traversal_state.entry_count += 1
565 if traversal_state.entry_count > configuration.named_destinations_maximum_entries:
566 raise LimitReachedError(
567 f"Maximum named destination entry limit exceeded: "
568 f"{traversal_state.entry_count} > {configuration.named_destinations_maximum_entries}."
569 )
571 if PagesAttributes.KIDS in tree:
572 kids = tree[PagesAttributes.KIDS].get_object()
573 if not isinstance(kids, ArrayObject):
574 logger_warning(
575 "Destination tree kids are not an array: %(kids)s",
576 source=__name__,
577 kids=kids,
578 )
579 return retval
580 # recurse down the tree
581 for kid in kids:
582 self._get_named_destinations(
583 tree=kid.get_object(),
584 retval=retval,
585 visited=visited,
586 depth=depth + 1,
587 traversal_state=traversal_state,
588 )
589 # §7.9.6, entries in a name tree node dictionary
590 elif CatalogAttributes.NAMES in tree: # /Kids and /Names are exclusives (§7.9.6)
591 names = tree[CatalogAttributes.NAMES].get_object()
592 if not isinstance(names, ArrayObject):
593 logger_warning(
594 "Destination tree names are not an array: %(names)s",
595 source=__name__,
596 names=names,
597 )
598 return retval
599 i = 0
600 while i < len(names):
601 key = names[i].get_object()
602 i += 1
603 if not isinstance(key, (bytes, str)):
604 continue
605 try:
606 value = names[i].get_object()
607 except IndexError:
608 break
609 i += 1
610 if isinstance(value, DictionaryObject):
611 if "/D" in value:
612 value = value["/D"]
613 else:
614 continue
615 dest = self._build_destination(key, value)
616 if dest is not None:
617 retval[cast(str, dest["/Title"])] = dest
618 # Remain backwards-compatible.
619 retval[str(key)] = dest
620 else: # case where /Dests is in the document's catalog dictionary (PDF 1.7 specs, §2 about PDF 1.1)
621 for k__, v__ in tree.items():
622 val = v__.get_object()
623 if isinstance(val, DictionaryObject):
624 if "/D" in val:
625 val = val["/D"].get_object()
626 else:
627 continue
628 dest = self._build_destination(k__, val)
629 if dest is not None:
630 retval[k__] = dest
631 return retval
633 # A select group of relevant field attributes. For the complete list,
634 # see §12.3.2 of the PDF 1.7 or PDF 2.0 specification.
636 def get_fields(
637 self,
638 tree: DictionaryObject | None = None,
639 retval: dict[Any, Any] | None = None,
640 fileobj: Any | None = None,
641 stack: Any = _UNSET,
642 *,
643 _visited: set[int] | None = None,
644 _depth: int = 0,
645 _traversal_state: _TraversalState | None = None,
646 ) -> dict[str, Any] | None:
647 """
648 Extract field data if this PDF contains interactive form fields.
650 The *tree*, *retval*, *visited*, *depth* parameters are for internal use.
652 Args:
653 tree: Current object to parse.
654 retval: In-progress list of fields.
655 fileobj: A file object (usually a text file) to write
656 a report to on all interactive form fields found.
657 stack: The stack to use. Deprecated.
658 _visited: Set of already visited IDs. Callers should usually omit this.
659 _depth: The current field depth.
660 _traversal_state: The current traversal state.
662 Returns:
663 A dictionary where each key is a field name, and each
664 value is a :class:`Field<pypdf.generic.Field>` object. By
665 default, the mapping name is used for keys.
666 ``None`` if form data could not be located.
668 """
669 if stack is not _UNSET:
670 deprecation_no_replacement(name="stack", removed_in="7.0.0")
672 configuration = get_configuration()
673 if _depth >= configuration.form_fields_maximum_depth:
674 raise LimitReachedError("Reached maximum allowed form field depth.")
675 if _traversal_state is None:
676 _traversal_state = _TraversalState()
678 def _check_field_limit(_increment: int) -> None:
679 _traversal_state.entry_count += _increment
680 if _traversal_state.entry_count > configuration.form_fields_maximum_entries:
681 raise LimitReachedError("Exceeded maximum number of fields allowed.")
683 field_attributes = FieldDictionaryAttributes.attributes_dict()
684 field_attributes.update(CheckboxRadioButtonAttributes.attributes_dict())
685 if retval is None:
686 retval = {}
687 catalog = self.root_object
688 _visited = set()
689 # get the AcroForm tree
690 if CatalogAttributes.ACRO_FORM in catalog:
691 entry = catalog[CatalogAttributes.ACRO_FORM]
692 acro_form = None if entry is None else entry.get_object()
693 if acro_form is not None and not isinstance(
694 acro_form, DictionaryObject
695 ):
696 logger_warning(
697 "AcroForm is not a dictionary: %(acro_form)s",
698 source=__name__,
699 acro_form=acro_form,
700 )
701 return None
702 tree = acro_form
703 else:
704 return None
705 if tree is None:
706 return retval
707 assert _visited is not None
708 if "/Fields" in tree:
709 fields = tree["/Fields"].get_object()
710 if not isinstance(fields, ArrayObject):
711 logger_warning(
712 "AcroForm /Fields is not an array: %(fields)s",
713 source=__name__,
714 fields=fields,
715 )
716 return retval
717 _check_field_limit(len(fields))
718 for f in fields:
719 field = f.get_object()
720 self._build_field(
721 field=field, retval=retval, fileobj=fileobj, field_attributes=field_attributes,
722 visited=_visited, depth=_depth, traversal_state=_traversal_state,
723 )
724 elif any(attr in tree for attr in field_attributes):
725 # Tree is a field
726 _check_field_limit(1)
727 self._build_field(
728 field=tree, retval=retval, fileobj=fileobj, field_attributes=field_attributes,
729 visited=_visited, depth=_depth, traversal_state=_traversal_state,
730 )
731 return retval
733 def _get_qualified_field_name(
734 self,
735 *,
736 parent: DictionaryObject,
737 visited: set[int] | None = None
738 ) -> str:
739 if visited is None:
740 visited = set()
741 parent_id = id(parent)
742 if parent_id in visited:
743 raise LimitReachedError("Detected cycle in /Parent hierarchy when retrieving qualified field name.")
744 visited.add(parent_id)
746 if "/TM" in parent:
747 return cast(str, parent["/TM"])
748 if "/Parent" in parent:
749 return (
750 self._get_qualified_field_name(
751 parent=cast(DictionaryObject, parent["/Parent"]),
752 visited=visited,
753 )
754 + "."
755 + cast(str, parent.get("/T", ""))
756 )
757 return cast(str, parent.get("/T", ""))
759 @staticmethod
760 def _normal_appearance(appearance: Any) -> DictionaryObject:
761 """Return the /N normal-appearance sub-dictionary of an /AP entry."""
762 appearance = appearance.get_object()
763 if not isinstance(appearance, DictionaryObject):
764 raise PdfReadError(f"Expected appearance dictionary, got {appearance!r}")
765 normal = appearance.get("/N")
766 if normal is not None:
767 normal = normal.get_object()
768 if not isinstance(normal, DictionaryObject):
769 raise PdfReadError(f"Expected /N appearance dictionary, got {normal!r}")
770 return normal
772 def _build_field(
773 self,
774 *,
775 field: TreeObject | DictionaryObject,
776 retval: dict[Any, Any],
777 fileobj: Any,
778 field_attributes: Any,
779 visited: set[int],
780 depth: int,
781 traversal_state: _TraversalState,
782 ) -> None:
783 if not isinstance(field, DictionaryObject):
784 logger_warning(
785 "Form field is not a dictionary: %(field)s",
786 source=__name__,
787 field=field,
788 )
789 return
790 if all(attr not in field for attr in ("/T", "/TM")):
791 return
792 key = self._get_qualified_field_name(parent=field)
793 if fileobj:
794 self._write_field(fileobj, field, field_attributes)
795 fileobj.write("\n")
796 retval[key] = Field(field)
797 obj = retval[key].indirect_reference.get_object() # to get the full object
798 if obj.get(FieldDictionaryAttributes.FT, "") == "/Ch" and obj.get(NameObject(FieldDictionaryAttributes.Opt)):
799 retval[key][NameObject("/_States_")] = obj[NameObject(FieldDictionaryAttributes.Opt)]
800 if obj.get(FieldDictionaryAttributes.FT, "") == "/Btn" and "/AP" in obj:
801 # Checkbox
802 normal = self._normal_appearance(obj["/AP"])
803 retval[key][NameObject("/_States_")] = ArrayObject(list(normal.keys()))
804 if "/Off" not in retval[key]["/_States_"]:
805 retval[key][NameObject("/_States_")].append(NameObject("/Off"))
806 elif (
807 obj.get(FieldDictionaryAttributes.FT, "") == "/Btn"
808 and obj.get(FieldDictionaryAttributes.Ff, 0) & FieldDictionaryAttributes.FfBits.Radio != 0
809 ):
810 states: list[str] = []
811 seen_states: set[str] = set()
812 # Widgets often share one /N dictionary, whose states only need to be read once.
813 seen_appearances: set[int] = set()
814 for k in obj.get(FieldDictionaryAttributes.Kids, {}):
815 k = k.get_object()
816 if "/AP" not in k:
817 raise PdfReadError(f"Button field kid missing /AP: {k!r}")
818 normal = self._normal_appearance(k["/AP"])
819 if id(normal) in seen_appearances:
820 continue
821 seen_appearances.add(id(normal))
822 for s in list(normal.keys()):
823 if s not in seen_states:
824 seen_states.add(s)
825 states.append(s)
826 retval[key][NameObject("/_States_")] = ArrayObject(states)
827 if (
828 obj.get(FieldDictionaryAttributes.Ff, 0) & FieldDictionaryAttributes.FfBits.NoToggleToOff != 0
829 and "/Off" in retval[key]["/_States_"]
830 ):
831 del retval[key]["/_States_"][retval[key]["/_States_"].index("/Off")]
832 # at last for order
833 self._check_kids(
834 tree=field, retval=retval, fileobj=fileobj, visited=visited, depth=depth, traversal_state=traversal_state
835 )
837 def _check_kids(
838 self,
839 *,
840 tree: TreeObject | DictionaryObject,
841 retval: Any,
842 fileobj: Any,
843 visited: set[int],
844 depth: int,
845 traversal_state: _TraversalState,
846 ) -> None:
847 tree_id = id(tree)
848 if tree_id in visited:
849 logger_warning(
850 "%(field_name)s already parsed",
851 source=__name__,
852 field_name=self._get_qualified_field_name(parent=tree),
853 )
854 return
855 visited.add(tree_id)
856 if PagesAttributes.KIDS in tree:
857 # recurse down the tree
858 for kid in tree[PagesAttributes.KIDS]: # type: ignore[attr-defined]
859 kid = kid.get_object()
860 self.get_fields(
861 tree=kid, retval=retval, fileobj=fileobj,
862 _visited=visited, _depth=depth + 1, _traversal_state=traversal_state
863 )
865 def _write_field(self, fileobj: Any, field: Any, field_attributes: Any) -> None:
866 field_attributes_tuple = FieldDictionaryAttributes.attributes()
867 field_attributes_tuple = (
868 field_attributes_tuple + CheckboxRadioButtonAttributes.attributes()
869 )
871 for attr in field_attributes_tuple:
872 if attr in (
873 FieldDictionaryAttributes.Kids,
874 FieldDictionaryAttributes.AA,
875 ):
876 continue
877 attr_name = field_attributes[attr]
878 try:
879 if attr == FieldDictionaryAttributes.FT:
880 # Make the field type value clearer
881 types = {
882 "/Btn": "Button",
883 "/Tx": "Text",
884 "/Ch": "Choice",
885 "/Sig": "Signature",
886 }
887 if field[attr] in types:
888 fileobj.write(f"{attr_name}: {types[field[attr]]}\n")
889 elif attr == FieldDictionaryAttributes.Parent:
890 # Let's just write the name of the parent
891 try:
892 name = field[attr][FieldDictionaryAttributes.TM]
893 except KeyError:
894 name = field[attr][FieldDictionaryAttributes.T]
895 fileobj.write(f"{attr_name}: {name}\n")
896 else:
897 fileobj.write(f"{attr_name}: {field[attr]}\n")
898 except KeyError:
899 # Field attribute is N/A or unknown, so don't write anything
900 pass
902 def get_form_text_fields(self, full_qualified_name: bool = False) -> dict[str, Any]:
903 """
904 Retrieve form fields from the document with textual data.
906 Args:
907 full_qualified_name: to get full name
909 Returns:
910 A dictionary. The key is the name of the form field,
911 the value is the content of the field.
913 If the document contains multiple form fields with the same name, the
914 second and following will get the suffix .2, .3, ...
916 """
917 # The keys as a tree of their dot-separated parts, so that numbering a duplicate
918 # name does not scan all keys collected so far.
919 dotted_names = _DottedNameNode()
921 def indexed_key(k: str, fields: dict[Any, Any]) -> str:
922 if k not in fields:
923 return k
924 return k + "." + str(get_prefix_count(k) + 2)
926 def get_prefix_count(k: str) -> int:
927 node = dotted_names
928 for part in k.split("."):
929 if part not in node.children:
930 return 0
931 node = node.children[part]
932 return node.count
934 def count_prefixes(k: Any) -> None:
935 if not isinstance(k, str):
936 return
937 node = dotted_names
938 for part in k.split(".")[:-1]:
939 node = node.children.setdefault(part, _DottedNameNode())
940 node.count += 1
942 # Retrieve document form fields
943 form_fields = self.get_fields()
944 if form_fields is None:
945 return {}
946 ff = {}
947 for field, value in form_fields.items():
948 if value.get("/FT") == "/Tx":
949 if full_qualified_name:
950 ff[field] = value.get("/V")
951 else:
952 key = indexed_key(cast(str, value.get("/T", field)), ff)
953 if key not in ff:
954 count_prefixes(key)
955 ff[key] = value.get("/V")
956 return ff
958 def get_pages_showing_field(
959 self, field: Field | PdfObject | IndirectObject
960 ) -> list[PageObject]:
961 """
962 Provides list of pages where the field is called.
964 Args:
965 field: Field Object, PdfObject or IndirectObject referencing a Field
967 Returns:
968 List of pages:
969 - Empty list:
970 The field has no widgets attached
971 (either hidden field or ancestor field).
972 - Single page list:
973 Page where the widget is present
974 (most common).
975 - Multi-page list:
976 Field with multiple kids widgets
977 (example: radio buttons, field repeated on multiple pages).
979 """
980 try:
981 # to cope with all types
982 field = cast(DictionaryObject, field.indirect_reference.get_object()) # type: ignore[union-attr]
983 except Exception as exc:
984 raise ValueError("Field type is invalid") from exc
985 if is_null_or_none(field.get_inherited(key="/FT", default=None)):
986 raise ValueError("Field is not valid")
987 ret = []
988 if field.get("/Subtype", "") == "/Widget":
989 if "/P" in field:
990 ret = [field["/P"].get_object()]
991 else:
992 ret = [
993 p
994 for p in self.pages
995 if field.indirect_reference in p.get("/Annots", "")
996 ]
997 else:
998 kids = field.get("/Kids", ())
999 for k in kids:
1000 k = k.get_object()
1001 if (k.get("/Subtype", "") == "/Widget") and ("/T" not in k):
1002 # Kid that is just a widget, not a field:
1003 if "/P" in k:
1004 ret += [k["/P"].get_object()]
1005 else:
1006 ret += [
1007 p
1008 for p in self.pages
1009 if k.indirect_reference in p.get("/Annots", "")
1010 ]
1011 return [
1012 x
1013 if isinstance(x, PageObject)
1014 else (self.pages[self._get_page_number_by_indirect(x.indirect_reference)]) # type: ignore[index, union-attr]
1015 for x in ret
1016 ]
1018 @property
1019 def open_destination(
1020 self,
1021 ) -> Destination | TextStringObject | ByteStringObject | None:
1022 """
1023 Property to access the opening destination (``/OpenAction`` entry in
1024 the PDF catalog). It returns ``None`` if the entry does not exist
1025 or is not set.
1027 Raises:
1028 Exception: If a destination is invalid.
1030 """
1031 if "/OpenAction" not in self.root_object:
1032 return None
1033 oa: Any = self.root_object["/OpenAction"]
1034 if isinstance(oa, bytes): # pragma: no cover
1035 oa = oa.decode()
1036 if isinstance(oa, str):
1037 return create_string_object(oa)
1038 if isinstance(oa, ArrayObject):
1039 try:
1040 page, typ, *array = oa
1041 fit = Fit(typ, tuple(array))
1042 return Destination("OpenAction", page, fit)
1043 except Exception as exc:
1044 raise Exception(f"Invalid Destination {oa}: {exc}") from exc
1045 else:
1046 return None
1048 @open_destination.setter
1049 def open_destination(self, dest: str | Destination | PageObject | None) -> None:
1050 raise NotImplementedError("No setter for open_destination")
1052 @property
1053 def outline(self) -> OutlineType:
1054 """
1055 Read-only property for the outline present in the document
1056 (i.e., a collection of 'outline items' which are also known as
1057 'bookmarks').
1058 """
1059 return self._get_outline()
1061 def _get_outline(
1062 self,
1063 *,
1064 node: DictionaryObject | None = None,
1065 outline: Any | None = None,
1066 visited: set[int] | None = None,
1067 depth: int = 0,
1068 traversal_state: _TraversalState | None = None
1069 ) -> OutlineType:
1070 if traversal_state is None:
1071 traversal_state = _TraversalState()
1073 if outline is None:
1074 outline = []
1075 catalog = self.root_object
1077 # get the outline dictionary and named destinations
1078 if Core.OUTLINES in catalog:
1079 lines = catalog[Core.OUTLINES]
1081 # A reference to an object which is missing or free in the xref table
1082 # resolves to None.
1083 if is_null_or_none(lines):
1084 return outline
1086 if not isinstance(lines, DictionaryObject):
1087 logger_warning(
1088 "Outlines are not a dictionary: %(lines)s",
1089 source=__name__,
1090 lines=lines,
1091 )
1092 return outline
1094 # §12.3.3 Document outline, entries in the outline dictionary
1095 if "/First" in lines:
1096 node = cast(DictionaryObject, lines["/First"])
1097 self._named_destinations = self._get_named_destinations()
1099 if node is None:
1100 return outline
1102 configuration = get_configuration()
1103 if depth > configuration.outline_maximum_depth:
1104 raise LimitReachedError(f"Maximum outline depth reached: {depth} > {configuration.outline_maximum_depth}.")
1106 # see if there are any more outline items
1107 if visited is None:
1108 visited = set()
1109 added: set[int] = set()
1110 while True:
1111 node_id = id(node)
1112 if node_id in visited:
1113 logger_warning("Detected cycle in outline structure for %(node)s", source=__name__, node=node)
1114 break
1115 visited.add(node_id)
1116 added.add(node_id)
1117 traversal_state.entry_count += 1
1118 if traversal_state.entry_count > configuration.outline_maximum_entries:
1119 raise LimitReachedError(
1120 f"Maximum outline entry limit reached: "
1121 f"{traversal_state.entry_count} > {configuration.outline_maximum_entries}."
1122 )
1124 if not isinstance(node, DictionaryObject):
1125 logger_warning(
1126 "Outline node is not a dictionary: %(node)s",
1127 source=__name__,
1128 node=node,
1129 )
1130 break
1132 outline_obj = self._build_outline_item(node)
1133 if outline_obj:
1134 outline.append(outline_obj)
1136 # check for sub-outline
1137 if "/First" in node:
1138 sub_outline: list[Any] = []
1139 # The inner call forgets its entries on return to allow multiple
1140 # outer entries to reference the same inner one.
1141 self._get_outline(
1142 node=cast(DictionaryObject, node["/First"]),
1143 outline=sub_outline,
1144 visited=visited,
1145 depth=depth + 1,
1146 traversal_state=traversal_state,
1147 )
1148 if sub_outline:
1149 outline.append(sub_outline)
1151 if "/Next" not in node:
1152 break
1153 node = cast(DictionaryObject, node["/Next"])
1155 visited.difference_update(added)
1156 return outline
1158 @property
1159 def threads(self) -> ArrayObject | None:
1160 """
1161 Read-only property for the list of threads.
1163 See §12.4.3 from the PDF 1.7 or 2.0 specification.
1165 It is an array of dictionaries with "/F" (the first bead in the thread)
1166 and "/I" (a thread information dictionary containing information about
1167 the thread, such as its title, author, and creation date) properties or
1168 None if there are no articles.
1170 Since PDF 2.0 it can also contain an indirect reference to a metadata
1171 stream containing information about the thread, such as its title,
1172 author, and creation date.
1173 """
1174 catalog = self.root_object
1175 if Core.THREADS in catalog:
1176 return cast("ArrayObject", catalog[Core.THREADS])
1177 return None
1179 @abstractmethod
1180 def _get_page_number_by_indirect(
1181 self, indirect_reference: int | NullObject | IndirectObject | None
1182 ) -> int | None:
1183 ... # pragma: no cover
1185 def get_page_number(self, page: PageObject) -> int | None:
1186 """
1187 Retrieve page number of a given PageObject.
1189 Args:
1190 page: The page to get page number. Should be
1191 an instance of :class:`PageObject<pypdf._page.PageObject>`
1193 Returns:
1194 The page number or None if page is not found
1196 """
1197 return self._get_page_number_by_indirect(page.indirect_reference)
1199 def get_destination_page_number(self, destination: Destination) -> int | None:
1200 """
1201 Retrieve page number of a given Destination object.
1203 Args:
1204 destination: The destination to get page number.
1206 Returns:
1207 The page number or None if page is not found
1209 """
1210 return self._get_page_number_by_indirect(destination.page)
1212 def _build_destination(
1213 self,
1214 title: str | bytes,
1215 array: ArrayObject | None,
1216 ) -> Destination:
1217 page, typ = None, None
1218 # A valid destination is an array of at least a page and a fit type.
1219 # Anything else (a name, a bare number, a NullObject, None, ...) cannot
1220 # be unpacked below, so treat it as a missing destination.
1221 if not isinstance(array, ArrayObject) or len(array) < 2:
1222 page = NullObject()
1223 return Destination(title, page, Fit.fit())
1224 page, typ, *fit_args = array
1225 try:
1226 return Destination(title, page, Fit(fit_type=typ, fit_args=fit_args))
1227 except PdfReadError:
1228 logger_warning(
1229 "Unknown destination: %(title)r %(fit_args)s",
1230 source=__name__,
1231 title=title,
1232 fit_args=fit_args,
1233 )
1234 if self.strict:
1235 raise
1236 # create a link to the first page if the document has one,
1237 # and to a null target otherwise
1238 if self.pages:
1239 tmp = self.pages[0].indirect_reference
1240 else:
1241 tmp = None
1242 indirect_reference = NullObject() if tmp is None else tmp
1243 return Destination(title, indirect_reference, Fit.fit())
1245 def _build_outline_item(self, node: DictionaryObject) -> Destination | None:
1246 dest, title, outline_item = None, None, None
1248 # title required for valid outline
1249 # §12.3.3, entries in an outline item dictionary
1250 if "/Title" in node:
1251 title = cast("str", node["/Title"])
1252 else:
1253 if self.strict:
1254 raise PdfReadError(f"Outline Entry Missing /Title attribute: {node!r}")
1255 title = ""
1257 if "/A" in node:
1258 # Action, PDF 1.7 and PDF 2.0 §12.6 (only type GoTo supported)
1259 action = cast(DictionaryObject, node["/A"])
1260 if GoToActionArguments.S in action:
1261 action_type = cast(NameObject, action[GoToActionArguments.S])
1262 if action_type == "/GoTo":
1263 if GoToActionArguments.D in action:
1264 dest = action[GoToActionArguments.D]
1265 elif self.strict:
1266 raise PdfReadError(f"Outline Action Missing /D attribute: {node!r}")
1267 elif self.strict:
1268 raise PdfReadError(f"Outline Action Missing /S attribute: {node!r}")
1269 elif "/Dest" in node:
1270 # Destination, PDF 1.7 and PDF 2.0 §12.3.2
1271 dest = node["/Dest"]
1272 # if array was referenced in another object, will be a dict w/ key "/D"
1273 if isinstance(dest, DictionaryObject) and "/D" in dest:
1274 dest = dest["/D"]
1276 if isinstance(dest, ArrayObject):
1277 outline_item = self._build_destination(title, dest)
1278 elif isinstance(dest, str):
1279 # named destination, addresses NameObject Issue #193
1280 # TODO: Keep named destination instead of replacing it?
1281 try:
1282 outline_item = self._build_destination(
1283 title, self._named_destinations[dest].dest_array
1284 )
1285 except KeyError:
1286 # named destination not found in Name Dict
1287 outline_item = self._build_destination(title, None)
1288 elif dest is None:
1289 # outline item not required to have destination or action
1290 # PDFv1.7 Table 153
1291 outline_item = self._build_destination(title, dest)
1292 else:
1293 if self.strict:
1294 raise PdfReadError(f"Unexpected destination {dest!r}")
1295 logger_warning(
1296 "Removed unexpected destination %(dest)r from destination",
1297 source=__name__,
1298 dest=dest,
1299 )
1300 outline_item = self._build_destination(title, None)
1302 # if outline item created, add color, format, and child count if present
1303 if outline_item:
1304 if "/C" in node:
1305 # Color of outline item font in (R, G, B) with values ranging 0.0-1.0
1306 color = node["/C"]
1307 if isinstance(color, list):
1308 outline_item[NameObject("/C")] = ArrayObject(FloatObject(c) for c in color)
1309 else:
1310 logger_warning(
1311 "Ignoring non-array outline color %(color)r",
1312 source=__name__,
1313 color=color,
1314 )
1315 if "/F" in node:
1316 # specifies style characteristics bold and/or italic
1317 # with 1=italic, 2=bold, 3=both
1318 outline_item[NameObject("/F")] = node["/F"]
1319 if "/Count" in node:
1320 # absolute value = num. visible children
1321 # with positive = open/unfolded, negative = closed/folded
1322 outline_item[NameObject("/Count")] = node["/Count"]
1323 # if count is 0 we will consider it as open (to have available is_open)
1324 outline_item[NameObject("/%is_open%")] = BooleanObject(
1325 node.get("/Count", 0) >= 0
1326 )
1327 outline_item.node = node
1328 with contextlib.suppress(AttributeError):
1329 outline_item.indirect_reference = node.indirect_reference
1330 return outline_item
1332 @property
1333 def pages(self) -> Sequence[PageObject]:
1334 """
1335 Property that emulates a list of :class:`PageObject<pypdf._page.PageObject>`.
1336 This property allows to get a page or a range of pages.
1338 The returned object supports indexing, slicing, ``len()``, iteration and
1339 (for PdfWriter) ``del``, but it is not a :class:`list` - pages are looked
1340 up on demand rather than materialized up front, so list-only operations
1341 such as ``append()`` or concatenation with ``+`` are not available.
1343 Note:
1344 For PdfWriter only: Provides the capability to remove a page/range of
1345 page from the list (using the del operator). Remember: Only the page
1346 entry is removed, as the objects beneath can be used elsewhere. A
1347 solution to completely remove them - if they are not used anywhere - is
1348 to write to a buffer/temporary file and then load it into a new
1349 PdfWriter.
1351 """
1352 return _VirtualList(self.get_num_pages, self.get_page)
1354 @property
1355 def page_labels(self) -> list[str]:
1356 """
1357 A list of labels for the pages in this document.
1359 This property is read-only. The labels are in the order that the pages
1360 appear in the document.
1361 """
1362 return index2labels(self, len(self.pages))
1364 @property
1365 def page_layout(self) -> str | None:
1366 """
1367 Get the page layout currently being used.
1369 .. list-table:: Valid ``layout`` values
1370 :widths: 50 200
1372 * - /NoLayout
1373 - Layout explicitly not specified
1374 * - /SinglePage
1375 - Show one page at a time
1376 * - /OneColumn
1377 - Show one column at a time
1378 * - /TwoColumnLeft
1379 - Show pages in two columns, odd-numbered pages on the left
1380 * - /TwoColumnRight
1381 - Show pages in two columns, odd-numbered pages on the right
1382 * - /TwoPageLeft
1383 - Show two pages at a time, odd-numbered pages on the left
1384 * - /TwoPageRight
1385 - Show two pages at a time, odd-numbered pages on the right
1386 """
1387 try:
1388 return cast(NameObject, self.root_object[CatalogAttributes.PAGE_LAYOUT])
1389 except KeyError:
1390 return None
1392 @property
1393 def page_mode(self) -> PagemodeType | None:
1394 """
1395 Get the page mode currently being used.
1397 .. list-table:: Valid ``mode`` values
1398 :widths: 50 200
1400 * - /UseNone
1401 - Do not show outline or thumbnails panels
1402 * - /UseOutlines
1403 - Show outline (aka bookmarks) panel
1404 * - /UseThumbs
1405 - Show page thumbnails panel
1406 * - /FullScreen
1407 - Fullscreen view
1408 * - /UseOC
1409 - Show Optional Content Group (OCG) panel
1410 * - /UseAttachments
1411 - Show attachments panel
1412 """
1413 try:
1414 return self.root_object[CatalogAttributes.PAGE_MODE] # type: ignore[return-value]
1415 except KeyError:
1416 return None
1418 def _flatten(self, list_only: bool = False) -> None:
1419 """
1420 Process the document pages to ease searching.
1422 Attributes of a page may inherit from ancestor nodes
1423 in the page tree. Flattening means moving
1424 any inheritance data into descendant nodes,
1425 effectively removing the inheritance dependency.
1426 The result is stored in ``self.flattened_pages``.
1428 Note: It is distinct from another use of "flattening" applied to PDFs.
1429 Flattening a PDF also means combining all the contents into one single layer
1430 and making the file less editable.
1432 The page tree is walked with an explicit stack instead of recursion, so the
1433 traversal is bound by ``Configuration.page_tree_maximum_depth`` and
1434 ``Configuration.page_tree_maximum_entries`` only, not by the interpreter
1435 recursion limit.
1437 Args:
1438 list_only: If True, the page's own entries are not copied into the
1439 generated :class:`PageObject`. Attributes inherited from ancestor
1440 nodes are applied either way. Note that a page reached through an
1441 indirect reference is already populated by :class:`PageObject`
1442 itself, so this only has an effect for ``/Kids`` entries that are
1443 inline dictionaries.
1445 """
1446 configuration = get_configuration()
1447 self.flattened_pages = None
1448 pages = self.root_object.get("/Pages", NullObject()).get_object()
1449 if not isinstance(pages, DictionaryObject):
1450 raise PdfReadError("Invalid object in /Pages")
1452 flattened_pages: list[PageObject] = []
1453 traversal_state = _TraversalState()
1454 remaining_page_entries = _TraversalState(entry_count=configuration.page_tree_maximum_page_entries)
1455 # id() values of the nodes on the path from the root to the current node.
1456 # Detects multi-hop cycles such as A→B→C→A that the single-parent check misses.
1457 ancestor_ids: set[int] = set()
1458 # The /Pages nodes of that path whose /Kids are not exhausted yet.
1459 stack: list[_PageTreeFrame] = []
1460 item: _PageTreeItem | None = _PageTreeItem(
1461 node=pages, inherit={}, indirect_reference=None, depth=0
1462 )
1463 while item is not None:
1464 if item.depth > configuration.page_tree_maximum_depth:
1465 raise LimitReachedError(
1466 f"Maximum page tree depth reached: {item.depth} > {configuration.page_tree_maximum_depth}."
1467 )
1469 # Get the current node_type
1470 node = item.node
1471 if PagesAttributes.TYPE in node:
1472 node_type = cast(str, node[PagesAttributes.TYPE])
1473 # if the page tree node has no /Type, consider as a page if /Kids is also missing
1474 elif PagesAttributes.KIDS not in node:
1475 # Without /Type, only accept it as a page if it carries a structural page key.
1476 if self.strict and not any(
1477 key in node for key in (PageAttributes.CONTENTS, PageAttributes.MEDIABOX, PageAttributes.PARENT)
1478 ):
1479 raise PdfReadError(f"Non-page object reached through /Kids: {node!r}")
1480 node_type = "/Page"
1481 else:
1482 node_type = "/Pages"
1484 # Flatten that type of node
1485 if node_type == "/Pages":
1486 ancestor_ids.add(id(node))
1487 stack.append(self._enter_page_tree_node(item))
1488 elif node_type == "/Page":
1489 flattened_pages.append(
1490 self._flatten_leaf_page(
1491 item=item, list_only=list_only, remaining_page_entries=remaining_page_entries
1492 )
1493 )
1495 item = self._pop_next_page_tree_kid(stack, ancestor_ids, traversal_state)
1497 # Assigned only here, so that a failed traversal does not leave a partial page list behind.
1498 self.flattened_pages = flattened_pages
1500 def _enter_page_tree_node(self, item: _PageTreeItem) -> _PageTreeFrame:
1501 """
1502 Start walking an intermediate ``/Pages`` node: propagate its inheritable
1503 attributes and pair it with an iterator over its ``/Kids``.
1504 """
1505 pages = item.node
1506 # Copied before being modified, as the kids of the enclosing node share it.
1507 inherit = dict(item.inherit)
1508 for attr in _INHERITABLE_PAGE_ATTRIBUTES:
1509 if attr in pages:
1510 inherit[attr] = pages[attr]
1512 kids = pages.get(PagesAttributes.KIDS, ArrayObject()).get_object()
1513 if isinstance(kids, NullObject):
1514 kids = ArrayObject()
1515 elif not isinstance(kids, ArrayObject):
1516 raise PdfReadError(f"Expected /Kids to be an array, got {type(kids).__name__}.")
1518 return item._replace(inherit=inherit), iter(kids)
1520 def _pop_next_page_tree_kid(
1521 self,
1522 stack: list[_PageTreeFrame],
1523 ancestor_ids: set[int],
1524 traversal_state: _TraversalState,
1525 ) -> _PageTreeItem | None:
1526 """
1527 Return the next page tree node to flatten, leaving the ``/Pages`` nodes whose
1528 ``/Kids`` are exhausted, or ``None`` when the traversal is complete.
1530 Cyclic references and the configured page-tree entry limit are enforced here.
1531 """
1532 configuration = get_configuration()
1533 while stack:
1534 parent, kids = stack[-1]
1535 pages_reference = getattr(parent.node, "indirect_reference", object())
1536 for page in kids:
1537 if getattr(page, "indirect_reference", object()) == pages_reference:
1538 raise PdfReadError("Detected cyclic page references.")
1540 obj = page.get_object()
1541 if not isinstance(obj, DictionaryObject):
1542 if not is_null_or_none(obj):
1543 logger_warning(
1544 "Ignoring page tree entry that is not a dictionary: %(entry)s",
1545 source=__name__,
1546 entry=obj,
1547 )
1548 # damaged file may have invalid child in /Pages
1549 continue
1550 if not obj:
1551 # An empty dictionary would otherwise be read as a blank page.
1552 continue
1553 if id(obj) in ancestor_ids:
1554 raise PdfReadError("Detected cyclic page references.")
1555 traversal_state.entry_count += 1
1556 if traversal_state.entry_count > configuration.page_tree_maximum_entries:
1557 raise LimitReachedError(
1558 "Maximum page tree entry limit reached: "
1559 f"{traversal_state.entry_count} > {configuration.page_tree_maximum_entries}."
1560 )
1561 return _PageTreeItem(
1562 node=obj,
1563 inherit=parent.inherit,
1564 indirect_reference=page if isinstance(page, IndirectObject) else None,
1565 depth=parent.depth + 1,
1566 )
1567 stack.pop()
1568 ancestor_ids.discard(id(parent.node))
1569 return None
1571 def _flatten_leaf_page(
1572 self, *, item: _PageTreeItem, list_only: bool, remaining_page_entries: _TraversalState
1573 ) -> PageObject:
1574 """
1575 Build the :class:`PageObject` for a leaf ``/Page`` node.
1577 ``list_only`` suppresses copying the page's own entries; the inherited
1578 attributes are applied regardless. When the node has an indirect reference,
1579 :class:`PageObject` has already copied those entries in its constructor,
1580 so the flag only matters for inline ``/Kids`` dictionaries.
1581 """
1582 node = item.node
1584 # Indirect PageObjects are populated by the constructor even when
1585 # list_only=True. Inline dictionaries are copied only when list_only=False.
1586 entry_count = (
1587 len(node)
1588 if item.indirect_reference is not None or not list_only
1589 else 0
1590 )
1592 # Inherited attributes are inserted only when missing from the page.
1593 entry_count += sum(
1594 attribute not in node for attribute in item.inherit
1595 )
1597 remaining_page_entries.entry_count -= entry_count
1598 if remaining_page_entries.entry_count < 0:
1599 raise LimitReachedError("Maximum page tree page entry limit exceeded!")
1601 page = PageObject(self, item.indirect_reference)
1602 if not list_only:
1603 page.update(node)
1604 for attribute, value in item.inherit.items():
1605 # If the page has its own value, it does not inherit the parent's value.
1606 if attribute not in page:
1607 page[attribute] = value
1609 return page
1611 def remove_page(
1612 self,
1613 page: int | PageObject | IndirectObject,
1614 clean: bool = False,
1615 ) -> None:
1616 """
1617 Remove page from pages list.
1619 Args:
1620 page:
1621 * :class:`int`: Page number to be removed.
1622 * :class:`~pypdf._page.PageObject`: page to be removed. If the page appears many times
1623 only the first one will be removed.
1624 * :class:`~pypdf.generic.IndirectObject`: Reference to page to be removed.
1626 clean: replace PageObject with NullObject to prevent annotations
1627 or destinations to reference a detached page.
1629 """
1630 if self.flattened_pages is None:
1631 self._flatten(self._readonly)
1632 assert self.flattened_pages is not None
1633 if isinstance(page, IndirectObject):
1634 p = page.get_object()
1635 if not isinstance(p, PageObject):
1636 logger_warning("IndirectObject is not referencing a page", source=__name__)
1637 return
1638 page = p
1640 if not isinstance(page, int):
1641 try:
1642 page = self.flattened_pages.index(page)
1643 except ValueError:
1644 logger_warning("Cannot find page in pages", source=__name__)
1645 return
1646 if not (0 <= page < len(self.flattened_pages)):
1647 logger_warning("Page number is out of range", source=__name__)
1648 return
1650 ind = self.pages[page].indirect_reference
1651 # `pages` is typed as a Sequence because it is not a list, but the
1652 # concrete _VirtualList does implement deletion.
1653 del cast(_VirtualList, self.pages)[page]
1654 if clean and ind is not None:
1655 self._replace_object(ind, NullObject())
1657 def _get_indirect_object(self, num: int, gen: int) -> PdfObject | None:
1658 """
1659 Used to ease development.
1661 This is equivalent to generic.IndirectObject(num,gen,self).get_object()
1663 Args:
1664 num: The object number of the indirect object.
1665 gen: The generation number of the indirect object.
1667 Returns:
1668 A PdfObject
1670 """
1671 return IndirectObject(num, gen, self).get_object()
1673 @property
1674 def user_access_permissions(self) -> UserAccessPermissions | None:
1675 """
1676 Get the user access permissions for encrypted documents.
1677 Returns None if not encrypted.
1679 .. warning::
1681 For AES-256 encrypted documents (R=5/R=6), the returned
1682 permissions are derived from the ``/P`` field, which is
1683 only trustworthy if the ``/Perms`` integrity check passed.
1684 Check :attr:`are_permissions_valid` to verify.
1685 """
1686 if self._encryption is None:
1687 return None
1688 return UserAccessPermissions(self._encryption.permissions)
1690 @property
1691 def are_permissions_valid(self) -> bool | None:
1692 """
1693 Whether the ``/Perms`` integrity check passed for this document.
1695 For AES-256 encrypted documents (R=5/R=6), the ``/Perms`` field
1696 is an encrypted copy of the permissions that can be verified
1697 independently. Returns ``False`` if this check fails (the ``/P``
1698 permissions may have been tampered with).
1700 Returns ``None`` if the document is not encrypted or has not yet
1701 been decrypted via :meth:`decrypt()<pypdf.PdfReader.decrypt>`.
1702 Returns ``True`` for non-AES-256 encryption (no ``/Perms`` to check).
1703 """
1704 if self._encryption is None:
1705 return None
1706 if not self._encryption.is_decrypted():
1707 return None
1708 return self._encryption._are_permissions_valid
1710 @property
1711 @abstractmethod
1712 def is_encrypted(self) -> bool:
1713 """
1714 Read-only boolean property showing whether this PDF file is encrypted.
1716 Note that this property, if true, will remain true even after the
1717 :meth:`decrypt()<pypdf.PdfReader.decrypt>` method is called.
1718 """
1719 ... # pragma: no cover
1721 @property
1722 def xfa(self) -> dict[str, bytes] | None:
1724 catalog = self.root_object
1726 if "/AcroForm" not in catalog or not catalog["/AcroForm"]:
1727 return None
1729 tree = cast(TreeObject, catalog["/AcroForm"])
1730 retval: dict[str, bytes] = {}
1732 if "/XFA" not in tree:
1733 return retval
1735 fields = tree["/XFA"].get_object()
1736 if not isinstance(fields, ArrayObject):
1737 logger_warning(
1738 "XFA entry is not an array: %(fields)s",
1739 source=__name__,
1740 fields=fields,
1741 )
1742 return retval
1744 accumulated_length = 0
1745 decoding_work_maximum_length = get_configuration().xfa_decoding_work_maximum_length
1747 field_iterator = iter(fields)
1748 for field in field_iterator:
1749 tag = field
1750 field = next(field_iterator, None)
1751 if is_null_or_none(field):
1752 continue
1753 assert field is not None, "mypy"
1755 field = cast(StreamObject | None, field.get_object())
1756 if is_null_or_none(field):
1757 continue
1758 assert field is not None, "mypy"
1760 decoded_data = field.get_data()
1761 accumulated_length += len(decoded_data)
1763 if accumulated_length > decoding_work_maximum_length:
1764 raise LimitReachedError(
1765 "XFA decoding exceeded the maximum accumulated "
1766 f"decoding work of {decoding_work_maximum_length} bytes."
1767 )
1769 retval[tag] = decoded_data
1770 return retval
1772 @property
1773 def attachments(self) -> Mapping[str, list[bytes]]:
1774 """Mapping of attachment filenames to their content."""
1775 entries: dict[str, list[EmbeddedFile]] = {}
1777 for entry in self.attachment_list:
1778 for name in entry._names:
1779 entries.setdefault(name, []).append(entry)
1781 configuration = get_configuration()
1782 traversal_state = _TraversalState(entry_count=configuration.embedded_files_maximum_output_length)
1784 return LazyDict(
1785 {
1786 name: (self._get_attachment_contents, attachment_entries, traversal_state)
1787 for name, attachment_entries in entries.items()
1788 }
1789 )
1791 @classmethod
1792 def _get_attachment_contents(cls, entries: list[EmbeddedFile], traversal_state: _TraversalState) -> list[bytes]:
1793 return [entry._get_content(traversal_state=traversal_state) for entry in entries]
1795 @property
1796 def attachment_list(self) -> Iterator[EmbeddedFile]:
1797 """Iterable of attachment objects."""
1798 yield from EmbeddedFile._load(self.root_object, strict=self.strict)
1800 @abstractmethod
1801 def _get_pdf_bytes(self) -> bytes:
1802 """Return the document as the bytes of a PDF file."""
1803 ... # pragma: no cover
1805 def _repr_mimebundle_(
1806 self,
1807 include: Iterable[str] | None = None,
1808 exclude: Iterable[str] | None = None,
1809 ) -> dict[str, Any]:
1810 """
1811 Integration into Jupyter Notebooks.
1813 This method returns a dictionary that maps a mime-type to its
1814 representation.
1816 .. seealso::
1818 https://ipython.readthedocs.io/en/stable/config/integrating.html
1819 """
1820 data: dict[str, Any] = {"application/pdf": self._get_pdf_bytes()}
1822 if include is not None:
1823 # Filter representations based on include list
1824 data = {k: v for k, v in data.items() if k in include}
1826 if exclude is not None:
1827 # Remove representations based on exclude list
1828 data = {k: v for k, v in data.items() if k not in exclude}
1830 return data
1833class LazyDict(Mapping[Any, Any]):
1834 def __init__(self, *args: Any, **kwargs: Any) -> None:
1835 self._raw_dict = dict(*args, **kwargs)
1837 def __getitem__(self, key: str) -> Any:
1838 func, *arg = self._raw_dict.__getitem__(key)
1839 return func(*arg)
1841 def __iter__(self) -> Iterator[Any]:
1842 return iter(self._raw_dict)
1844 def __len__(self) -> int:
1845 return len(self._raw_dict)
1847 def __str__(self) -> str:
1848 return f"LazyDict(keys={list(self.keys())})"