Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/pypdf/_writer.py: 20%
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#
4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without
7# modification, are permitted provided that the following conditions are
8# met:
9#
10# * Redistributions of source code must retain the above copyright notice,
11# this list of conditions and the following disclaimer.
12# * Redistributions in binary form must reproduce the above copyright notice,
13# this list of conditions and the following disclaimer in the documentation
14# and/or other materials provided with the distribution.
15# * The name of the author may not be used to endorse or promote products
16# derived from this software without specific prior written permission.
17#
18# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
22# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28# POSSIBILITY OF SUCH DAMAGE.
30import contextlib
31import decimal
32import enum
33import re
34import secrets
35import struct
36import sys
37from collections.abc import Callable, Iterable, Mapping, Sequence
38from io import BytesIO, FileIO, IOBase
39from itertools import pairwise
40from pathlib import Path
41from re import Pattern
42from types import TracebackType
43from typing import (
44 IO,
45 Any,
46 Literal,
47 NoReturn,
48 cast,
49)
51if sys.version_info >= (3, 11):
52 from typing import Self
53else:
54 from typing_extensions import Self
56from ._configuration import get_configuration
57from ._doc_common import DocumentInformation, PdfDocCommon
58from ._encryption import EncryptAlgorithm, Encryption
59from ._page import PageObject, Transformation
60from ._page_labels import nums_clear_range, nums_insert, nums_next
61from ._reader import PdfReader
62from ._utils import (
63 StrByteType,
64 StreamType,
65 _get_max_pdf_version_header,
66 deprecate_positional_arguments,
67 deprecate_with_replacement,
68 deprecation_with_replacement,
69 logger_warning,
70)
71from .actions import Action
72from .constants import (
73 AnnotationDictionaryAttributes,
74 CatalogAttributes,
75 Core,
76 FieldDictionaryAttributes,
77 GoToActionArguments,
78 ImageType,
79 InteractiveFormDictEntries,
80 OutlineFontFlag,
81 PageAttributes,
82 PageLabelStyle,
83 PagesAttributes,
84 TrailerKeys,
85 UserAccessPermissions,
86)
87from .errors import LimitReachedError, PdfReadError, PyPdfError
88from .generic import (
89 PAGE_FIT,
90 ArrayObject,
91 BooleanObject,
92 ByteStringObject,
93 ContentStream,
94 Destination,
95 DictionaryObject,
96 EmbeddedFile,
97 Fit,
98 FloatObject,
99 IndirectObject,
100 NamedReferenceLink,
101 NameObject,
102 NullObject,
103 NumberObject,
104 PdfObject,
105 RectangleObject,
106 ReferenceLink,
107 StreamObject,
108 TextStringObject,
109 TreeObject,
110 ViewerPreferences,
111 create_string_object,
112 extract_links,
113 hex_to_rgb,
114 is_null_or_none,
115)
116from .generic._appearance_stream import TextStreamAppearance
117from .pagerange import PageRange, PageRangeSpec
118from .types import (
119 AnnotationSubtype,
120 BorderArrayType,
121 LayoutType,
122 OutlineItemType,
123 OutlineType,
124 PagemodeType,
125)
126from .xmp import XmpInformation
128ALL_DOCUMENT_PERMISSIONS = UserAccessPermissions.all()
131class ObjectDeletionFlag(enum.IntFlag):
132 NONE = 0
133 TEXT = enum.auto()
134 LINKS = enum.auto()
135 ATTACHMENTS = enum.auto()
136 OBJECTS_3D = enum.auto()
137 ALL_ANNOTATIONS = enum.auto()
138 XOBJECT_IMAGES = enum.auto()
139 INLINE_IMAGES = enum.auto()
140 DRAWING_IMAGES = enum.auto()
141 IMAGES = XOBJECT_IMAGES | INLINE_IMAGES | DRAWING_IMAGES
144_TEXT_SHOWING_OPERATORS = (b"Tj", b"TJ", b"'", b'"')
147# Building the index reads the whole /Names array, which costs more than it saves
148# when a document adds only a few named destinations.
149_NAMED_DESTINATION_INDEX_MINIMUM = 32
152class _NamedDestinationIndex:
153 """
154 Look up and insert named destinations in a ``/Names`` array without scanning it.
156 ``PdfWriter.merge`` adds the named destinations of a document one by one, and both
157 looking each one up in the growing array and inserting it there take quadratic time.
158 The string entries are kept in a set instead, as only strings compare equal to a title.
159 If the keys are sorted strings, the new destinations are collected and sorted into the
160 array once by ``flush``: inserting each one before the first greater key gives the same
161 order as this stable sort. Other arrays are scanned as before.
162 """
164 def __init__(self, *, is_enabled: bool) -> None:
165 self._is_enabled = is_enabled
166 self._names: list[Any] | None = None
167 self._length = 0
168 self._strings: set[str] = set()
169 self._is_sorted = False
170 self._pending: list[tuple[str, Any]] = []
172 def _update(self, names: list[Any]) -> None:
173 if names is self._names and len(names) == self._length:
174 return
175 self.flush()
176 self._names = names
177 self._length = len(names)
178 self._strings = {entry for entry in names if isinstance(entry, str)}
179 keys = names[::2]
180 self._is_sorted = (
181 self._length % 2 == 0
182 and all(isinstance(key, str) for key in keys)
183 and all(previous <= key for previous, key in pairwise(keys))
184 )
186 def contains(self, container: Any, title: Any) -> bool:
187 if isinstance(container, IndirectObject):
188 container = container.get_object()
189 if not self._is_enabled or not isinstance(container, list) or not isinstance(title, str):
190 return title in container
191 self._update(container)
192 return title in self._strings
194 def insert(self, names: list[Any], title: Any, destination: Any) -> bool:
195 """Insert like ``PdfWriter.add_named_destination_array``; return False if the array has to be scanned."""
196 if not self._is_enabled:
197 return False
198 self._update(names)
199 if not self._is_sorted or not isinstance(title, str):
200 self.flush()
201 return False
202 self._pending.append((title, destination))
203 self._strings.add(title)
204 return True
206 def record_insertion(self, names: list[Any], title: Any) -> None:
207 """Update the index after ``add_named_destination_array`` inserted ``title`` into ``names``."""
208 if names is self._names and isinstance(title, str):
209 self._strings.add(title)
210 self._length = len(names)
212 def flush(self) -> None:
213 if not self._pending:
214 return
215 names = self._names
216 assert names is not None, "mypy"
217 pairs = [(names[i], names[i + 1]) for i in range(0, len(names), 2)]
218 pairs += [(TextStringObject(title), destination) for title, destination in self._pending]
219 pairs.sort(key=lambda pair: pair[0])
220 names[:] = [entry for pair in pairs for entry in pair]
221 self._pending = []
222 self._length = len(names)
225class _RootPagePrefix:
226 """
227 Track how many of the first kids of the root ``/Pages`` node are pages, each of them once.
229 For a page number below that count, the tree walk in ``PdfDocCommon._get_page_in_node``
230 stops at the root's kid with the same index, so ``PdfWriter`` can skip it. The kids are
231 checked only as far as needed and only once while the same ``/Kids`` array keeps its
232 length. ``PdfWriter._add_page`` reports the pages it inserts; any other change to the
233 length of the array makes the next lookup check the kids again.
234 """
236 def __init__(self) -> None:
237 self._kids: ArrayObject | None = None
238 self._length = 0
239 self._page_numbers: set[int] = set()
240 self._has_other_kid = False
242 def reset(self) -> None:
243 self._kids = None
245 def _update(self, kids: ArrayObject) -> None:
246 if kids is self._kids and len(kids) == self._length:
247 return
248 self._kids = kids
249 self._length = len(kids)
250 self._page_numbers = set()
251 self._has_other_kid = False
253 def _is_new_page(self, kid: PdfObject) -> bool:
254 """Check whether the kid is a page that is not in the prefix yet."""
255 # Same checks as in the tree walk, which also rejects an object seen before.
256 # The writer resolves a reference by its object number only.
257 if not isinstance(kid, IndirectObject) or kid.idnum in self._page_numbers:
258 return False
259 page = kid.get_object()
260 return isinstance(page, DictionaryObject) and page.get("/Type") == "/Page"
262 def contains(self, kids: ArrayObject, page_number: int) -> bool:
263 self._update(kids)
264 while not self._has_other_kid and len(self._page_numbers) <= page_number < len(kids):
265 kid = kids[len(self._page_numbers)]
266 if self._is_new_page(kid):
267 self._page_numbers.add(kid.idnum)
268 else:
269 self._has_other_kid = True
270 return page_number < len(self._page_numbers)
272 def record_insertion(self, kids: ArrayObject, index: int) -> None:
273 """Update the count after ``PdfWriter._add_page`` inserted a page at this index of the kids."""
274 if kids is not self._kids or len(kids) != self._length + 1:
275 self.reset()
276 return
277 self._length += 1
278 if index > len(self._page_numbers):
279 return
280 kid = kids[index]
281 if not self._is_new_page(kid):
282 self.reset()
283 return
284 self._page_numbers.add(kid.idnum)
287class PdfWriter(PdfDocCommon):
288 """
289 Write a PDF file out, given pages produced by another class or through
290 cloning a PDF file during initialization.
292 Typically data is added from a :class:`PdfReader<pypdf.PdfReader>`.
294 Args:
295 clone_from: identical to fileobj (for compatibility)
297 incremental: If true, loads the document and set the PdfWriter in incremental mode.
299 When writing incrementally, the original document is written first and new/modified
300 content is appended. To be used for signed document/forms to keep signature valid.
301 Encryption is not supported in this mode: calling ``encrypt`` or writing changes to an
302 encrypted document raises a ``NotImplementedError``.
304 full: If true, loads all the objects (always full if incremental = True).
305 This parameter may allow loading large PDFs.
307 strict: If true, pypdf will raise an exception if a PDF does not follow the specification.
308 If false, pypdf will try to be forgiving and do something reasonable, but it will log
309 a warning message. It is a best-effort approach.
311 keep_initial_header: If true, the PDF header of the cloned document is kept
312 when using ``clone_from`` in non-incremental mode.
314 """
316 incremental: bool
317 """
318 Returns if the PdfWriter object has been started in incremental mode.
319 """
321 _objects: list[PdfObject | None]
322 """
323 The indirect objects in the PDF.
324 For the incremental case, it will be filled with None
325 in clone_reader_document_root.
326 """
328 _id_translated: dict[int, dict[int | Literal["PreventGC"], Any]]
329 """
330 List of already translated IDs.
331 dict[id(pdf)][(idnum, generation)]
332 """
334 _reader: PdfReader | None
335 """
336 The document being appended to, in incremental mode only.
337 """
339 def __init__(
340 self,
341 fileobj: PdfReader | StrByteType | Path | None = "",
342 clone_from: PdfReader | StrByteType | Path | None = None,
343 incremental: bool = False,
344 full: bool = False,
345 strict: bool = False,
346 *,
347 keep_initial_header: bool = False,
348 incremental_clone_object_count_limit: int | None = 500_000,
349 incremental_clone_object_id_limit: int | None = 1_000_000,
350 ) -> None:
351 self.strict = strict
352 """
353 If true, pypdf will raise an exception if a PDF does not follow the specification.
354 If false, pypdf will try to be forgiving and do something reasonable, but it will log
355 a warning message. It is a best-effort approach.
356 """
358 self.incremental = incremental or full
360 self._objects = []
362 self._original_hash: list[int] = []
363 """
364 List of hashes after import; used to identify changes.
365 """
367 self._idnum_hash: dict[bytes, tuple[IndirectObject, list[IndirectObject]]] = {}
368 """
369 Maps hash values of indirect objects to the list of IndirectObjects.
370 This is used for compression.
371 """
373 self._id_translated = {}
375 self._info_obj: PdfObject | None
376 """The PDF files's document information dictionary,
377 defined by Info in the PDF file's trailer dictionary."""
379 self._reader = None
381 self._file_identifiers: ArrayObject | None = None
382 """The PDF file identifier,
383 defined by the ID in the PDF file's trailer dictionary."""
385 self._unresolved_links: list[tuple[ReferenceLink, ReferenceLink]] = []
386 "Tracks links in pages added to the writer for resolving later."
387 self._merged_in_pages: dict[IndirectObject | None, IndirectObject | None] = {}
388 "Tracks pages added to the writer and what page they turned into."
390 # Security parameters.
391 self._incremental_clone_object_count_limit = (
392 incremental_clone_object_count_limit
393 if isinstance(incremental_clone_object_count_limit, int)
394 else sys.maxsize
395 )
396 self._incremental_clone_object_id_limit = (
397 incremental_clone_object_id_limit if isinstance(incremental_clone_object_id_limit, int) else sys.maxsize
398 )
400 if self.incremental:
401 if isinstance(fileobj, (str, Path)):
402 with open(fileobj, "rb") as f:
403 fileobj = BytesIO(f.read(-1))
404 if isinstance(fileobj, BytesIO):
405 fileobj = PdfReader(fileobj)
406 if not isinstance(fileobj, PdfReader):
407 raise PyPdfError("Invalid type for incremental mode")
408 self._reader = fileobj # prev content is in _reader.stream
409 self._header = fileobj.pdf_header.encode()
410 self._readonly = True # TODO: to be analysed
411 else:
412 self._header = b"%PDF-1.3"
413 self._info_obj = self._add_object(
414 DictionaryObject(
415 {NameObject("/Producer"): create_string_object("pypdf")}
416 )
417 )
419 def _get_clone_from(
420 fileobj: PdfReader | str | Path | IO[Any] | BytesIO | None,
421 clone_from: PdfReader | str | Path | IO[Any] | BytesIO | None,
422 ) -> PdfReader | str | Path | IO[Any] | BytesIO | None:
423 if isinstance(fileobj, (str, Path, IO, BytesIO)) and (
424 fileobj == "" or clone_from is not None
425 ):
426 return clone_from
427 cloning = True
428 if isinstance(fileobj, (str, Path)):
429 fileobj_path = Path(fileobj)
430 if not fileobj_path.exists() or fileobj_path.stat().st_size == 0:
431 cloning = False
432 elif isinstance(fileobj, (IOBase, BytesIO)):
433 t = fileobj.tell()
434 if fileobj.seek(0, 2) == 0:
435 cloning = False
436 fileobj.seek(t, 0)
437 if cloning:
438 clone_from = fileobj
439 return clone_from
441 clone_from = _get_clone_from(fileobj, clone_from)
442 # To prevent overwriting
443 self.temp_fileobj = fileobj
444 self.fileobj = ""
445 self._with_as_usage = False
446 # A document cloned from fileobj is not written back to it by __exit__.
447 self._is_cloned_from_fileobj = clone_from is not None and clone_from is fileobj
448 # The root of our page tree node
449 pages = DictionaryObject(
450 {
451 NameObject(PagesAttributes.TYPE): NameObject("/Pages"),
452 NameObject(PagesAttributes.COUNT): NumberObject(0),
453 NameObject(PagesAttributes.KIDS): ArrayObject(),
454 }
455 )
456 self.flattened_pages = []
457 self._root_page_prefix = _RootPagePrefix()
458 self._page_id2num: dict[int, int] = {}
459 self._encryption: Encryption | None = None
460 self._encrypt_entry: DictionaryObject | None = None
462 if clone_from is not None:
463 if not isinstance(clone_from, PdfReader):
464 clone_from = PdfReader(clone_from)
465 self.clone_document_from_reader(clone_from)
466 if keep_initial_header and not self.incremental:
467 self._header = clone_from.pdf_header.encode()
468 else:
469 self._pages = self._add_object(pages)
470 self._root_object = DictionaryObject(
471 {
472 NameObject(PagesAttributes.TYPE): NameObject(Core.CATALOG),
473 NameObject(Core.PAGES): self._pages,
474 }
475 )
476 self._add_object(self._root_object)
477 if full and not incremental:
478 self.incremental = False
479 if isinstance(self._file_identifiers, list):
480 if isinstance(self._file_identifiers[0], TextStringObject):
481 self._file_identifiers[0] = ByteStringObject(self._file_identifiers[0].original_bytes)
482 if isinstance(self._file_identifiers[1], TextStringObject):
483 self._file_identifiers[1] = ByteStringObject(self._file_identifiers[1].original_bytes)
485 # for commonality
486 @property
487 def is_encrypted(self) -> bool:
488 """
489 Read-only boolean property showing whether this PDF file is encrypted.
491 Note that this property, if true, will remain true even after the
492 :meth:`decrypt()<pypdf.PdfReader.decrypt>` method is called.
493 """
494 return False
496 @property
497 def root_object(self) -> DictionaryObject:
498 """
499 Provide direct access to PDF Structure.
501 Note:
502 Recommended only for read access.
504 """
505 return self._root_object
507 @property
508 def _info(self) -> DictionaryObject | None:
509 """
510 Provide access to "/Info". Standardized with PdfReader.
512 Returns:
513 /Info Dictionary; None if the entry does not exist
515 """
516 return (
517 None
518 if self._info_obj is None
519 else cast(DictionaryObject, self._info_obj.get_object())
520 )
522 @_info.setter
523 def _info(self, value: IndirectObject | DictionaryObject | None) -> None:
524 if value is None:
525 with contextlib.suppress(KeyError, AttributeError):
526 self._objects[self._info_obj.indirect_reference.idnum - 1] = None # type: ignore[union-attr]
527 self._info_obj = None
528 else:
529 if self._info_obj is None:
530 self._info_obj = self._add_object(DictionaryObject())
531 obj = cast(DictionaryObject, self._info_obj.get_object())
532 obj.clear()
533 obj.update(cast(DictionaryObject, value.get_object()))
535 @property
536 def xmp_metadata(self) -> XmpInformation | None:
537 """XMP (Extensible Metadata Platform) data."""
538 return cast(XmpInformation, self.root_object.xmp_metadata)
540 @xmp_metadata.setter
541 def xmp_metadata(self, value: XmpInformation | bytes | None) -> None:
542 """XMP (Extensible Metadata Platform) data."""
543 if value is None:
544 if "/Metadata" in self.root_object:
545 del self.root_object["/Metadata"]
546 return
548 metadata = self.root_object.get("/Metadata", None)
549 if not isinstance(metadata, IndirectObject):
550 if metadata is not None:
551 del self.root_object["/Metadata"]
552 metadata_stream = StreamObject()
553 stream_reference = self._add_object(metadata_stream)
554 self.root_object[NameObject("/Metadata")] = stream_reference
555 else:
556 metadata_stream = cast(StreamObject, metadata.get_object())
558 if isinstance(value, XmpInformation):
559 bytes_data = value.stream.get_data()
560 else:
561 bytes_data = value
562 metadata_stream.set_data(bytes_data)
564 def __enter__(self) -> Self:
565 """Store that the writer is used by 'with', so that __exit__ writes to fileobj."""
566 self._with_as_usage = True
567 self.fileobj = self.temp_fileobj # type: ignore[assignment]
568 return self
570 def __exit__(
571 self,
572 exc_type: type[BaseException] | None,
573 exc: BaseException | None,
574 traceback: TracebackType | None,
575 ) -> None:
576 """Write data to the fileobj."""
577 if self.fileobj and not self._is_cloned_from_fileobj:
578 self.write(self.fileobj)
580 @property
581 def pdf_header(self) -> str:
582 """
583 Read/Write property of the PDF header that is written.
585 This should be something like ``'%PDF-1.5'``. It is recommended to set
586 the lowest version that supports all features which are used within the
587 PDF file.
589 Note: `pdf_header` returns a string but accepts bytes or str for writing
590 """
591 return self._header.decode()
593 @pdf_header.setter
594 def pdf_header(self, new_header: str | bytes) -> None:
595 if isinstance(new_header, str):
596 new_header = new_header.encode()
597 self._header = new_header
599 def _add_object(self, obj: PdfObject) -> IndirectObject:
600 if (
601 getattr(obj, "indirect_reference", None) is not None
602 and obj.indirect_reference.pdf == self # type: ignore[union-attr]
603 ):
604 return obj.indirect_reference # type: ignore[return-value]
605 # check for /Contents in Pages (/Contents in annotations are strings)
606 if isinstance(obj, DictionaryObject) and isinstance(
607 obj.get(PageAttributes.CONTENTS, None), (ArrayObject, DictionaryObject)
608 ):
609 obj[NameObject(PageAttributes.CONTENTS)] = self._add_object(obj[PageAttributes.CONTENTS])
610 self._objects.append(obj)
611 obj.indirect_reference = IndirectObject(len(self._objects), 0, self)
612 return obj.indirect_reference
614 def get_object(
615 self,
616 indirect_reference: int | IndirectObject,
617 ) -> PdfObject:
618 if isinstance(indirect_reference, int):
619 obj = self._objects[indirect_reference - 1]
620 elif indirect_reference.pdf != self:
621 raise ValueError("PDF must be self")
622 else:
623 obj = self._objects[indirect_reference.idnum - 1]
624 if obj is None:
625 raise PdfReadError(f"Object {indirect_reference!r} not found!")
626 return obj
628 def _replace_object(
629 self,
630 indirect_reference: int | IndirectObject,
631 obj: PdfObject,
632 ) -> PdfObject:
633 if isinstance(indirect_reference, IndirectObject):
634 if indirect_reference.pdf != self:
635 raise ValueError("PDF must be self")
636 indirect_reference = indirect_reference.idnum
637 gen = self._objects[indirect_reference - 1].indirect_reference.generation # type: ignore[union-attr]
638 if (
639 getattr(obj, "indirect_reference", None) is not None
640 and obj.indirect_reference.pdf != self # type: ignore[union-attr]
641 ):
642 obj = obj.clone(self)
643 self._objects[indirect_reference - 1] = obj
644 obj.indirect_reference = IndirectObject(indirect_reference, gen, self)
646 assert isinstance(obj, PdfObject), "mypy"
647 return obj
649 def _add_page(
650 self,
651 page: PageObject,
652 index: int,
653 excluded_keys: Iterable[str] = (),
654 ) -> PageObject:
655 if not isinstance(page, PageObject) or page.get(PagesAttributes.TYPE, None) != Core.PAGE:
656 raise ValueError("Invalid page object")
657 assert self.flattened_pages is not None, "mypy"
658 page_org = page
659 excluded_keys = list(excluded_keys)
660 excluded_keys += [PagesAttributes.PARENT, "/StructParents"]
661 # Acrobat does not accept two indirect references pointing on the same
662 # page; therefore in order to add multiple copies of the same
663 # page, we need to create a new dictionary for the page, however the
664 # objects below (including content) are not duplicated:
665 try: # delete an already existing page
666 del self._id_translated[id(page_org.indirect_reference.pdf)][ # type: ignore[union-attr]
667 page_org.indirect_reference.idnum # type: ignore[union-attr]
668 ]
669 except MemoryError: # pragma: no cover # TODO: BLE001
670 raise
671 except Exception:
672 pass
674 page = cast(
675 "PageObject", page_org.clone(self, False, excluded_keys).get_object()
676 )
677 if self.incremental and page_org.pdf == self._reader:
678 # Cloning reuses the object numbers of the reader, which can replace pages of the tree.
679 self._root_page_prefix.reset()
680 if page_org.pdf is not None:
681 other = page_org.pdf.pdf_header
682 self.pdf_header = _get_max_pdf_version_header(self.pdf_header, other)
684 node, idx = self._get_page_in_node(index)
685 page[NameObject(PagesAttributes.PARENT)] = node.indirect_reference
687 kids = cast(ArrayObject, node[PagesAttributes.KIDS])
688 if idx >= 0:
689 kids.insert(idx, page.indirect_reference)
690 self.flattened_pages.insert(index, page)
691 else:
692 idx = len(kids)
693 kids.append(page.indirect_reference)
694 self.flattened_pages.append(page)
695 self._root_page_prefix.record_insertion(kids, idx)
696 current: PdfObject | None = node
697 recurse = 0
698 while not is_null_or_none(current):
699 assert current is not None, "mypy" # guarded by is_null_or_none
700 node_dict = cast(DictionaryObject, current.get_object())
701 node_dict[NameObject(PagesAttributes.COUNT)] = NumberObject(cast(int, node_dict[PagesAttributes.COUNT]) + 1)
702 current = node_dict.get(PagesAttributes.PARENT, None)
703 recurse += 1
704 if recurse > 1000:
705 raise PyPdfError("Too many recursive calls!")
707 if page_org.pdf is not None:
708 # the page may contain links to other pages, and those other
709 # pages may or may not already be added. we store the
710 # information we need, so that we can resolve the references
711 # later.
712 if "/Annots" not in excluded_keys:
713 self._unresolved_links.extend(extract_links(page, page_org))
714 self._merged_in_pages[page_org.indirect_reference] = page.indirect_reference
716 return page
718 def _get_page_in_node(self, page_number: int) -> tuple[DictionaryObject, int]:
719 top = cast(DictionaryObject, self.root_object["/Pages"])
720 count = top.get("/Count", 1)
721 kids = top.get("/Kids")
722 # Below the root's /Count, the tree walk returns the root and the page number
723 # if all kids up to that index are pages.
724 if (
725 isinstance(count, int)
726 and 0 <= page_number < count
727 and isinstance(kids, ArrayObject)
728 and self._root_page_prefix.contains(kids, page_number)
729 ):
730 return top, page_number
731 return super()._get_page_in_node(page_number)
733 def set_need_appearances_writer(self, state: bool = True) -> None:
734 """
735 Sets the "NeedAppearances" flag in the PDF writer.
737 The "NeedAppearances" flag indicates whether the appearance dictionary
738 for form fields should be automatically generated by the PDF viewer or
739 if the embedded appearance should be used.
741 Args:
742 state: The actual value of the NeedAppearances flag.
744 Returns:
745 None
747 """
748 # See §12.7.2 and §7.7.2 for more information:
749 # https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf
750 try:
751 # get the AcroForm tree
752 if CatalogAttributes.ACRO_FORM not in self._root_object:
753 self._root_object[
754 NameObject(CatalogAttributes.ACRO_FORM)
755 ] = self._add_object(DictionaryObject())
757 need_appearances = NameObject(InteractiveFormDictEntries.NeedAppearances)
758 cast(DictionaryObject, self._root_object[CatalogAttributes.ACRO_FORM])[
759 need_appearances
760 ] = BooleanObject(state)
761 except MemoryError: # pragma: no cover # TODO: BLE001
762 raise
763 except Exception as exc: # pragma: no cover
764 logger_warning(
765 "set_need_appearances_writer(%(state)s) catch : %(exc)s",
766 source=__name__,
767 state=state,
768 exc=exc,
769 )
771 def create_viewer_preferences(self) -> ViewerPreferences:
772 o = ViewerPreferences()
773 self._root_object[
774 NameObject(CatalogAttributes.VIEWER_PREFERENCES)
775 ] = self._add_object(o)
776 return o
778 def add_page(
779 self,
780 page: PageObject,
781 excluded_keys: Iterable[str] = (),
782 ) -> PageObject:
783 """
784 Add a page to this PDF file.
786 Recommended for advanced usage including the adequate excluded_keys.
788 The page is usually acquired from a :class:`PdfReader<pypdf.PdfReader>`
789 instance.
791 Args:
792 page: The page to add to the document. Should be
793 an instance of :class:`PageObject<pypdf._page.PageObject>`
794 excluded_keys:
796 Returns:
797 The added PageObject.
799 """
800 assert self.flattened_pages is not None, "mypy"
801 return self._add_page(page, len(self.flattened_pages), excluded_keys)
803 def insert_page(
804 self,
805 page: PageObject,
806 index: int = 0,
807 excluded_keys: Iterable[str] = (),
808 ) -> PageObject:
809 """
810 Insert a page in this PDF file. The page is usually acquired from a
811 :class:`PdfReader<pypdf.PdfReader>` instance.
813 Args:
814 page: The page to add to the document.
815 index: Position at which the page will be inserted.
816 excluded_keys:
818 Returns:
819 The added PageObject.
821 """
822 assert self.flattened_pages is not None, "mypy"
823 if index < 0:
824 index += len(self.flattened_pages)
825 if index < 0:
826 raise ValueError("Invalid index value")
827 if index >= len(self.flattened_pages):
828 return self.add_page(page, excluded_keys)
829 return self._add_page(page, index, excluded_keys)
831 def _get_page_number_by_indirect(
832 self, indirect_reference: int | NullObject | IndirectObject | None
833 ) -> int | None:
834 """
835 Retrieve the page number from an indirect reference.
837 The index of every page is remembered. As pages are added, inserted and
838 removed, an index is only trusted after checking the page at that
839 position; otherwise the index is rebuilt.
841 Args:
842 indirect_reference: The indirect reference to locate.
844 Returns:
845 The page number or None
847 """
848 # To provide same function as in PdfReader
849 if is_null_or_none(indirect_reference):
850 return None
851 assert indirect_reference is not None, "mypy"
852 if isinstance(indirect_reference, IndirectObject):
853 if indirect_reference.pdf is not self:
854 # A page of another document is not a page of this one.
855 return None
856 idnum = indirect_reference.idnum
857 else:
858 idnum = cast(int, indirect_reference)
859 # A writer starts with an empty page list; only _flatten() sets it to
860 # None, while it rebuilds the list. Every page of a writer is an
861 # indirect object.
862 assert self.flattened_pages is not None, "mypy"
863 pages = self.flattened_pages
865 # The remembered number is still right if the page at that position
866 # has this object number.
867 number = self._page_id2num.get(idnum)
868 if (
869 number is not None
870 and number < len(pages)
871 and cast(IndirectObject, pages[number].indirect_reference).idnum == idnum
872 ):
873 return number
875 # Pages were added, inserted or removed since the numbers were
876 # remembered, or the object is no page of this writer. A page that
877 # appears twice keeps its first position.
878 self._page_id2num = {}
879 for index, page in enumerate(pages):
880 self._page_id2num.setdefault(cast(IndirectObject, page.indirect_reference).idnum, index)
881 return self._page_id2num.get(idnum)
883 def add_blank_page(
884 self, width: float | None = None, height: float | None = None
885 ) -> PageObject:
886 """
887 Append a blank page to this PDF file and return it.
889 If no page size is specified, use the size of the last page.
891 Args:
892 width: The width of the new page expressed in default user
893 space units.
894 height: The height of the new page expressed in default
895 user space units.
897 Returns:
898 The newly appended page.
900 Raises:
901 PageSizeNotDefinedError: if width and height are not defined
902 and previous page does not exist.
904 """
905 page = PageObject.create_blank_page(self, width, height)
906 return self.add_page(page)
908 def insert_blank_page(
909 self,
910 width: float | decimal.Decimal | None = None,
911 height: float | decimal.Decimal | None = None,
912 index: int = 0,
913 ) -> PageObject:
914 """
915 Insert a blank page to this PDF file and return it.
917 If no page size is specified for a dimension, use the size of the last page.
919 Args:
920 width: The width of the new page in default user space units.
921 height: The height of the new page in default user space units.
922 index: Position to add the page.
924 Returns:
925 The newly inserted page.
927 Raises:
928 PageSizeNotDefinedError: if width and height are not defined
929 and previous page does not exist.
930 IndexError: Index is outside of [-self.get_num_pages(), self.get_num_pages()]
931 """
932 num_pages = self.get_num_pages()
933 if abs(index) > num_pages:
934 raise IndexError(f"Index should be in range [-{num_pages}, {num_pages}]")
936 if num_pages:
937 # Use the chosen index, but do not exceed the available pages
938 fixed_index = min(index, num_pages - 1)
939 mediabox = self.pages[fixed_index].mediabox
940 if width is None or width <= 0:
941 width = mediabox.width
942 if height is None or height <= 0:
943 height = mediabox.height
945 page = PageObject.create_blank_page(self, width, height)
946 self.insert_page(page, index)
947 return page
949 @property
950 def open_destination(
951 self,
952 ) -> Destination | TextStringObject | ByteStringObject | None:
953 return super().open_destination
955 @open_destination.setter
956 def open_destination(self, dest: str | Destination | PageObject | None) -> None:
957 if dest is None:
958 with contextlib.suppress(KeyError):
959 del self._root_object["/OpenAction"]
960 elif isinstance(dest, str):
961 self._root_object[NameObject("/OpenAction")] = TextStringObject(dest)
962 elif isinstance(dest, Destination):
963 self._root_object[NameObject("/OpenAction")] = dest.dest_array
964 elif isinstance(dest, PageObject):
965 self._root_object[NameObject("/OpenAction")] = Destination(
966 "Opening",
967 dest.indirect_reference
968 if dest.indirect_reference is not None
969 else NullObject(),
970 PAGE_FIT,
971 ).dest_array
973 def add_js(self, javascript: str) -> NoReturn:
974 """
975 Add JavaScript which will launch upon opening this PDF.
977 Args:
978 javascript: Your JavaScript.
979 """
980 deprecation_with_replacement("add_js", "add_open_action", "7.0.0")
982 def add_open_action(self, action: Action) -> None:
983 """
984 Add an action to the document-level JavaScript name tree.
986 Args:
987 action: The action to add.
989 Example:
990 This will launch the print window when the PDF is opened.
992 >>> from pypdf import PdfWriter
993 >>> from pypdf.actions import JavaScript
994 >>> output = PdfWriter()
995 >>> output.add_open_action(JavaScript("this.print({bUI:true,bSilent:false,bShrinkToFit:true});"))
996 """
997 return Action._create_open_action(self, action)
999 def add_attachment(self, filename: str, data: str | bytes) -> "EmbeddedFile":
1000 """
1001 Embed a file inside the PDF.
1003 Reference:
1004 https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf
1005 Section 7.11.3
1007 Args:
1008 filename: The filename to display.
1009 data: The data in the file.
1011 Returns:
1012 EmbeddedFile instance for the newly created embedded file.
1014 """
1015 return EmbeddedFile._create_new(self, filename, data)
1017 def append_pages_from_reader(
1018 self,
1019 reader: PdfReader,
1020 after_page_append: Callable[[PageObject], None] | None = None,
1021 ) -> None:
1022 """
1023 Copy pages from reader to writer. Includes an optional callback
1024 parameter which is invoked after pages are appended to the writer.
1026 ``append`` should be preferred.
1028 Args:
1029 reader: a PdfReader object from which to copy page
1030 annotations to this writer object. The writer's annots
1031 will then be updated.
1032 after_page_append:
1033 Callback function that is invoked after each page is appended to
1034 the writer. Signature includes a reference to the appended page
1035 (delegates to append_pages_from_reader). The single parameter of
1036 the callback is a reference to the page just appended to the
1037 document.
1039 """
1040 reader_num_pages = len(reader.pages)
1041 # Copy pages from reader to writer
1042 for reader_page_number in range(reader_num_pages):
1043 reader_page = reader.pages[reader_page_number]
1044 writer_page = self.add_page(reader_page)
1045 # Trigger callback, pass writer page as parameter
1046 if callable(after_page_append):
1047 after_page_append(writer_page)
1049 def _merge_content_stream_to_page(
1050 self,
1051 page: PageObject,
1052 new_content_data: bytes,
1053 ) -> None:
1054 """
1055 Combines existing content stream(s) with new content (as bytes).
1057 Args:
1058 page: The page to which the new content data will be added.
1059 new_content_data: A binary-encoded new content stream, for
1060 instance the commands to draw an XObject.
1061 """
1062 # First resolve the existing page content. This always is an IndirectObject:
1063 # PDF Explained by John Whitington
1064 # https://www.oreilly.com/library/view/pdf-explained/9781449321581/ch04.html
1065 if NameObject("/Contents") in page:
1066 existing_content_ref = page[NameObject("/Contents")]
1067 existing_content = existing_content_ref.get_object()
1069 if isinstance(existing_content, ArrayObject):
1070 # Create a new StreamObject for the new_content_data
1071 new_stream_obj = StreamObject()
1072 new_stream_obj.set_data(new_content_data)
1073 existing_content.append(self._add_object(new_stream_obj))
1074 page[NameObject("/Contents")] = self._add_object(existing_content)
1075 if isinstance(existing_content, StreamObject):
1076 # Merge new content to existing StreamObject
1077 merged_data = existing_content.get_data() + b"\n" + new_content_data
1078 new_stream = StreamObject()
1079 new_stream.set_data(merged_data)
1080 page[NameObject("/Contents")] = self._add_object(new_stream)
1081 else:
1082 # If no existing content, then we have an empty page.
1083 # Create a new StreamObject in a new /Contents entry.
1084 new_stream = StreamObject()
1085 new_stream.set_data(new_content_data)
1086 page[NameObject("/Contents")] = self._add_object(new_stream)
1088 def _add_apstream_object(
1089 self,
1090 page: PageObject,
1091 appearance_stream_obj: StreamObject,
1092 object_name: str,
1093 x_offset: float,
1094 y_offset: float,
1095 ) -> None:
1096 """
1097 Adds an appearance stream to the page content in the form of
1098 an XObject.
1100 Args:
1101 page: The page to which to add the appearance stream.
1102 appearance_stream_obj: The appearance stream.
1103 object_name: The name of the appearance stream.
1104 x_offset: The horizontal offset for the appearance stream.
1105 y_offset: The vertical offset for the appearance stream.
1106 """
1107 pg_res = cast(DictionaryObject, page[PageAttributes.RESOURCES])
1108 # Always add the resolved stream object to the writer to get a new IndirectObject.
1109 # This ensures we have a valid IndirectObject managed by *this* writer.
1110 xobject_ref = self._add_object(appearance_stream_obj)
1111 xobject_name = NameObject(f"/Fm_{object_name}")._sanitize()
1112 if "/XObject" not in pg_res:
1113 pg_res[NameObject("/XObject")] = DictionaryObject()
1114 pg_xo_res = cast(DictionaryObject, pg_res["/XObject"])
1115 if xobject_name not in pg_xo_res:
1116 pg_xo_res[xobject_name] = xobject_ref
1117 else:
1118 logger_warning(
1119 "XObject %(xobject_name)r already added to page resources. This might be an issue.",
1120 source=__name__,
1121 xobject_name=xobject_name,
1122 )
1123 xobject_cm = Transformation().translate(x_offset, y_offset)
1124 xobject_drawing_commands = f"q\n{xobject_cm._to_cm()}\n{xobject_name} Do\nQ".encode()
1125 self._merge_content_stream_to_page(page, xobject_drawing_commands)
1127 FFBITS_NUL = FieldDictionaryAttributes.FfBits(0)
1129 def update_page_form_field_values(
1130 self,
1131 page: PageObject | list[PageObject] | None,
1132 fields: Mapping[str, str | list[str] | tuple[str, str, float]],
1133 flags: FieldDictionaryAttributes.FfBits = FFBITS_NUL,
1134 auto_regenerate: bool | None = True,
1135 flatten: bool = False,
1136 ) -> None:
1137 """
1138 Update the form field values for a given page from a fields dictionary.
1140 Copy field texts and values from fields to page.
1141 If the field links to a parent object, add the information to the parent.
1143 Args:
1144 page: `PageObject` - references **PDF writer's page** where the
1145 annotations and field data will be updated.
1146 `List[Pageobject]` - provides list of pages to be processed.
1147 `None` - all pages.
1148 fields: a Python dictionary of:
1150 * field names (/T) as keys and text values (/V) as value
1151 * field names (/T) as keys and list of text values (/V) for multiple choice list
1152 * field names (/T) as keys and tuple of:
1153 * text values (/V)
1154 * font id (e.g. /F1, the font id must exist)
1155 * font size (0 for autosize)
1157 flags: A set of flags from :class:`~pypdf.constants.FieldDictionaryAttributes.FfBits`.
1159 auto_regenerate: Set/unset the need_appearances flag;
1160 the flag is unchanged if auto_regenerate is None.
1162 flatten: Whether or not to flatten the annotation. If True, this adds the annotation's
1163 appearance stream to the page contents. Note that this option does not remove the
1164 annotation itself.
1166 """
1167 if CatalogAttributes.ACRO_FORM not in self._root_object:
1168 raise PyPdfError("No /AcroForm dictionary in PDF of PdfWriter Object")
1169 acro_form = cast(DictionaryObject, self._root_object[CatalogAttributes.ACRO_FORM])
1170 if InteractiveFormDictEntries.Fields not in acro_form:
1171 raise PyPdfError("No /Fields dictionary in PDF of PdfWriter Object")
1172 if isinstance(auto_regenerate, bool):
1173 self.set_need_appearances_writer(auto_regenerate)
1174 # Iterate through pages, update field values
1175 if page is None:
1176 page = list(self.pages)
1177 if isinstance(page, list):
1178 for p in page:
1179 if PageAttributes.ANNOTS in p: # just to prevent warnings
1180 self.update_page_form_field_values(p, fields, flags, None, flatten=flatten)
1181 return
1182 if PageAttributes.ANNOTS not in page:
1183 logger_warning("No fields to update on this page", source=__name__)
1184 return
1185 appearance_stream_obj: StreamObject | None = None
1187 for annotation in page[PageAttributes.ANNOTS]: # type: ignore[attr-defined]
1188 annotation = cast(DictionaryObject, annotation.get_object())
1189 if annotation.get("/Subtype", "") != "/Widget":
1190 continue
1191 if "/FT" in annotation and "/T" in annotation:
1192 parent_annotation = annotation
1193 else:
1194 parent_annotation = annotation.get(
1195 PageAttributes.PARENT, DictionaryObject()
1196 ).get_object()
1198 for field, value in fields.items():
1199 rectangle = cast(RectangleObject, annotation[AnnotationDictionaryAttributes.Rect])
1200 if not (
1201 self._get_qualified_field_name(parent=parent_annotation) == field
1202 or parent_annotation.get("/T", None) == field
1203 ):
1204 continue
1205 if (
1206 parent_annotation.get("/FT", None) == "/Ch"
1207 and "/I" in parent_annotation
1208 ):
1209 del parent_annotation["/I"]
1210 if flags:
1211 annotation[NameObject(FieldDictionaryAttributes.Ff)] = NumberObject(flags)
1212 # Set the field value
1213 if not (value is None and flatten): # Only change values if given by user and not flattening.
1214 if isinstance(value, list):
1215 lst = ArrayObject(TextStringObject(v) for v in value)
1216 parent_annotation[NameObject(FieldDictionaryAttributes.V)] = lst
1217 elif isinstance(value, tuple):
1218 parent_annotation[NameObject(FieldDictionaryAttributes.V)] = TextStringObject(
1219 value[0],
1220 )
1221 else:
1222 parent_annotation[NameObject(FieldDictionaryAttributes.V)] = TextStringObject(value)
1223 # Get or create the field's appearance stream object
1224 if parent_annotation.get(FieldDictionaryAttributes.FT) == "/Btn":
1225 # Checkbox button (no /FT found in Radio widgets);
1226 # We can find the associated appearance stream object
1227 # within the annotation.
1228 v = NameObject(value)
1229 ap = cast(DictionaryObject, annotation[NameObject(AnnotationDictionaryAttributes.AP)])
1230 normal_ap = cast(DictionaryObject, ap["/N"])
1231 if v not in normal_ap:
1232 v = NameObject("/Off")
1233 appearance_stream_obj = normal_ap.get(v)
1234 # Other cases will be updated through the for loop
1235 annotation[NameObject(AnnotationDictionaryAttributes.AS)] = v
1236 annotation[NameObject(FieldDictionaryAttributes.V)] = v
1237 elif (
1238 parent_annotation.get(FieldDictionaryAttributes.FT) == "/Tx"
1239 or parent_annotation.get(FieldDictionaryAttributes.FT) == "/Ch"
1240 ):
1241 # Textbox; we need to generate the appearance stream object
1242 if isinstance(value, tuple):
1243 appearance_stream_obj = TextStreamAppearance.from_text_annotation(
1244 self, page, flatten, acro_form, parent_annotation, annotation, value[1], value[2]
1245 )
1246 else:
1247 appearance_stream_obj = TextStreamAppearance.from_text_annotation(
1248 self, page, flatten, acro_form, parent_annotation, annotation
1249 )
1250 # Add the appearance stream object
1251 if AnnotationDictionaryAttributes.AP not in annotation:
1252 annotation[NameObject(AnnotationDictionaryAttributes.AP)] = DictionaryObject(
1253 {NameObject("/N"): self._add_object(appearance_stream_obj)}
1254 )
1255 elif "/N" not in (ap:= cast(DictionaryObject, annotation[AnnotationDictionaryAttributes.AP])):
1256 cast(DictionaryObject, annotation[NameObject(AnnotationDictionaryAttributes.AP)])[
1257 NameObject("/N")
1258 ] = self._add_object(appearance_stream_obj)
1259 else: # [/AP][/N] exists
1260 n = annotation[AnnotationDictionaryAttributes.AP]["/N"].indirect_reference.idnum # type: ignore[index]
1261 self._replace_object(n, appearance_stream_obj)
1262 elif (
1263 annotation.get(FieldDictionaryAttributes.FT) == "/Sig"
1264 ): # deprecated # not implemented yet
1265 logger_warning("Signature forms not implemented yet", source=__name__)
1267 if appearance_stream_obj and flatten:
1268 self._add_apstream_object(page, appearance_stream_obj, field, rectangle[0], rectangle[1])
1270 def reattach_fields(
1271 self, page: PageObject | None = None
1272 ) -> list[DictionaryObject]:
1273 """
1274 Parse annotations within the page looking for orphan fields and
1275 reattach then into the Fields Structure.
1277 Args:
1278 page: page to analyze.
1279 If none is provided, all pages will be analyzed.
1281 Returns:
1282 list of reattached fields.
1284 """
1285 lst = []
1286 if page is None:
1287 for p in self.pages:
1288 lst += self.reattach_fields(p)
1289 return lst
1291 acro_form = self._root_object.get(CatalogAttributes.ACRO_FORM, NullObject()).get_object()
1292 if is_null_or_none(acro_form):
1293 # Missing, null, or a reference to an object that does not exist
1294 acro_form = DictionaryObject()
1295 self._root_object[NameObject(CatalogAttributes.ACRO_FORM)] = acro_form
1296 af = cast(DictionaryObject, acro_form)
1297 field_array = af.get(InteractiveFormDictEntries.Fields, NullObject()).get_object()
1298 if is_null_or_none(field_array):
1299 field_array = ArrayObject()
1300 af[NameObject(InteractiveFormDictEntries.Fields)] = field_array
1301 fields = cast(ArrayObject, field_array)
1303 annotation_array = page.get("/Annots", NullObject()).get_object()
1304 if is_null_or_none(annotation_array):
1305 return lst
1306 annotations = cast(ArrayObject, annotation_array)
1307 for idx, annotation in enumerate(annotations):
1308 is_indirect = isinstance(annotation, IndirectObject)
1309 annotation = cast(DictionaryObject, annotation.get_object())
1310 if annotation.get("/Subtype", "") == "/Widget" and "/FT" in annotation:
1311 if (
1312 "indirect_reference" in annotation.__dict__
1313 and annotation.indirect_reference in fields
1314 ):
1315 continue
1316 if not is_indirect:
1317 annotations[idx] = self._add_object(annotation)
1318 fields.append(annotation.indirect_reference)
1319 lst.append(annotation)
1320 return lst
1322 def _collect_incremental_clone_object_ids(self, reader: PdfReader) -> list[int]:
1323 object_ids: set[int] = set()
1324 for xref_entry in reader.xref.values():
1325 object_ids.update(filter(None, xref_entry))
1326 object_ids.update(filter(None, reader.xref_objStm))
1328 object_count = len(object_ids)
1329 if object_count > self._incremental_clone_object_count_limit:
1330 raise LimitReachedError(
1331 f"Incremental clone object count {object_count} exceeds "
1332 f"maximum allowed count {self._incremental_clone_object_count_limit}."
1333 )
1335 max_object_id = max(object_ids, default=0)
1336 if max_object_id > self._incremental_clone_object_id_limit:
1337 raise LimitReachedError(
1338 f"Incremental clone object ID {max_object_id} exceeds "
1339 f"maximum allowed ID {self._incremental_clone_object_id_limit}."
1340 )
1342 return sorted(object_ids)
1344 def clone_reader_document_root(self, reader: PdfReader) -> None:
1345 """
1346 Copy the reader document root to the writer and all sub-elements,
1347 including pages, threads, outlines,... For partial insertion, ``append``
1348 should be considered.
1350 Args:
1351 reader: PdfReader from which the document root should be copied.
1353 """
1354 self._info_obj = None
1355 if self.incremental:
1356 object_ids = self._collect_incremental_clone_object_ids(reader)
1357 self._objects = [None] * (object_ids[-1] if object_ids else 0)
1358 for object_id in object_ids:
1359 # Generation numbers only increase when an object number is reused,
1360 # thus the highest one is the version the references point to.
1361 generation = max(
1362 (generation for generation, entries in reader.xref.items() if object_id in entries),
1363 default=0,
1364 )
1365 reader_object = reader.get_object(IndirectObject(object_id, generation, reader))
1366 if reader_object is not None:
1367 self._objects[object_id - 1] = reader_object.replicate(self)
1368 else:
1369 self._objects.clear()
1370 self._root_object = reader.root_object.clone(self)
1371 self._pages = self._root_object.raw_get("/Pages")
1373 trailer_size = cast(int, reader.trailer["/Size"])
1374 if len(self._objects) > trailer_size:
1375 if self.strict:
1376 raise PdfReadError(
1377 f"Object count {len(self._objects)} exceeds defined trailer size {trailer_size}"
1378 )
1379 logger_warning(
1380 "Object count %(object_count)d exceeds defined trailer size %(trailer_size)d",
1381 source=__name__,
1382 object_count=len(self._objects),
1383 trailer_size=trailer_size,
1384 )
1386 # must be done here before rewriting
1387 if self.incremental:
1388 self._original_hash = [
1389 (obj.hash_bin() if obj is not None else 0) for obj in self._objects
1390 ]
1392 try:
1393 self._flatten()
1394 except IndexError as exception: # pragma: no cover
1395 raise PdfReadError("Got index error while flattening.") from exception # pragma: no cover
1397 assert self.flattened_pages is not None
1398 for p in self.flattened_pages:
1399 self._replace_object(cast(IndirectObject, p.indirect_reference).idnum, p)
1400 if not self.incremental:
1401 p[NameObject("/Parent")] = self._pages
1402 if not self.incremental:
1403 cast(DictionaryObject, self._pages.get_object())[
1404 NameObject("/Kids")
1405 ] = ArrayObject([p.indirect_reference for p in self.flattened_pages])
1407 def clone_document_from_reader(
1408 self,
1409 reader: PdfReader,
1410 after_page_append: Callable[[PageObject], None] | None = None,
1411 ) -> None:
1412 """
1413 Create a copy (clone) of a document from a PDF file reader cloning
1414 section '/Root' and '/Info' and '/ID' of the pdf.
1416 Args:
1417 reader: PDF file reader instance from which the clone
1418 should be created.
1419 after_page_append:
1420 Callback function that is invoked after each page is appended to
1421 the writer. Signature includes a reference to the appended page
1422 (delegates to append_pages_from_reader). The single parameter of
1423 the callback is a reference to the page just appended to the
1424 document.
1426 """
1427 self.clone_reader_document_root(reader)
1428 inf = reader._info
1429 if self.incremental:
1430 if inf is not None:
1431 self._info_obj = cast(
1432 IndirectObject, inf.clone(self).indirect_reference
1433 )
1434 assert isinstance(self._info, DictionaryObject), "mypy"
1435 self._original_hash[
1436 self._info_obj.indirect_reference.idnum - 1
1437 ] = self._info.hash_bin()
1438 elif inf is not None:
1439 self._info_obj = self._add_object(inf.clone(self))
1440 # else: _info_obj = None done in clone_reader_document_root()
1442 with contextlib.suppress(AttributeError):
1443 self._file_identifiers = cast(ArrayObject, reader._file_identifiers).clone(self)
1445 if callable(after_page_append):
1446 for page in cast(
1447 ArrayObject, cast(DictionaryObject, self._pages.get_object())["/Kids"]
1448 ):
1449 after_page_append(page.get_object())
1451 def generate_file_identifiers(self) -> None:
1452 """
1453 Generate an identifier for the PDF that will be written.
1455 The only point of this is ensuring uniqueness. Reproducibility is not
1456 required.
1457 When a file is first written, both identifiers shall be set to the same value.
1458 If both identifiers match when a file reference is resolved, it is very
1459 likely that the correct and unchanged file has been found. If only the first
1460 identifier matches, a different version of the correct file has been found.
1461 see §14.4 "File Identifiers".
1462 """
1463 if self._file_identifiers:
1464 id1 = self._file_identifiers[0]
1465 id2 = ByteStringObject(secrets.token_bytes(16))
1466 else:
1467 id1 = ByteStringObject(secrets.token_bytes(16))
1468 id2 = id1
1469 self._file_identifiers = ArrayObject((id1, id2))
1471 def encrypt(
1472 self,
1473 user_password: str,
1474 owner_password: str | None = None,
1475 use_128bit: bool = True,
1476 permissions_flag: UserAccessPermissions = ALL_DOCUMENT_PERMISSIONS,
1477 *,
1478 algorithm: str | None = None,
1479 ) -> None:
1480 """
1481 Encrypt this PDF file with the PDF Standard encryption handler.
1483 Args:
1484 user_password: The password which allows for opening
1485 and reading the PDF file with the restrictions provided.
1486 owner_password: The password which allows for
1487 opening the PDF files without any restrictions. By default,
1488 the owner password is the same as the user password.
1489 use_128bit: flag as to whether to use 128bit
1490 encryption. When false, 40bit encryption will be used.
1491 By default, this flag is on.
1492 permissions_flag: permissions as described in
1493 Table 3.20 of the PDF 1.7 specification. A bit value of 1 means
1494 the permission is granted.
1495 Hence an integer value of -1 will set all flags.
1496 Bit position 3 is for printing, 4 is for modifying content,
1497 5 and 6 control annotations, 9 for form fields,
1498 10 for extraction of text and graphics.
1499 algorithm: encrypt algorithm. Values may be one of "RC4-40", "RC4-128",
1500 "AES-128", "AES-256-R5", "AES-256". If it is valid,
1501 `use_128bit` will be ignored.
1503 """
1504 if self.incremental:
1505 raise NotImplementedError("Encrypting incremental PDF files is currently not supported.")
1507 if owner_password is None:
1508 owner_password = user_password
1510 if algorithm is not None:
1511 try:
1512 alg = getattr(EncryptAlgorithm, algorithm.replace("-", "_"))
1513 except AttributeError as exception: # pragma: no cover
1514 raise ValueError(f"Algorithm '{algorithm}' NOT supported") from exception # pragma: no cover
1515 else:
1516 alg = EncryptAlgorithm.RC4_128
1517 if not use_128bit:
1518 alg = EncryptAlgorithm.RC4_40
1519 self.generate_file_identifiers()
1520 assert self._file_identifiers
1521 self._encryption = Encryption.make(alg, permissions_flag, self._file_identifiers[0])
1522 # in case call `encrypt` again
1523 entry = self._encryption.write_entry(user_password, owner_password, strict=self.strict)
1524 if self._encrypt_entry:
1525 # replace old encrypt_entry
1526 assert self._encrypt_entry.indirect_reference is not None
1527 entry.indirect_reference = self._encrypt_entry.indirect_reference
1528 self._objects[entry.indirect_reference.idnum - 1] = entry
1529 else:
1530 self._add_object(entry)
1531 self._encrypt_entry = entry
1533 def _resolve_links(self) -> None:
1534 """Patch up links that were added to the document earlier, to
1535 make sure they still point to the same pages.
1536 """
1537 known_names: set[str] | None = None
1538 for (new_link, old_link) in self._unresolved_links:
1539 old_page = old_link.find_referenced_page()
1540 if not old_page:
1541 continue
1542 new_page = self._merged_in_pages.get(old_page)
1543 if new_page is None:
1544 continue
1545 if isinstance(new_link, NamedReferenceLink):
1546 if known_names is None:
1547 known_names = set(self.named_destinations)
1548 new_link.patch_reference(self, new_page, known_names=known_names)
1549 else:
1550 new_link.patch_reference(self, new_page)
1552 def write_stream(self, stream: StreamType) -> None:
1553 if hasattr(stream, "mode") and "b" not in stream.mode:
1554 logger_warning(
1555 "File <%(stream_name)s> to write to is not in binary mode. "
1556 "It may not be written to correctly.",
1557 source=__name__,
1558 stream_name=stream.name,
1559 )
1560 self._resolve_links()
1562 if self.incremental:
1563 assert self._reader is not None, "mypy"
1564 has_increment = len(self.list_objects_in_increment()) > 0
1565 if has_increment and self._reader.is_encrypted:
1566 raise NotImplementedError(
1567 "Writing incremental updates of encrypted PDF files is currently not supported."
1568 )
1569 self._reader.stream.seek(0)
1570 stream.write(self._reader.stream.read(-1))
1571 if has_increment:
1572 self._write_increment(stream) # writes objs, xref stream and startxref
1573 else:
1574 object_positions, free_objects = self._write_pdf_structure(stream)
1575 xref_location = self._write_xref_table(
1576 stream, object_positions, free_objects
1577 )
1578 self._write_trailer(stream, xref_location)
1580 def write(self, stream: Path | StrByteType) -> tuple[bool, IO[Any]]:
1581 """
1582 Write the collection of pages added to this object out as a PDF file.
1584 Args:
1585 stream: An object to write the file to. The object can support
1586 the write method and the tell method, similar to a file object, or
1587 be a file path, just like the fileobj, just named it stream to keep
1588 existing workflow.
1590 Returns:
1591 A tuple (bool, IO).
1593 """
1594 my_file = False
1596 if stream == "":
1597 raise ValueError(f"Output({stream=}) is empty.")
1599 if isinstance(stream, (str, Path)):
1600 stream = FileIO(stream, "wb")
1601 my_file = True
1603 self.write_stream(stream)
1605 if my_file:
1606 stream.close()
1607 else:
1608 stream.flush()
1610 return my_file, stream
1612 def list_objects_in_increment(self) -> list[IndirectObject]:
1613 """
1614 For analysis or debugging.
1615 Provides the list of new or modified objects that will be written
1616 in the increment.
1617 Deleted objects will not be freed but will become orphans.
1619 Returns:
1620 List of new or modified IndirectObjects
1622 """
1623 original_hash_count = len(self._original_hash)
1624 return [
1625 cast(IndirectObject, obj).indirect_reference
1626 for i, obj in enumerate(self._objects)
1627 if (
1628 obj is not None
1629 and (
1630 i >= original_hash_count
1631 or obj.hash_bin() != self._original_hash[i]
1632 )
1633 )
1634 ]
1636 def _write_increment(self, stream: StreamType) -> None:
1637 # Only reached from `write()` inside `if self.incremental`.
1638 assert self._reader is not None, "mypy"
1639 if self._reader.is_encrypted:
1640 raise NotImplementedError("Writing incremental updates of encrypted PDF files is currently not supported.")
1641 object_positions = {}
1642 object_blocks = []
1643 current_start = -1
1644 current_stop = -2
1645 original_hash_count = len(self._original_hash)
1646 for i, obj in enumerate(self._objects):
1647 if obj is not None and (
1648 i >= original_hash_count
1649 or obj.hash_bin() != self._original_hash[i]
1650 ):
1651 idnum = i + 1
1652 assert isinstance(obj, PdfObject), "mypy"
1653 reference = getattr(obj, "indirect_reference", None)
1654 generation = reference.generation if isinstance(reference, IndirectObject) else 0
1655 # first write new/modified object
1656 object_positions[idnum] = (stream.tell(), generation)
1657 stream.write(f"{idnum} {generation} obj\n".encode())
1658 obj.write_to_stream(stream)
1659 stream.write(b"\nendobj\n")
1661 # prepare xref
1662 if idnum != current_stop:
1663 if current_start > 0:
1664 object_blocks.append(
1665 [current_start, current_stop - current_start]
1666 )
1667 current_start = idnum
1668 current_stop = idnum + 1
1669 assert current_start > 0, "for pytest only"
1670 object_blocks.append([current_start, current_stop - current_start])
1671 # write incremented xref
1672 xref_location = stream.tell()
1673 xr_id = len(self._objects) + 1
1674 stream.write(f"{xr_id} 0 obj".encode())
1675 init_data = {
1676 NameObject("/Type"): NameObject("/XRef"),
1677 NameObject("/Size"): NumberObject(xr_id + 1),
1678 NameObject("/Root"): self.root_object.indirect_reference,
1679 NameObject("/Filter"): NameObject("/FlateDecode"),
1680 NameObject("/Index"): ArrayObject(
1681 [NumberObject(_it) for _su in object_blocks for _it in _su]
1682 ),
1683 NameObject("/W"): ArrayObject(
1684 [NumberObject(1), NumberObject(4), NumberObject(2)]
1685 ),
1686 "__streamdata__": b"",
1687 }
1688 if self._info is not None and (
1689 self._info.indirect_reference.idnum - 1 # type: ignore[union-attr]
1690 >= len(self._original_hash)
1691 or cast(IndirectObject, self._info).hash_bin() # kept for future
1692 != self._original_hash[
1693 self._info.indirect_reference.idnum - 1 # type: ignore[union-attr]
1694 ]
1695 ):
1696 init_data[NameObject(TrailerKeys.INFO)] = self._info.indirect_reference
1697 init_data[NameObject(TrailerKeys.PREV)] = NumberObject(self._reader._startxref)
1698 if self._file_identifiers:
1699 init_data[NameObject(TrailerKeys.ID)] = self._file_identifiers
1700 xr = StreamObject.initialize_from_dictionary(init_data)
1701 xr.set_data(
1702 b"".join(
1703 [struct.pack(b">BIH", 1, _pos, _gen) for _pos, _gen in object_positions.values()]
1704 )
1705 )
1706 xr.write_to_stream(stream)
1707 stream.write(f"\nendobj\nstartxref\n{xref_location}\n%%EOF\n".encode()) # eof
1709 def _write_pdf_structure(self, stream: StreamType) -> tuple[list[int], list[int]]:
1710 object_positions = []
1711 free_objects = []
1712 stream.write(self.pdf_header.encode() + b"\n")
1713 stream.write(b"%\xE2\xE3\xCF\xD3\n")
1715 for idnum, obj in enumerate(self._objects, start=1):
1716 if obj is not None:
1717 object_positions.append(stream.tell())
1718 stream.write(f"{idnum} 0 obj\n".encode())
1719 if self._encryption and obj != self._encrypt_entry:
1720 obj = self._encryption.encrypt_object(obj, idnum, 0)
1721 obj.write_to_stream(stream)
1722 stream.write(b"\nendobj\n")
1723 else:
1724 object_positions.append(-1)
1725 free_objects.append(idnum)
1726 free_objects.append(0) # add 0 to loop in accordance with specification
1727 return object_positions, free_objects
1729 def _write_xref_table(
1730 self, stream: StreamType, object_positions: list[int], free_objects: list[int]
1731 ) -> int:
1732 xref_location = stream.tell()
1733 stream.write(b"xref\n")
1734 stream.write(f"0 {len(self._objects) + 1}\n".encode())
1735 stream.write(f"{free_objects[0]:0>10} {65535:0>5} f \n".encode())
1736 free_idx = 1
1737 for offset in object_positions:
1738 if offset > 0:
1739 stream.write(f"{offset:0>10} {0:0>5} n \n".encode())
1740 else:
1741 stream.write(f"{free_objects[free_idx]:0>10} {1:0>5} f \n".encode())
1742 free_idx += 1
1743 return xref_location
1745 def _write_trailer(self, stream: StreamType, xref_location: int) -> None:
1746 """
1747 Write the PDF trailer to the stream.
1749 To quote the PDF specification:
1750 [The] trailer [gives] the location of the cross-reference table and
1751 of certain special objects within the body of the file.
1752 """
1753 stream.write(b"trailer\n")
1754 trailer = DictionaryObject(
1755 {
1756 NameObject(TrailerKeys.SIZE): NumberObject(len(self._objects) + 1),
1757 NameObject(TrailerKeys.ROOT): self.root_object.indirect_reference,
1758 }
1759 )
1760 if self._info is not None:
1761 trailer[NameObject(TrailerKeys.INFO)] = self._info.indirect_reference
1762 if self._file_identifiers is not None:
1763 trailer[NameObject(TrailerKeys.ID)] = self._file_identifiers
1764 if self._encrypt_entry:
1765 trailer[NameObject(TrailerKeys.ENCRYPT)] = self._encrypt_entry.indirect_reference
1766 trailer.write_to_stream(stream)
1767 stream.write(f"\nstartxref\n{xref_location}\n%%EOF\n".encode()) # eof
1769 @property
1770 def metadata(self) -> DocumentInformation | None:
1771 """
1772 Retrieve/set the PDF file's document information dictionary, if it exists.
1774 Args:
1775 value: dict with the entries to be set. if None : remove the /Info entry from the pdf.
1777 Note that some PDF files use (XMP) metadata streams instead of document
1778 information dictionaries, and these metadata streams will not be
1779 accessed by this function, but by :meth:`~xmp_metadata`.
1781 """
1782 return super().metadata
1784 @metadata.setter
1785 def metadata(
1786 self,
1787 value: DocumentInformation | DictionaryObject | dict[Any, Any] | None,
1788 ) -> None:
1789 if value is None:
1790 self._info = None
1791 else:
1792 if self._info is not None:
1793 self._info.clear()
1795 self.add_metadata(value)
1797 def add_metadata(self, infos: dict[str, Any]) -> None:
1798 """
1799 Add custom metadata to the output.
1801 Args:
1802 infos: a Python dictionary where each key is a field
1803 and each value is your new metadata.
1805 """
1806 args = {}
1807 if isinstance(infos, PdfObject):
1808 infos = cast(DictionaryObject, infos.get_object())
1809 for key, value in list(infos.items()):
1810 if isinstance(value, PdfObject):
1811 value = value.get_object()
1812 args[NameObject(key)] = create_string_object(str(value))
1813 if self._info is None:
1814 self._info = DictionaryObject()
1815 self._info.update(args)
1817 _UNSET = object()
1819 def compress_identical_objects(
1820 self,
1821 remove_identicals: Any = _UNSET,
1822 remove_orphans: Any = _UNSET,
1823 *,
1824 remove_duplicates: bool = True,
1825 remove_unreferenced: bool = True,
1826 ) -> None:
1827 """
1828 Parse the PDF file and merge objects that have the same hash.
1829 This will make objects common to multiple pages.
1830 Recommended to be used just before writing output.
1832 Args:
1833 remove_identicals: Deprecated.
1834 remove_orphans: Deprecated.
1835 remove_duplicates: Remove duplicate objects.
1836 remove_unreferenced: Remove unreferenced objects.
1838 """
1839 if remove_identicals != self._UNSET:
1840 deprecation_with_replacement("remove_identicals", "remove_duplicates", "7.0.0")
1841 if remove_orphans != self._UNSET:
1842 deprecation_with_replacement("remove_orphans", "remove_unreferenced", "7.0.0")
1844 def replace_in_obj(
1845 obj: PdfObject, crossref: dict[IndirectObject, IndirectObject]
1846 ) -> None:
1847 if isinstance(obj, DictionaryObject):
1848 key_val = obj.items()
1849 elif isinstance(obj, ArrayObject):
1850 key_val = enumerate(obj) # type: ignore[assignment]
1851 else:
1852 return
1853 assert isinstance(obj, (DictionaryObject, ArrayObject))
1854 for k, v in key_val:
1855 if isinstance(v, IndirectObject):
1856 if v in crossref:
1857 obj[k] = crossref[v]
1858 else:
1859 """The filtering on DictionaryObject and ArrayObject only
1860 will be performed within replace_in_obj"""
1861 replace_in_obj(v, crossref)
1863 # _idnum_hash: dict[hash] = (1st_ind_obj, [2nd_ind_obj,...])
1864 self._idnum_hash = {}
1865 # look for similar objects
1866 for idx, obj in enumerate(self._objects):
1867 if is_null_or_none(obj):
1868 continue
1869 assert obj is not None, "mypy" # mypy: TypeGuard of `is_null_or_none` does not help here.
1870 assert isinstance(obj.indirect_reference, IndirectObject)
1871 h = obj.hash_value()
1872 if remove_duplicates and h in self._idnum_hash:
1873 self._idnum_hash[h][1].append(obj.indirect_reference)
1874 self._objects[idx] = None
1875 else:
1876 self._idnum_hash[h] = (obj.indirect_reference, [])
1878 # generate the dict converting others to 1st
1879 cnv = {v[0]: v[1] for v in self._idnum_hash.values() if len(v[1]) > 0}
1880 cnv_rev: dict[IndirectObject, IndirectObject] = {}
1881 for k, v in cnv.items():
1882 cnv_rev.update(zip(v, (k,) * len(v)))
1884 # replace reference to merged objects
1885 for obj in self._objects:
1886 if isinstance(obj, (DictionaryObject, ArrayObject)):
1887 replace_in_obj(obj, cnv_rev)
1889 if remove_unreferenced:
1890 reachable = self._find_reachable_objects()
1891 for idnum in range(1, len(self._objects) + 1):
1892 if idnum not in reachable:
1893 self._objects[idnum - 1] = None
1895 def _find_reachable_objects(self) -> set[int]:
1896 """Get the numbers of all objects which the trailer leads to."""
1897 reachable: set[int] = set()
1898 object_count = len(self._objects)
1899 objects_to_visit: list[Any] = []
1900 for obj in (self.root_object, self._info, self._file_identifiers, self._encrypt_entry):
1901 reference = getattr(obj, "indirect_reference", None)
1902 objects_to_visit.append(obj if reference is None else reference)
1903 while objects_to_visit:
1904 obj = objects_to_visit.pop()
1905 if isinstance(obj, IndirectObject):
1906 if obj.pdf is self and obj.idnum not in reachable and 0 < obj.idnum <= object_count:
1907 reachable.add(obj.idnum)
1908 objects_to_visit.append(self._objects[obj.idnum - 1])
1909 elif isinstance(obj, DictionaryObject):
1910 objects_to_visit.extend(obj.values())
1911 elif isinstance(obj, ArrayObject):
1912 objects_to_visit.extend(obj)
1913 return reachable
1915 def get_reference(self, obj: PdfObject) -> IndirectObject:
1916 idnum = self._objects.index(obj) + 1
1917 ref = IndirectObject(idnum, 0, self)
1918 assert ref.get_object() == obj
1919 return ref
1921 def get_outline_root(self) -> TreeObject:
1922 outline: TreeObject | None = None
1923 if Core.OUTLINES in self._root_object:
1924 # Entries in the catalog dictionary
1925 entry = self._root_object[Core.OUTLINES]
1926 if isinstance(entry, TreeObject):
1927 outline = entry
1928 elif isinstance(entry, DictionaryObject):
1929 outline = TreeObject(entry)
1930 reference = getattr(entry, "indirect_reference", None)
1931 if reference is None:
1932 # A direct dictionary cannot be replaced in place
1933 self._root_object[NameObject(Core.OUTLINES)] = self._add_object(outline)
1934 else:
1935 self._replace_object(reference.idnum, outline)
1936 elif not is_null_or_none(entry):
1937 logger_warning(
1938 "Outlines are not a dictionary: %(entry)s",
1939 source=__name__,
1940 entry=entry,
1941 )
1942 if outline is None:
1943 outline = TreeObject()
1944 outline.update({})
1945 outline_ref = self._add_object(outline)
1946 self._root_object[NameObject(Core.OUTLINES)] = outline_ref
1948 return outline
1950 def get_threads_root(self) -> ArrayObject:
1951 """
1952 The list of threads.
1954 See §12.4.3 of the PDF 1.7 or PDF 2.0 specification.
1956 Returns:
1957 An array (possibly empty) of Dictionaries with an ``/F`` key,
1958 and optionally information about the thread in ``/I`` or ``/Metadata`` keys.
1960 """
1961 if Core.THREADS in self._root_object:
1962 # Entries in the catalog dictionary
1963 threads = cast(ArrayObject, self._root_object[Core.THREADS])
1964 else:
1965 threads = ArrayObject()
1966 self._root_object[NameObject(Core.THREADS)] = threads
1967 return threads
1969 @property
1970 def threads(self) -> ArrayObject:
1971 """
1972 Read-only property for the list of threads.
1974 See §12.4.3 of the PDF 1.7 or PDF 2.0 specification.
1976 Each element is a dictionary with an ``/F`` key, and optionally
1977 information about the thread in ``/I`` or ``/Metadata`` keys.
1978 """
1979 return self.get_threads_root()
1981 def add_outline_item_destination(
1982 self,
1983 page_destination: IndirectObject | PageObject | TreeObject,
1984 parent: TreeObject | IndirectObject | None = None,
1985 before: TreeObject | IndirectObject | None = None,
1986 is_open: bool = True,
1987 ) -> IndirectObject:
1988 page_destination = cast(PageObject, page_destination.get_object())
1989 if isinstance(page_destination, PageObject):
1990 return self.add_outline_item_destination(
1991 Destination(
1992 f"page #{page_destination.page_number}",
1993 cast(IndirectObject, page_destination.indirect_reference),
1994 Fit.fit(),
1995 )
1996 )
1998 if parent is None:
1999 parent = self.get_outline_root()
2001 page_destination[NameObject("/%is_open%")] = BooleanObject(is_open)
2002 parent = cast(TreeObject, parent.get_object())
2003 page_destination_ref = self._add_object(page_destination)
2004 if before is not None:
2005 before = before.indirect_reference
2006 parent.insert_child(
2007 page_destination_ref,
2008 before,
2009 self,
2010 page_destination.inc_parent_counter_outline,
2011 )
2012 if "/Count" not in page_destination:
2013 page_destination[NameObject("/Count")] = NumberObject(0)
2015 return page_destination_ref
2017 def add_outline_item_dict(
2018 self,
2019 outline_item: OutlineItemType,
2020 parent: TreeObject | IndirectObject | None = None,
2021 before: TreeObject | IndirectObject | None = None,
2022 is_open: bool = True,
2023 ) -> IndirectObject:
2024 outline_item_object = TreeObject()
2025 outline_item_object.update(outline_item)
2027 """code currently unreachable
2028 if "/A" in outline_item:
2029 action = DictionaryObject()
2030 a_dict = cast(DictionaryObject, outline_item["/A"])
2031 for k, v in list(a_dict.items()):
2032 action[NameObject(str(k))] = v
2033 action_ref = self._add_object(action)
2034 outline_item_object[NameObject("/A")] = action_ref
2035 """
2036 return self.add_outline_item_destination(
2037 outline_item_object, parent, before, is_open
2038 )
2040 @deprecate_positional_arguments("8.0.0")
2041 def add_outline_item(
2042 self,
2043 *,
2044 title: str,
2045 page_number: PageObject | IndirectObject | int | None,
2046 parent: TreeObject | IndirectObject | None = None,
2047 before: TreeObject | IndirectObject | None = None,
2048 color: tuple[float, float, float] | str | None = None,
2049 bold: bool = False,
2050 italic: bool = False,
2051 fit: Fit = PAGE_FIT,
2052 is_open: bool = True,
2053 ) -> IndirectObject:
2054 """
2055 Add an outline item (commonly referred to as a "Bookmark") to the PDF file.
2057 Args:
2058 title: Title to use for this outline item.
2059 page_number: Page number this outline item will point to.
2060 parent: A reference to a parent outline item to create nested
2061 outline items.
2062 before: The outline item in front of which the new outline item
2063 is inserted. If None, the new outline item is appended.
2064 color: Color of the outline item's font as a red, green, blue tuple
2065 from 0.0 to 1.0 or as a Hex String (#RRGGBB)
2066 bold: Outline item font is bold
2067 italic: Outline item font is italic
2068 fit: The fit of the destination page.
2069 is_open: Whether the children of the outline item are shown.
2071 Returns:
2072 The added outline item as an indirect object.
2074 .. deprecated:: 7.1.0
2075 Passing positional arguments is deprecated and will be removed
2076 in pypdf 8.0.0. Use keyword arguments instead.
2078 """
2079 page_ref: NullObject | IndirectObject | NumberObject | None
2080 if page_number is None:
2081 action_ref = None
2082 else:
2083 if isinstance(page_number, IndirectObject):
2084 page_ref = page_number
2085 elif isinstance(page_number, PageObject):
2086 page_ref = page_number.indirect_reference
2087 elif isinstance(page_number, int):
2088 try:
2089 page_ref = self.pages[page_number].indirect_reference
2090 except IndexError:
2091 page_ref = NumberObject(page_number)
2092 else:
2093 raise TypeError(f"page_number: invalid type {type(page_number)}")
2094 if page_ref is None:
2095 logger_warning(
2096 "can not find reference of page %(page_number)s",
2097 source=__name__,
2098 page_number=page_number,
2099 )
2100 page_ref = NullObject()
2101 dest = Destination(
2102 NameObject("/" + title + " outline item"),
2103 page_ref,
2104 fit,
2105 )
2107 action_ref = self._add_object(
2108 DictionaryObject(
2109 {
2110 NameObject(GoToActionArguments.D): dest.dest_array,
2111 NameObject(GoToActionArguments.S): NameObject("/GoTo"),
2112 }
2113 )
2114 )
2115 outline_item = self._add_object(
2116 _create_outline_item(action_ref, title, color, italic, bold)
2117 )
2119 if parent is None:
2120 parent = self.get_outline_root()
2121 return self.add_outline_item_destination(outline_item, parent, before, is_open)
2123 def add_outline(self) -> None:
2124 raise NotImplementedError(
2125 "This method is not yet implemented. Use :meth:`add_outline_item` instead."
2126 )
2128 def add_named_destination_array(
2129 self, title: TextStringObject, destination: IndirectObject | ArrayObject
2130 ) -> None:
2131 named_dest = self.get_named_dest_root()
2132 i = 0
2133 while i < len(named_dest):
2134 if title < named_dest[i]:
2135 named_dest.insert(i, destination)
2136 named_dest.insert(i, TextStringObject(title))
2137 return
2138 i += 2
2139 named_dest.extend([TextStringObject(title), destination])
2140 return
2142 def add_named_destination_object(
2143 self,
2144 page_destination: PdfObject,
2145 ) -> IndirectObject:
2146 page_destination_ref = self._add_object(page_destination.dest_array) # type: ignore[attr-defined]
2147 self.add_named_destination_array(
2148 cast("TextStringObject", page_destination["/Title"]), page_destination_ref # type: ignore[index]
2149 )
2151 return page_destination_ref
2153 def _get_page_reference(self, page_number: int) -> IndirectObject:
2154 """Look up a page by number, reporting a bad index rather than an IndexError from the kids array."""
2155 pages = self.pages
2156 count = len(pages)
2157 if not (-count <= page_number < count):
2158 raise IndexError(f"Page number {page_number} is out of range")
2159 return cast(IndirectObject, pages[page_number].indirect_reference)
2161 def add_named_destination(
2162 self,
2163 title: str,
2164 page_number: int,
2165 fit: Fit | None = None,
2166 ) -> IndirectObject:
2167 """
2168 Add a named destination to a page in this PDF.
2170 Args:
2171 title: Name of the destination.
2172 page_number: Index of the destination page, starting at zero.
2173 fit: How the destination is displayed.
2174 Defaults to fitting the page horizontally with its
2175 top edge at the top of the window.
2177 Returns:
2178 A reference to the destination's GoTo action.
2180 """
2181 page_ref = self._get_page_reference(page_number)
2182 if fit is None:
2183 top = cast(DictionaryObject, page_ref.get_object()).get(PageAttributes.MEDIABOX)
2184 top = RectangleObject(top).top if top is not None else 0
2185 fit = Fit.fit_horizontally(top=top)
2186 if not isinstance(title, TextStringObject):
2187 title = TextStringObject(str(title))
2188 dest = DictionaryObject()
2189 dest.update(
2190 {
2191 NameObject(GoToActionArguments.D): Destination(title, page_ref, fit).dest_array,
2192 NameObject(GoToActionArguments.S): NameObject("/GoTo"),
2193 }
2194 )
2196 dest_ref = self._add_object(dest)
2197 self.add_named_destination_array(title, dest_ref)
2198 return dest_ref
2200 def remove_links(self) -> None:
2201 """Remove links and annotations from this output."""
2202 for page in self.pages:
2203 self.remove_objects_from_page(page, ObjectDeletionFlag.ALL_ANNOTATIONS)
2205 def remove_annotations(
2206 self, subtypes: AnnotationSubtype | Iterable[AnnotationSubtype] | None
2207 ) -> None:
2208 """
2209 Remove annotations by annotation subtype.
2211 Args:
2212 subtypes: subtype or list of subtypes to be removed.
2213 Examples are: "/Link", "/FileAttachment", "/Sound",
2214 "/Movie", "/Screen", ...
2215 If you want to remove all annotations, use subtypes=None.
2217 """
2218 for page in self.pages:
2219 self._remove_annots_from_page(page, subtypes)
2221 def _remove_annots_from_page(
2222 self,
2223 page: IndirectObject | PageObject | DictionaryObject,
2224 subtypes: Iterable[str] | None,
2225 ) -> None:
2226 page = cast(DictionaryObject, page.get_object())
2227 if PageAttributes.ANNOTS in page:
2228 annotations = page[PageAttributes.ANNOTS]
2229 if not isinstance(annotations, ArrayObject):
2230 logger_warning(
2231 "Annotations are not an array: %(annotations)s",
2232 source=__name__,
2233 annotations=annotations,
2234 )
2235 return
2236 i = 0
2237 while i < len(annotations):
2238 an = annotations[i]
2239 obj = an.get_object()
2240 # An entry that is not a dictionary has no subtype: it is only removed with all the annotations
2241 subtype = obj.get("/Subtype") if isinstance(obj, DictionaryObject) else None
2242 if subtypes is None or (subtype is not None and subtype in subtypes):
2243 if isinstance(an, IndirectObject):
2244 self._objects[an.idnum - 1] = NullObject() # to reduce PDF size
2245 del annotations[i]
2246 else:
2247 i += 1
2249 def remove_objects_from_page(
2250 self,
2251 page: PageObject | DictionaryObject,
2252 to_delete: ObjectDeletionFlag | Iterable[ObjectDeletionFlag],
2253 text_filters: dict[str, Any] | None = None
2254 ) -> None:
2255 """
2256 Remove objects specified by ``to_delete`` from the given page.
2258 Args:
2259 page: Page object to clean up.
2260 to_delete: Objects to be deleted; can be a ``ObjectDeletionFlag``
2261 or a list of ObjectDeletionFlag
2262 text_filters: Properties of text to be deleted, if applicable. Optional.
2263 This is a Python dictionary with the following properties:
2265 * font_ids: List of font resource IDs (such as /F1 or /T1_0) to be deleted.
2267 """
2268 if isinstance(to_delete, (list, tuple)):
2269 for to_d in to_delete:
2270 self.remove_objects_from_page(page, to_d, text_filters)
2271 return
2272 assert isinstance(to_delete, ObjectDeletionFlag)
2273 if to_delete & ObjectDeletionFlag.LINKS:
2274 self._remove_annots_from_page(page, ("/Link",))
2275 if to_delete & ObjectDeletionFlag.ATTACHMENTS:
2276 self._remove_annots_from_page(
2277 page, ("/FileAttachment", "/Sound", "/Movie", "/Screen")
2278 )
2279 if to_delete & ObjectDeletionFlag.OBJECTS_3D:
2280 self._remove_annots_from_page(page, ("/3D",))
2281 if to_delete & ObjectDeletionFlag.ALL_ANNOTATIONS:
2282 self._remove_annots_from_page(page, None)
2283 if not to_delete & (ObjectDeletionFlag.TEXT | ObjectDeletionFlag.IMAGES):
2284 return
2286 jump_operators = []
2287 if to_delete & ObjectDeletionFlag.DRAWING_IMAGES:
2288 jump_operators += [
2289 b"w", b"J", b"j", b"M", b"d", b"i",
2290 b"W", b"W*",
2291 b"b", b"b*", b"B", b"B*", b"S", b"s", b"f", b"f*", b"F", b"n",
2292 b"m", b"l", b"c", b"v", b"y", b"h", b"re",
2293 b"sh"
2294 ]
2295 if to_delete & ObjectDeletionFlag.TEXT:
2296 jump_operators += list(_TEXT_SHOWING_OPERATORS)
2298 if not isinstance(page, PageObject):
2299 page = PageObject(self, page.indirect_reference) # pragma: no cover
2300 if "/Contents" in page:
2301 content = cast(ContentStream, page.get_contents())
2303 images, forms = self._remove_objects_from_page__clean_forms(
2304 elt=page, stack=[], jump_operators=jump_operators, to_delete=to_delete, text_filters=text_filters,
2305 )
2307 self._remove_objects_from_page__clean(
2308 content=content, images=images, forms=forms,
2309 jump_operators=jump_operators, to_delete=to_delete,
2310 text_filters=text_filters
2311 )
2312 page.replace_contents(content)
2313 return
2315 def _remove_objects_from_page__clean(
2316 self,
2317 content: ContentStream,
2318 images: list[str],
2319 forms: list[str],
2320 jump_operators: list[bytes],
2321 to_delete: ObjectDeletionFlag,
2322 text_filters: dict[str, Any] | None = None,
2323 ) -> None:
2324 font_id = None
2325 font_ids_to_delete = []
2326 if text_filters and to_delete & ObjectDeletionFlag.TEXT:
2327 font_ids_to_delete = text_filters.get("font_ids", [])
2329 i = 0
2330 while i < len(content.operations):
2331 operands, operator = content.operations[i]
2332 if operator == b"Tf":
2333 font_id = operands[0]
2334 if (
2335 (
2336 operator == b"INLINE IMAGE"
2337 and (to_delete & ObjectDeletionFlag.INLINE_IMAGES)
2338 )
2339 or (operator in jump_operators)
2340 or (
2341 operator == b"Do"
2342 and (to_delete & ObjectDeletionFlag.XOBJECT_IMAGES)
2343 and (operands[0] in images)
2344 )
2345 ):
2346 if (
2347 operator in _TEXT_SHOWING_OPERATORS
2348 and text_filters
2349 and font_id not in font_ids_to_delete
2350 ):
2351 i += 1
2352 else:
2353 del content.operations[i]
2354 else:
2355 i += 1
2356 content.get_data() # this ensures ._data is rebuilt from the .operations
2358 def _remove_objects_from_page__clean_forms(
2359 self,
2360 elt: DictionaryObject,
2361 stack: list[DictionaryObject],
2362 jump_operators: list[bytes],
2363 to_delete: ObjectDeletionFlag,
2364 text_filters: dict[str, Any] | None = None,
2365 ) -> tuple[list[str], list[str]]:
2366 # elt in recursive call is a new ContentStream object, so we have to check the indirect_reference
2367 if (elt in stack) or (
2368 hasattr(elt, "indirect_reference") and any(
2369 elt.indirect_reference == getattr(x, "indirect_reference", -1)
2370 for x in stack
2371 )
2372 ):
2373 # to prevent infinite looping
2374 return [], [] # pragma: no cover
2375 resources = elt.get("/Resources", NullObject()).get_object()
2376 if not isinstance(resources, DictionaryObject):
2377 if not is_null_or_none(resources):
2378 logger_warning(
2379 "Resources are not a dictionary: %(resources)s",
2380 source=__name__,
2381 resources=resources,
2382 )
2383 resources = DictionaryObject()
2384 d: dict[Any, Any] = resources.get("/XObject", DictionaryObject()).get_object()
2385 if not isinstance(d, DictionaryObject):
2386 if not is_null_or_none(d):
2387 logger_warning(
2388 "XObject resources are not a dictionary: %(x_object)s",
2389 source=__name__,
2390 x_object=d,
2391 )
2392 d = {}
2393 images = []
2394 forms = []
2395 for k, v in d.items():
2396 o = v.get_object()
2397 try:
2398 content: Any = None
2399 if (
2400 to_delete & ObjectDeletionFlag.XOBJECT_IMAGES
2401 and o["/Subtype"] == "/Image"
2402 ):
2403 content = NullObject() # to delete the image keeping the entry
2404 images.append(k)
2405 if o["/Subtype"] == "/Form":
2406 forms.append(k)
2407 if isinstance(o, ContentStream):
2408 content = o
2409 else:
2410 content = ContentStream(o, self)
2411 content.update(
2412 {
2413 k1: v1
2414 for k1, v1 in o.items()
2415 if k1 not in ["/Length", "/Filter", "/DecodeParms"]
2416 }
2417 )
2418 with contextlib.suppress(AttributeError):
2419 content.indirect_reference = o.indirect_reference
2420 stack.append(elt)
2422 # clean subforms
2423 self._remove_objects_from_page__clean_forms(
2424 elt=content, stack=stack, jump_operators=jump_operators, to_delete=to_delete,
2425 text_filters=text_filters,
2426 )
2427 if content is not None:
2428 if isinstance(v, IndirectObject):
2429 self._objects[v.idnum - 1] = content
2430 else:
2431 # should only occur in a PDF not respecting PDF spec
2432 # where streams must be indirected.
2433 d[k] = self._add_object(content) # pragma: no cover
2434 except (TypeError, KeyError):
2435 pass
2436 for im in images:
2437 del d[im] # for clean-up
2438 if isinstance(elt, StreamObject): # for /Form
2439 if not isinstance(elt, ContentStream): # pragma: no cover
2440 e = ContentStream(elt, self)
2441 e.update(elt.items())
2442 elt = e
2443 # clean the content
2444 self._remove_objects_from_page__clean(
2445 content=elt, images=images, forms=forms, jump_operators=jump_operators,
2446 to_delete=to_delete, text_filters=text_filters
2447 )
2448 return images, forms
2450 def remove_images(
2451 self,
2452 to_delete: ImageType = ImageType.ALL,
2453 ) -> None:
2454 """
2455 Remove images from this output.
2457 Args:
2458 to_delete: The type of images to be deleted
2459 (default = all images types)
2461 .. deprecated:: 7.1.0
2462 Passing a boolean as ``to_delete`` is deprecated and will be
2463 removed in pypdf 8.0.0. Use ``ImageType.ALL`` instead.
2465 """
2466 if isinstance(to_delete, bool):
2467 deprecate_with_replacement("Passing a boolean to remove_images", "ImageType.ALL", "8.0.0")
2468 to_delete = ImageType.ALL
2470 i = ObjectDeletionFlag.NONE
2472 for image in ("XOBJECT_IMAGES", "INLINE_IMAGES", "DRAWING_IMAGES"):
2473 if to_delete & ImageType[image]:
2474 i |= ObjectDeletionFlag[image]
2476 for page in self.pages:
2477 self.remove_objects_from_page(page, i)
2479 def remove_text(self, font_names: list[str] | None = None) -> None:
2480 """
2481 Remove text from the PDF.
2483 Args:
2484 font_names: List of font names to remove, such as "Helvetica-Bold".
2485 Optional. If not specified, all text will be removed.
2486 """
2487 if not font_names:
2488 font_names = []
2490 for page in self.pages:
2491 resource_ids_to_remove = []
2493 # Content streams reference fonts and other resources with names like "/F1" or "/T1_0"
2494 # Font names need to be converted to resource names/IDs for easier removal
2495 if font_names:
2496 # Recursively loop through page objects to gather font info
2497 def get_font_info(
2498 obj: Any,
2499 font_info: dict[str, Any] | None = None,
2500 key: str | None = None
2501 ) -> dict[str, Any]:
2502 if font_info is None:
2503 font_info = {}
2504 if isinstance(obj, IndirectObject):
2505 obj = obj.get_object()
2506 if isinstance(obj, dict):
2507 if obj.get("/Type") == "/Font":
2508 font_name = obj.get("/BaseFont", "")
2509 # Normalize font names like "/RRXFFV+Palatino-Bold" to "Palatino-Bold"
2510 normalized_font_name = font_name.lstrip("/").split("+")[-1]
2511 if normalized_font_name not in font_info:
2512 font_info[normalized_font_name] = {
2513 "normalized_font_name": normalized_font_name,
2514 "resource_ids": [],
2515 }
2516 if key not in font_info[normalized_font_name]["resource_ids"]:
2517 font_info[normalized_font_name]["resource_ids"].append(key)
2518 for k in obj:
2519 font_info = get_font_info(obj[k], font_info, k)
2520 elif isinstance(obj, (list, ArrayObject)):
2521 for child_obj in obj:
2522 font_info = get_font_info(child_obj, font_info)
2523 return font_info
2525 # Add relevant resource names for removal
2526 font_info = get_font_info(page.get("/Resources"))
2527 for font_name in font_names:
2528 if font_name in font_info:
2529 resource_ids_to_remove.extend(font_info[font_name]["resource_ids"])
2531 text_filters = {}
2532 if font_names:
2533 text_filters["font_ids"] = resource_ids_to_remove
2534 self.remove_objects_from_page(page, ObjectDeletionFlag.TEXT, text_filters=text_filters)
2536 def add_uri(
2537 self,
2538 page_number: int,
2539 uri: str,
2540 rect: RectangleObject,
2541 border: Sequence[Any] | None = None,
2542 ) -> None:
2543 """
2544 Add an URI from a rectangular area to the specified page.
2546 Args:
2547 page_number: index of the page on which to place the URI action.
2548 uri: URI of resource to link to.
2549 rect: :class:`RectangleObject<pypdf.generic.RectangleObject>` or
2550 array of four integers specifying the clickable rectangular area
2551 ``[xLL, yLL, xUR, yUR]``, or string in the form
2552 ``"[ xLL yLL xUR yUR ]"``.
2553 border: if provided, an array describing border-drawing
2554 properties. See the PDF spec for details. No border will be
2555 drawn if this argument is omitted.
2557 """
2558 page_link = self._get_page_reference(page_number)
2559 page_ref = cast(dict[str, Any], self.get_object(page_link))
2561 border_arr: BorderArrayType
2562 if border is not None:
2563 border_arr = [NumberObject(n) for n in border[:3]]
2564 if len(border) == 4:
2565 dash_pattern = ArrayObject([NumberObject(n) for n in border[3]])
2566 border_arr.append(dash_pattern)
2567 else:
2568 border_arr = [NumberObject(2), NumberObject(2), NumberObject(2)]
2570 if isinstance(rect, str):
2571 coords = [float(n) for n in rect.strip().strip("[]").split()]
2572 rect = RectangleObject(coords)
2573 elif isinstance(rect, RectangleObject):
2574 pass
2575 else:
2576 rect = RectangleObject(rect)
2578 lnk2 = DictionaryObject()
2579 lnk2.update(
2580 {
2581 NameObject("/S"): NameObject("/URI"),
2582 NameObject("/URI"): TextStringObject(uri),
2583 }
2584 )
2585 lnk = DictionaryObject()
2586 lnk.update(
2587 {
2588 NameObject(AnnotationDictionaryAttributes.Type): NameObject("/Annot"),
2589 NameObject(AnnotationDictionaryAttributes.Subtype): NameObject("/Link"),
2590 NameObject(AnnotationDictionaryAttributes.P): page_link,
2591 NameObject(AnnotationDictionaryAttributes.Rect): rect,
2592 NameObject("/H"): NameObject("/I"),
2593 NameObject(AnnotationDictionaryAttributes.Border): ArrayObject(border_arr),
2594 NameObject("/A"): lnk2,
2595 }
2596 )
2597 lnk_ref = self._add_object(lnk)
2599 if PageAttributes.ANNOTS in page_ref:
2600 page_ref[PageAttributes.ANNOTS].append(lnk_ref)
2601 else:
2602 page_ref[NameObject(PageAttributes.ANNOTS)] = ArrayObject([lnk_ref])
2604 _valid_layouts = (
2605 "/NoLayout",
2606 "/SinglePage",
2607 "/OneColumn",
2608 "/TwoColumnLeft",
2609 "/TwoColumnRight",
2610 "/TwoPageLeft",
2611 "/TwoPageRight",
2612 )
2614 def _get_page_layout(self) -> LayoutType | None:
2615 try:
2616 return cast(LayoutType, self._root_object[CatalogAttributes.PAGE_LAYOUT])
2617 except KeyError:
2618 return None
2620 def _set_page_layout(self, layout: NameObject | LayoutType) -> None:
2621 """
2622 Set the page layout.
2624 Args:
2625 layout: The page layout to be used.
2627 .. list-table:: Valid ``layout`` arguments
2628 :widths: 50 200
2630 * - /NoLayout
2631 - Layout explicitly not specified
2632 * - /SinglePage
2633 - Show one page at a time
2634 * - /OneColumn
2635 - Show one column at a time
2636 * - /TwoColumnLeft
2637 - Show pages in two columns, odd-numbered pages on the left
2638 * - /TwoColumnRight
2639 - Show pages in two columns, odd-numbered pages on the right
2640 * - /TwoPageLeft
2641 - Show two pages at a time, odd-numbered pages on the left
2642 * - /TwoPageRight
2643 - Show two pages at a time, odd-numbered pages on the right
2645 """
2646 if not isinstance(layout, NameObject):
2647 if layout not in self._valid_layouts:
2648 logger_warning(
2649 "Layout should be one of: %(layouts)s",
2650 source=__name__,
2651 layouts=", ".join(self._valid_layouts),
2652 )
2653 layout = NameObject(layout)
2654 self._root_object.update({NameObject(CatalogAttributes.PAGE_LAYOUT): layout})
2656 def set_page_layout(self, layout: LayoutType) -> None:
2657 """
2658 Set the page layout.
2660 Args:
2661 layout: The page layout to be used
2663 .. list-table:: Valid ``layout`` arguments
2664 :widths: 50 200
2666 * - /NoLayout
2667 - Layout explicitly not specified
2668 * - /SinglePage
2669 - Show one page at a time
2670 * - /OneColumn
2671 - Show one column at a time
2672 * - /TwoColumnLeft
2673 - Show pages in two columns, odd-numbered pages on the left
2674 * - /TwoColumnRight
2675 - Show pages in two columns, odd-numbered pages on the right
2676 * - /TwoPageLeft
2677 - Show two pages at a time, odd-numbered pages on the left
2678 * - /TwoPageRight
2679 - Show two pages at a time, odd-numbered pages on the right
2681 """
2682 self._set_page_layout(layout)
2684 @property
2685 def page_layout(self) -> LayoutType | None:
2686 """
2687 Page layout property.
2689 .. list-table:: Valid ``layout`` values
2690 :widths: 50 200
2692 * - /NoLayout
2693 - Layout explicitly not specified
2694 * - /SinglePage
2695 - Show one page at a time
2696 * - /OneColumn
2697 - Show one column at a time
2698 * - /TwoColumnLeft
2699 - Show pages in two columns, odd-numbered pages on the left
2700 * - /TwoColumnRight
2701 - Show pages in two columns, odd-numbered pages on the right
2702 * - /TwoPageLeft
2703 - Show two pages at a time, odd-numbered pages on the left
2704 * - /TwoPageRight
2705 - Show two pages at a time, odd-numbered pages on the right
2706 """
2707 return self._get_page_layout()
2709 @page_layout.setter
2710 def page_layout(self, layout: LayoutType) -> None:
2711 self._set_page_layout(layout)
2713 _valid_modes = (
2714 "/UseNone",
2715 "/UseOutlines",
2716 "/UseThumbs",
2717 "/FullScreen",
2718 "/UseOC",
2719 "/UseAttachments",
2720 )
2722 def _get_page_mode(self) -> PagemodeType | None:
2723 try:
2724 return cast(PagemodeType, self._root_object[CatalogAttributes.PAGE_MODE])
2725 except KeyError:
2726 return None
2728 @property
2729 def page_mode(self) -> PagemodeType | None:
2730 """
2731 Page mode property.
2733 .. list-table:: Valid ``mode`` values
2734 :widths: 50 200
2736 * - /UseNone
2737 - Do not show outline or thumbnails panels
2738 * - /UseOutlines
2739 - Show outline (aka bookmarks) panel
2740 * - /UseThumbs
2741 - Show page thumbnails panel
2742 * - /FullScreen
2743 - Fullscreen view
2744 * - /UseOC
2745 - Show Optional Content Group (OCG) panel
2746 * - /UseAttachments
2747 - Show attachments panel
2748 """
2749 return self._get_page_mode()
2751 @page_mode.setter
2752 def page_mode(self, mode: PagemodeType) -> None:
2753 if isinstance(mode, NameObject):
2754 mode_name: NameObject = mode
2755 else:
2756 if mode not in self._valid_modes:
2757 logger_warning(
2758 "Mode should be one of: %(modes)s",
2759 source=__name__,
2760 modes=", ".join(self._valid_modes),
2761 )
2762 mode_name = NameObject(mode)
2763 self._root_object.update({NameObject(CatalogAttributes.PAGE_MODE): mode_name})
2765 def add_annotation(
2766 self,
2767 page_number: int | PageObject,
2768 annotation: dict[str, Any],
2769 ) -> DictionaryObject:
2770 """
2771 Add a single annotation to the page.
2772 The added annotation must be a new annotation.
2773 It cannot be recycled.
2775 Args:
2776 page_number: PageObject or page index.
2777 annotation: Annotation to be added (created with annotation).
2779 Returns:
2780 The inserted object.
2781 This can be used for popup creation, for example.
2783 """
2784 page = page_number
2785 if isinstance(page, int):
2786 page = self.pages[page]
2787 elif not isinstance(page, PageObject):
2788 raise TypeError("page: invalid type")
2790 to_add = cast(DictionaryObject, _pdf_objectify(annotation))
2791 to_add[NameObject("/P")] = page.indirect_reference
2793 if page.annotations is None:
2794 page[NameObject("/Annots")] = ArrayObject()
2795 assert page.annotations is not None
2797 # Resolve pypdf's intermediate internal-link destination.
2798 destination = to_add.get("/Dest")
2799 if (
2800 to_add.get("/Subtype") == "/Link"
2801 and isinstance(destination, DictionaryObject)
2802 and "target_page_index" in destination
2803 ):
2804 target_page_reference: IndirectObject | NumberObject
2805 target_page_index = cast(int, destination["target_page_index"])
2806 fit_type = cast(str, destination["fit"])
2807 # Work around the intermediate destination containing native Python
2808 # objects instead of PdfObject instances.
2809 fit_args = cast(Sequence[Any], dict(destination)["fit_args"])
2811 if 0 <= target_page_index < len(self.pages):
2812 target_page_reference = cast(
2813 IndirectObject,
2814 self.pages[target_page_index].indirect_reference,
2815 )
2816 else:
2817 # Preserve support for referencing a page that may be added
2818 # later. See #2450.
2819 target_page_reference = NumberObject(target_page_index)
2821 to_add[NameObject("/Dest")] = Destination(
2822 NameObject("/LinkName"),
2823 target_page_reference,
2824 Fit(fit_type=fit_type, fit_args=fit_args),
2825 ).dest_array
2827 page.annotations.append(self._add_object(to_add))
2829 if to_add.get("/Subtype") == "/Popup" and NameObject("/Parent") in to_add:
2830 cast(DictionaryObject, to_add["/Parent"].get_object())[
2831 NameObject("/Popup")
2832 ] = to_add.indirect_reference
2834 return to_add
2836 def clean_page(self, page: PageObject | IndirectObject) -> PageObject:
2837 """
2838 Perform some clean up in the page.
2839 Currently: convert NameObject named destination to TextStringObject
2840 (required for names/dests list)
2842 Args:
2843 page:
2845 Returns:
2846 The cleaned PageObject
2848 """
2849 page = cast("PageObject", page.get_object())
2850 for a in page.get("/Annots", []):
2851 a_obj = a.get_object()
2852 d = a_obj.get("/Dest", None)
2853 act = a_obj.get("/A", None)
2854 if isinstance(d, NameObject):
2855 a_obj[NameObject("/Dest")] = TextStringObject(d)
2856 elif act is not None:
2857 act = act.get_object()
2858 d = act.get("/D", None)
2859 if isinstance(d, NameObject):
2860 act[NameObject("/D")] = TextStringObject(d)
2861 return page
2863 def _create_stream(self, fileobj: Path | StrByteType) -> IOBase:
2864 # If the fileobj parameter is a string, assume it is a path
2865 # and create a file object at that location. If it is a file,
2866 # copy the file's contents into a BytesIO stream object.
2867 stream: IOBase
2868 if isinstance(fileobj, (str, Path)):
2869 with FileIO(fileobj, "rb") as f:
2870 stream = BytesIO(f.read())
2871 elif hasattr(fileobj, "seek") and hasattr(fileobj, "read"):
2872 fileobj.seek(0)
2873 filecontent = fileobj.read()
2874 stream = BytesIO(filecontent)
2875 else:
2876 raise NotImplementedError(
2877 "Merging requires an object that PdfReader can parse. "
2878 "Typically, that is a Path or a string representing a Path, "
2879 "a file object, or an object implementing .seek and .read. "
2880 "Passing a PdfReader directly works as well."
2881 )
2882 return stream
2884 def append(
2885 self,
2886 fileobj: StrByteType | PdfReader | Path,
2887 outline_item: str | PageRange | tuple[int, int] | tuple[int, int, int] | list[int] | None = None,
2888 pages: PageRange | tuple[int, int] | tuple[int, int, int] | list[int] | list[PageObject] | None = None,
2889 import_outline: bool = True,
2890 excluded_fields: list[str] | tuple[str, ...] | None = None,
2891 ) -> None:
2892 """
2893 Identical to the :meth:`merge()<merge>` method, but assumes you want to
2894 concatenate all pages onto the end of the file instead of specifying a
2895 position.
2897 Args:
2898 fileobj: A File Object or an object that supports the standard
2899 read and seek methods similar to a File Object. Could also be a
2900 string representing a path to a PDF file.
2901 outline_item: Optionally, you may specify a string to build an
2902 outline (aka 'bookmark') to identify the beginning of the
2903 included file.
2904 pages: Can be a :class:`PageRange<pypdf.pagerange.PageRange>`
2905 or a ``(start, stop[, step])`` tuple
2906 or a list of pages to be processed
2907 to merge only the specified range of pages from the source
2908 document into the output document.
2909 import_outline: You may prevent the source document's
2910 outline (collection of outline items, previously referred to as
2911 'bookmarks') from being imported by specifying this as ``False``.
2912 excluded_fields: Provide the list of fields/keys to be ignored
2913 if ``/Annots`` is part of the list, the annotation will be ignored
2914 if ``/B`` is part of the list, the articles will be ignored
2916 """
2917 if excluded_fields is None:
2918 excluded_fields = ()
2919 if isinstance(outline_item, (tuple, list, PageRange)):
2920 if isinstance(pages, bool):
2921 if not isinstance(import_outline, bool):
2922 excluded_fields = import_outline
2923 import_outline = pages
2924 pages = outline_item
2925 self.merge(
2926 None,
2927 fileobj,
2928 None,
2929 pages,
2930 import_outline,
2931 excluded_fields,
2932 )
2933 else: # if isinstance(outline_item, str):
2934 self.merge(
2935 None,
2936 fileobj,
2937 outline_item,
2938 pages,
2939 import_outline,
2940 excluded_fields,
2941 )
2943 def merge(
2944 self,
2945 position: int | None,
2946 fileobj: Path | StrByteType | PdfReader,
2947 outline_item: str | None = None,
2948 pages: PageRangeSpec | list[PageObject] | None = None,
2949 import_outline: bool = True,
2950 excluded_fields: list[str] | tuple[str, ...] | None = (),
2951 ) -> None:
2952 """
2953 Merge the pages from the given file into the output file at the
2954 specified page number.
2956 Args:
2957 position: The *page number* to insert this file. File will
2958 be inserted after the given number.
2959 fileobj: A File Object or an object that supports the standard
2960 read and seek methods similar to a File Object. Could also be a
2961 string representing a path to a PDF file.
2962 outline_item: Optionally, you may specify a string to build an outline
2963 (aka 'bookmark') to identify the
2964 beginning of the included file.
2965 pages: can be a :class:`PageRange<pypdf.pagerange.PageRange>`
2966 or a ``(start, stop[, step])`` tuple
2967 or a list of pages to be processed
2968 to merge only the specified range of pages from the source
2969 document into the output document.
2970 import_outline: You may prevent the source document's
2971 outline (collection of outline items, previously referred to as
2972 'bookmarks') from being imported by specifying this as ``False``.
2973 excluded_fields: provide the list of fields/keys to be ignored
2974 if ``/Annots`` is part of the list, the annotation will be ignored
2975 if ``/B`` is part of the list, the articles will be ignored
2977 Raises:
2978 TypeError: The pages attribute is not configured properly
2980 """
2981 if isinstance(fileobj, PdfDocCommon):
2982 reader = fileobj
2983 else:
2984 stream = self._create_stream(fileobj)
2985 # Create a new PdfReader instance using the stream
2986 # (either file or BytesIO or StringIO) created above
2987 reader = PdfReader(stream, strict=False) # type: ignore[arg-type]
2989 if excluded_fields is None:
2990 excluded_fields = ()
2991 # Find the range of pages to merge.
2992 if pages is None:
2993 pages = list(range(len(reader.pages)))
2994 elif isinstance(pages, PageRange):
2995 pages = list(range(*pages.indices(len(reader.pages))))
2996 elif isinstance(pages, list):
2997 pass # keep unchanged
2998 elif isinstance(pages, tuple) and len(pages) <= 3:
2999 pages = list(range(*pages))
3000 elif not isinstance(pages, tuple):
3001 raise TypeError(
3002 '"pages" must be a tuple of (start, stop[, step]) or a list'
3003 )
3005 srcpages = {}
3006 for page in pages:
3007 if isinstance(page, PageObject):
3008 pg = page
3009 else:
3010 pg = reader.pages[page]
3011 assert pg.indirect_reference is not None
3012 if position is None:
3013 # numbers in the exclude list identifies that the exclusion is
3014 # only applicable to 1st level of cloning
3015 srcpages[pg.indirect_reference.idnum] = self.add_page(
3016 pg, [*list(excluded_fields), 1, "/B", 1, "/Annots"] # type: ignore[list-item]
3017 )
3018 else:
3019 srcpages[pg.indirect_reference.idnum] = self.insert_page(
3020 pg, position, [*list(excluded_fields), 1, "/B", 1, "/Annots"] # type: ignore[list-item]
3021 )
3022 position += 1
3023 srcpages[pg.indirect_reference.idnum].original_page = pg
3025 reader._named_destinations = (
3026 reader.named_destinations
3027 ) # need for the outline processing below
3029 arr: Any
3031 named_destinations = _NamedDestinationIndex(
3032 is_enabled=len(reader._named_destinations) >= _NAMED_DESTINATION_INDEX_MINIMUM
3033 )
3034 # Keep the destinations added before an error, as adding them one by one did.
3035 try:
3036 for dest in reader._named_destinations.values():
3037 self._merge__process_named_dests(
3038 dest=dest, reader=reader, srcpages=srcpages, named_destinations=named_destinations
3039 )
3040 finally:
3041 named_destinations.flush()
3043 outline_item_typ: TreeObject
3044 if outline_item is not None:
3045 outline_item_typ = cast(
3046 "TreeObject",
3047 self.add_outline_item(
3048 title=TextStringObject(outline_item),
3049 page_number=next(iter(srcpages.values())).indirect_reference,
3050 fit=PAGE_FIT,
3051 ).get_object(),
3052 )
3053 else:
3054 outline_item_typ = self.get_outline_root()
3056 _ro = reader.root_object
3057 if import_outline and Core.OUTLINES in _ro:
3058 outline = self._get_filtered_outline(
3059 node=_ro.get(Core.OUTLINES, None), pages=srcpages, reader=reader
3060 )
3061 self._insert_filtered_outline(
3062 outline, outline_item_typ, None
3063 ) # TODO: use before parameter
3065 if "/Annots" not in excluded_fields:
3066 parent_fields: dict[int, DictionaryObject] = {}
3067 for pag in srcpages.values():
3068 lst = self._insert_filtered_annotations(
3069 annots=pag.original_page.get("/Annots", []),
3070 page=pag,
3071 pages=srcpages,
3072 reader=reader,
3073 parent_fields=parent_fields,
3074 )
3075 if len(lst) > 0:
3076 pag[NameObject("/Annots")] = lst
3077 self.clean_page(pag)
3078 self._set_cloned_kids(parent_fields, reader)
3080 acro_form = _ro.get("/AcroForm")
3081 if acro_form is not None:
3082 acro_form = acro_form.get_object()
3083 if not is_null_or_none(acro_form) and not isinstance(acro_form, DictionaryObject):
3084 logger_warning(
3085 "AcroForm is not a dictionary: %(acro_form)s",
3086 source=__name__,
3087 acro_form=acro_form,
3088 )
3089 if isinstance(acro_form, DictionaryObject):
3090 writer_acro_form = self._root_object.get("/AcroForm")
3091 if writer_acro_form is None or not isinstance(writer_acro_form.get_object(), DictionaryObject):
3092 self._root_object[NameObject("/AcroForm")] = self._add_object(
3093 acro_form.clone(self, False, ("/Fields",))
3094 )
3095 arr = ArrayObject()
3096 else:
3097 arr = cast(DictionaryObject, writer_acro_form.get_object()).get("/Fields", ArrayObject()).get_object()
3098 if not isinstance(arr, ArrayObject):
3099 arr = ArrayObject()
3100 fields = acro_form.get("/Fields", ArrayObject()).get_object()
3101 if not isinstance(fields, ArrayObject):
3102 logger_warning(
3103 "AcroForm /Fields is not an array: %(fields)s",
3104 source=__name__,
3105 fields=fields,
3106 )
3107 fields = ArrayObject()
3108 trslat = self._id_translated[id(reader)]
3109 known = {
3110 x.idnum for x in arr if isinstance(x, IndirectObject) and x.generation == 0 and x.pdf is self
3111 }
3112 for f in fields:
3113 # trslat only knows the fields which have been copied through the pages
3114 if isinstance(f, IndirectObject) and f.idnum in trslat and trslat[f.idnum] not in known:
3115 known.add(trslat[f.idnum])
3116 arr.append(IndirectObject(trslat[f.idnum], 0, self))
3117 cast(DictionaryObject, self._root_object["/AcroForm"])[
3118 NameObject("/Fields")
3119 ] = arr
3121 if "/B" not in excluded_fields:
3122 self.add_filtered_articles("", srcpages, reader)
3124 def _merge__process_named_dests(
3125 self,
3126 dest: Any,
3127 reader: PdfDocCommon,
3128 srcpages: dict[int, PageObject],
3129 named_destinations: _NamedDestinationIndex,
3130 ) -> None:
3131 arr: Any = dest.dest_array
3132 if "/Names" in self._root_object and named_destinations.contains(self.get_named_dest_root(), dest["/Title"]):
3133 # already exists: should not duplicate it
3134 pass
3135 elif dest["/Page"] is None or isinstance(dest["/Page"], NullObject):
3136 pass
3137 elif isinstance(dest["/Page"], int):
3138 # the page reference is a page number normally not a PDF Reference
3139 # page numbers as int are normally accepted only in external goto
3140 try:
3141 p = reader.pages[dest["/Page"]]
3142 except IndexError:
3143 return
3144 assert p.indirect_reference is not None
3145 try:
3146 arr[NumberObject(0)] = NumberObject(
3147 srcpages[p.indirect_reference.idnum].page_number
3148 )
3149 self._add_named_destination_array_indexed(dest["/Title"], arr, named_destinations)
3150 except KeyError:
3151 pass
3152 elif dest["/Page"].indirect_reference.idnum in srcpages:
3153 arr[NumberObject(0)] = srcpages[
3154 dest["/Page"].indirect_reference.idnum
3155 ].indirect_reference
3156 self._add_named_destination_array_indexed(dest["/Title"], arr, named_destinations)
3158 def _add_named_destination_array_indexed(
3159 self, title: Any, destination: Any, named_destinations: _NamedDestinationIndex
3160 ) -> None:
3161 names = self.get_named_dest_root()
3162 if not named_destinations.insert(names, title, destination):
3163 self.add_named_destination_array(title, destination)
3164 named_destinations.record_insertion(names, title)
3166 def _add_articles_thread(
3167 self,
3168 thread: DictionaryObject,
3169 pages: dict[int, PageObject],
3170 reader: PdfReader,
3171 ) -> IndirectObject:
3172 """
3173 Clone the thread with only the applicable articles.
3175 Args:
3176 thread: Thread entry from the reader's array of threads
3177 pages: Mapping of object numbers to page objects.
3178 reader: The corresponding reader.
3180 Returns:
3181 The added thread as an indirect reference
3183 """
3184 new_thread = thread.clone(
3185 self, force_duplicate=True, ignore_fields=("/F",)
3186 ) # use of clone to keep link between reader and writer
3187 self.threads.append(new_thread.indirect_reference)
3188 first_article = cast("DictionaryObject", thread["/F"])
3189 current_article: DictionaryObject | None = first_article
3190 new_article: DictionaryObject | None = None
3192 visited: set[int] = set()
3193 while current_article is not None:
3194 article_id = id(current_article)
3195 if article_id in visited:
3196 raise LimitReachedError("Detected cyclic article structure.")
3197 visited.add(article_id)
3199 page = self._get_cloned_page(
3200 cast("PageObject", current_article.get("/P", NullObject()).get_object()),
3201 pages,
3202 reader,
3203 )
3204 if page is not None:
3205 if new_article is None:
3206 new_article = cast(
3207 "DictionaryObject",
3208 self._add_object(DictionaryObject()).get_object(),
3209 )
3210 new_first = new_article
3211 new_thread[NameObject("/F")] = new_article.indirect_reference
3212 else:
3213 new_article2 = cast(
3214 "DictionaryObject",
3215 self._add_object(
3216 DictionaryObject(
3217 {NameObject("/V"): new_article.indirect_reference}
3218 )
3219 ).get_object(),
3220 )
3221 new_article[NameObject("/N")] = new_article2.indirect_reference
3222 new_article = new_article2
3223 new_article[NameObject("/P")] = page
3224 new_article[NameObject("/T")] = new_thread.indirect_reference
3225 new_article[NameObject("/R")] = current_article["/R"]
3226 page_object = cast("PageObject", page.get_object())
3227 if "/B" not in page_object:
3228 page_object[NameObject("/B")] = ArrayObject()
3229 cast("ArrayObject", page_object["/B"]).append(
3230 new_article.indirect_reference
3231 )
3233 current_article = cast("DictionaryObject", current_article["/N"])
3234 if current_article == first_article:
3235 new_article[NameObject("/N")] = new_first.indirect_reference # type: ignore[index]
3236 new_first[NameObject("/V")] = new_article.indirect_reference # type: ignore[union-attr]
3237 current_article = None
3239 assert new_thread.indirect_reference is not None
3240 return new_thread.indirect_reference
3242 def add_filtered_articles(
3243 self,
3244 fltr: (
3245 Pattern[Any] | str
3246 ), # thread entry from the reader's array of threads
3247 pages: dict[int, PageObject],
3248 reader: PdfReader,
3249 ) -> None:
3250 """
3251 Add articles matching the defined criteria.
3253 Args:
3254 fltr:
3255 pages:
3256 reader:
3258 """
3259 if isinstance(fltr, str):
3260 fltr = re.compile(fltr)
3261 elif not isinstance(fltr, Pattern):
3262 fltr = re.compile("")
3263 for p in pages.values():
3264 pp = p.original_page
3265 for a in pp.get("/B", ()):
3266 a_obj = a.get_object()
3267 if is_null_or_none(a_obj):
3268 continue
3269 thr = a_obj.get("/T")
3270 if thr is None:
3271 continue
3272 thr = thr.get_object()
3273 if thr.indirect_reference.idnum not in self._id_translated[
3274 id(reader)
3275 ] and fltr.search((thr.get("/I", {})).get("/Title", "")):
3276 self._add_articles_thread(thr, pages, reader)
3278 def _get_cloned_page(
3279 self,
3280 page: IndirectObject | PageObject | NullObject | int | None,
3281 pages: dict[int, PageObject],
3282 reader: PdfReader,
3283 ) -> IndirectObject | None:
3284 if isinstance(page, NullObject):
3285 return None
3286 if isinstance(page, int):
3287 # An explicit destination may reference the target page by its
3288 # (zero-based) index in the source document rather than by an
3289 # indirect reference; this is what `Link(target_page_index=...)`
3290 # produces. Resolve the index through the reader's page list so it
3291 # can be remapped like a regular page reference. A destination that
3292 # points past the end of the source document is dropped.
3293 try:
3294 page = reader.pages[page].indirect_reference
3295 except IndexError:
3296 return None
3297 if isinstance(page, DictionaryObject) and page.get("/Type", "") == "/Page":
3298 _i = page.indirect_reference
3299 elif isinstance(page, IndirectObject):
3300 _i = page
3301 try:
3302 return pages[_i.idnum].indirect_reference # type: ignore[union-attr]
3303 except MemoryError: # pragma: no cover # TODO: BLE001
3304 raise
3305 except Exception:
3306 return None
3308 def _insert_filtered_annotations(
3309 self,
3310 *,
3311 annots: IndirectObject | list[PdfObject] | None,
3312 page: PageObject,
3313 pages: dict[int, PageObject],
3314 reader: PdfReader,
3315 parent_fields: dict[int, DictionaryObject] | None = None,
3316 ) -> list[Destination]:
3317 outlist = ArrayObject()
3318 if isinstance(annots, IndirectObject):
3319 annots = cast("list[Any]", annots.get_object())
3320 if annots is None:
3321 return outlist
3322 if not isinstance(annots, list):
3323 logger_warning(
3324 "Expected list of annotations, got %(annots)s of type %(annots_type)s.",
3325 source=__name__,
3326 annots=annots,
3327 annots_type=annots.__class__.__name__,
3328 )
3329 return outlist
3330 configuration = get_configuration()
3331 if len(annots) > configuration.annotations_maximum_per_page:
3332 raise LimitReachedError(
3333 f"Maximum annotations per page exceeded: "
3334 f"{len(annots)} > {configuration.annotations_maximum_per_page}."
3335 )
3336 for an in annots:
3337 ano = cast("DictionaryObject", an.get_object())
3338 if (
3339 ano.get("/Subtype") != "/Link"
3340 or "/A" not in ano
3341 or cast("DictionaryObject", ano["/A"])["/S"] != "/GoTo" # type: ignore[comparison-overlap]
3342 or "/Dest" in ano
3343 ):
3344 if (
3345 parent_fields is not None
3346 and ano.get("/Subtype") == "/Widget"
3347 and isinstance(ano.get("/Parent"), IndirectObject)
3348 ):
3349 outlist.append(self._clone_widget_annotation(ano, parent_fields))
3350 elif "/Dest" not in ano:
3351 outlist.append(self._add_object(ano.clone(self)))
3352 else:
3353 d = ano["/Dest"]
3354 if isinstance(d, str):
3355 # it is a named dest
3356 if str(d) in self.get_named_dest_root():
3357 outlist.append(ano.clone(self).indirect_reference)
3358 else:
3359 if not isinstance(d, ArrayObject) or not d:
3360 continue
3361 p = self._get_cloned_page(d[0], pages, reader)
3362 if p is not None:
3363 anc = ano.clone(self, ignore_fields=("/Dest",))
3364 anc[NameObject("/Dest")] = ArrayObject([p, *d[1:]])
3365 outlist.append(self._add_object(anc))
3366 else:
3367 d = cast("DictionaryObject", ano["/A"]).get("/D", NullObject())
3368 if is_null_or_none(d):
3369 continue
3370 if isinstance(d, str):
3371 # it is a named dest
3372 if str(d) in self.get_named_dest_root():
3373 outlist.append(ano.clone(self).indirect_reference)
3374 else:
3375 if not isinstance(d, ArrayObject) or not d:
3376 continue
3377 p = self._get_cloned_page(d[0], pages, reader)
3378 if p is not None:
3379 anc = ano.clone(self, ignore_fields=("/D",))
3380 cast("DictionaryObject", anc["/A"])[
3381 NameObject("/D")
3382 ] = ArrayObject([p, *d[1:]])
3383 outlist.append(self._add_object(anc))
3384 return outlist
3386 def _clone_widget_annotation(
3387 self, annotation: DictionaryObject, parent_fields: dict[int, DictionaryObject]
3388 ) -> IndirectObject:
3389 """
3390 Clone a widget annotation and link it to its parent fields.
3392 Cloning ``/Parent`` directly would also clone the ``/Kids`` of the
3393 parent fields, and with them the widgets and pages of sibling fields
3394 which are not part of the merge. Instead, the parent fields are cloned
3395 without ``/Kids`` and collected in ``parent_fields``, so that their kids
3396 can be set by :meth:`_set_cloned_kids` once all annotations are cloned.
3397 """
3398 clone = annotation.clone(self, ignore_fields=(1, "/Parent"))
3399 source, target = annotation, clone
3400 while isinstance(source.get("/Parent"), IndirectObject):
3401 parent_reference = cast(IndirectObject, source.get("/Parent"))
3402 source_parent = parent_reference.get_object()
3403 if not isinstance(source_parent, DictionaryObject):
3404 break
3405 parent = source_parent.clone(self, ignore_fields=(1, "/Kids", 1, "/Parent"))
3406 target[NameObject("/Parent")] = parent.indirect_reference
3407 if parent_reference.idnum in parent_fields:
3408 # The ancestors have already been linked.
3409 break
3410 parent_fields[parent_reference.idnum] = source_parent
3411 source, target = source_parent, parent
3412 assert clone.indirect_reference is not None
3413 return clone.indirect_reference
3415 def _set_cloned_kids(self, parent_fields: dict[int, DictionaryObject], reader: PdfReader) -> None:
3416 """Set the ``/Kids`` of the cloned parent fields to the cloned kids, in their original order."""
3417 translated = self._id_translated.get(id(reader), {})
3418 for idnum, source_parent in parent_fields.items():
3419 kids = source_parent.get("/Kids", ArrayObject())
3420 parent = cast(DictionaryObject, self.get_object(translated[idnum]))
3421 parent[NameObject("/Kids")] = ArrayObject(
3422 IndirectObject(translated[kid.idnum], 0, self)
3423 for kid in cast(ArrayObject, kids)
3424 if isinstance(kid, IndirectObject) and kid.idnum in translated
3425 )
3427 def _get_filtered_outline(
3428 self,
3429 *,
3430 node: Any,
3431 pages: dict[int, PageObject],
3432 reader: PdfReader,
3433 visited: set[int] | None = None,
3434 ) -> list[Destination]:
3435 """
3436 Extract outline item entries that are part of the specified page set.
3438 Returns:
3439 A list of destination objects.
3441 """
3442 if visited is None:
3443 visited = set()
3444 new_outline: list[Destination] = []
3445 if node is None:
3446 return new_outline
3447 node = node.get_object()
3448 if is_null_or_none(node):
3449 node = DictionaryObject()
3450 if not isinstance(node, DictionaryObject):
3451 logger_warning("Outline node is not a dictionary: %(node)s", source=__name__, node=node)
3452 return new_outline
3454 if node.get("/Type", "") == "/Outlines" or "/Title" not in node:
3455 node_id = id(node)
3456 if node_id in visited:
3457 logger_warning("Detected cycle in outlines.", source=__name__)
3458 return []
3459 visited.add(node_id)
3461 node = node.get("/First", None)
3462 if node is not None:
3463 node = node.get_object()
3464 new_outline += self._get_filtered_outline(node=node, pages=pages, reader=reader, visited=visited)
3465 else:
3466 cloned_page: IndirectObject | NullObject | None
3467 while True:
3468 node = node.get_object()
3469 if not isinstance(node, DictionaryObject):
3470 logger_warning("Outline node is not a dictionary: %(node)s", source=__name__, node=node)
3471 break
3472 node_id = id(node)
3473 if node_id in visited:
3474 logger_warning("Detected cycle in outlines.", source=__name__)
3475 break
3476 visited.add(node_id)
3478 destination = cast("Destination", reader._build_outline_item(node))
3479 cloned_page = self._get_cloned_page(cast("PageObject", destination["/Page"]), pages, reader)
3480 if cloned_page is None:
3481 cloned_page = NullObject()
3482 destination[NameObject("/Page")] = cloned_page
3483 if "/First" in node:
3484 destination._filtered_children = self._get_filtered_outline(
3485 node=node["/First"], pages=pages, reader=reader, visited=visited
3486 )
3487 else:
3488 destination._filtered_children = []
3489 if (
3490 not isinstance(cloned_page, NullObject)
3491 or len(destination._filtered_children) > 0
3492 ):
3493 new_outline.append(destination)
3495 if "/Next" not in node:
3496 break
3497 node = node["/Next"]
3498 return new_outline
3500 def _clone_outline(self, dest: Destination) -> TreeObject:
3501 n_ol = TreeObject()
3502 self._add_object(n_ol)
3503 n_ol[NameObject("/Title")] = TextStringObject(dest["/Title"])
3504 if not isinstance(dest["/Page"], NullObject):
3505 if dest.node is not None and "/A" in dest.node:
3506 n_ol[NameObject("/A")] = dest.node["/A"].clone(self)
3507 else:
3508 n_ol[NameObject("/Dest")] = dest.dest_array
3509 # TODO: /SE
3510 if dest.node is not None:
3511 n_ol[NameObject("/F")] = NumberObject(dest.node.get("/F", 0))
3512 color = dest.node.get("/C", NullObject()).get_object()
3513 if not isinstance(color, list):
3514 color = [FloatObject(0.0), FloatObject(0.0), FloatObject(0.0)]
3515 n_ol[NameObject("/C")] = ArrayObject(color)
3516 return n_ol
3518 def _insert_filtered_outline(
3519 self,
3520 outlines: list[Destination],
3521 parent: TreeObject | IndirectObject,
3522 before: IndirectObject | None = None,
3523 ) -> None:
3524 for dest in outlines:
3525 # TODO: can be improved to keep A and SE entries (ignored for the moment)
3526 # with np=self.add_outline_item_destination(dest,parent,before)
3527 if dest.get("/Type", "") == "/Outlines" or "/Title" not in dest:
3528 np = parent
3529 else:
3530 np = self._clone_outline(dest)
3531 cast(TreeObject, parent.get_object()).insert_child(np, before, self)
3532 self._insert_filtered_outline(dest._filtered_children, np, None)
3534 def close(self) -> None:
3535 """Implemented for API harmonization."""
3536 return
3538 def find_outline_item(
3539 self,
3540 outline_item: IndirectObject | str,
3541 root: OutlineType | None = None,
3542 *,
3543 visited: set[int] | None = None,
3544 ) -> list[int] | None:
3545 if root is None:
3546 outline = self.get_outline_root()
3547 else:
3548 outline = cast("TreeObject", root)
3549 if visited is None:
3550 visited = set()
3552 index = 0
3553 while outline is not None:
3554 if (
3555 outline.indirect_reference == outline_item
3556 or outline.get("/Title", None) == outline_item
3557 ):
3558 return [index]
3560 outline_id = id(outline)
3561 if outline_id in visited:
3562 raise LimitReachedError("Detected cyclic outline hierarchy.")
3563 visited.add(outline_id)
3565 if "/First" in outline:
3566 result = self.find_outline_item(
3567 outline_item=outline_item,
3568 root=cast(OutlineType, outline["/First"]),
3569 visited=visited,
3570 )
3571 if result:
3572 return ([index] if "/Title" in outline else []) + result
3573 if "/Next" in outline:
3574 index += 1
3575 outline = cast(TreeObject, outline["/Next"])
3576 else:
3577 return None
3578 raise PyPdfError("This line is theoretically unreachable.") # pragma: no cover
3580 def reset_translation(
3581 self, reader: PdfReader | IndirectObject | None = None
3582 ) -> None:
3583 """
3584 Reset the translation table between reader and the writer object.
3586 Late cloning will create new independent objects.
3588 Args:
3589 reader: PdfReader or IndirectObject referencing a PdfReader object.
3590 if set to None or omitted, all tables will be reset.
3592 """
3593 if reader is None:
3594 self._id_translated = {}
3595 elif isinstance(reader, PdfReader):
3596 try:
3597 del self._id_translated[id(reader)]
3598 except MemoryError: # pragma: no cover # TODO: BLE001
3599 raise
3600 except Exception:
3601 pass
3602 elif isinstance(reader, IndirectObject):
3603 try:
3604 del self._id_translated[id(reader.pdf)]
3605 except MemoryError: # pragma: no cover # TODO: BLE001
3606 raise
3607 except Exception:
3608 pass
3609 else:
3610 raise TypeError(f"Invalid parameter {reader}")
3612 def set_page_label(
3613 self,
3614 page_index_from: int,
3615 page_index_to: int,
3616 style: PageLabelStyle | None = None,
3617 prefix: str | None = None,
3618 start: int | None = 0,
3619 ) -> None:
3620 """
3621 Set a page label to a range of pages.
3623 Page indexes must be given starting from 0.
3624 Labels must have a style, a prefix or both.
3625 If a range is not assigned any page label, a decimal label starting from 1 is applied.
3627 Args:
3628 page_index_from: page index of the beginning of the range starting from 0
3629 page_index_to: page index of the beginning of the range starting from 0
3630 style: The numbering style to be used for the numeric portion of each page label:
3632 * ``/D`` Decimal Arabic numerals
3633 * ``/R`` Uppercase Roman numerals
3634 * ``/r`` Lowercase Roman numerals
3635 * ``/A`` Uppercase letters (A to Z for the first 26 pages,
3636 AA to ZZ for the next 26, and so on)
3637 * ``/a`` Lowercase letters (a to z for the first 26 pages,
3638 aa to zz for the next 26, and so on)
3640 prefix: The label prefix for page labels in this range.
3641 start: The value of the numeric portion for the first page label
3642 in the range.
3643 Subsequent pages are numbered sequentially from this value,
3644 which must be greater than or equal to 1.
3645 Default value: 1.
3647 """
3648 if style is None and prefix is None:
3649 raise ValueError("At least one of style and prefix must be given")
3650 if style is not None and style not in tuple(PageLabelStyle):
3651 raise ValueError(
3652 f"style must be one of: {', '.join(PageLabelStyle)}, got {style!r}"
3653 )
3654 if page_index_from < 0:
3655 raise ValueError("page_index_from must be greater or equal than 0")
3656 if page_index_to < page_index_from:
3657 raise ValueError(
3658 "page_index_to must be greater or equal than page_index_from"
3659 )
3660 if page_index_to >= len(self.pages):
3661 raise ValueError("page_index_to exceeds number of pages")
3662 if start is not None and start != 0 and start < 1:
3663 raise ValueError("If given, start must be greater or equal than one")
3665 self._set_page_label(page_index_from, page_index_to, style, prefix, start)
3667 def _set_page_label(
3668 self,
3669 page_index_from: int,
3670 page_index_to: int,
3671 style: PageLabelStyle | None = None,
3672 prefix: str | None = None,
3673 start: int | None = 0,
3674 ) -> None:
3675 """
3676 Set a page label to a range of pages.
3678 Page indexes must be given starting from 0.
3679 Labels must have a style, a prefix or both.
3680 If a range is not assigned any page label a decimal label starting from 1 is applied.
3682 Args:
3683 page_index_from: page index of the beginning of the range starting from 0
3684 page_index_to: page index of the beginning of the range starting from 0
3685 style: The numbering style to be used for the numeric portion of each page label:
3686 /D Decimal Arabic numerals
3687 /R Uppercase Roman numerals
3688 /r Lowercase Roman numerals
3689 /A Uppercase letters (A to Z for the first 26 pages,
3690 AA to ZZ for the next 26, and so on)
3691 /a Lowercase letters (a to z for the first 26 pages,
3692 aa to zz for the next 26, and so on)
3693 prefix: The label prefix for page labels in this range.
3694 start: The value of the numeric portion for the first page label
3695 in the range.
3696 Subsequent pages are numbered sequentially from this value,
3697 which must be greater than or equal to 1. Default value: 1.
3699 """
3700 default_page_label = DictionaryObject()
3701 default_page_label[NameObject("/S")] = NameObject("/D")
3703 new_page_label = DictionaryObject()
3704 if style is not None:
3705 new_page_label[NameObject("/S")] = NameObject(style)
3706 if prefix is not None:
3707 new_page_label[NameObject("/P")] = TextStringObject(prefix)
3708 if start is not None and start != 0:
3709 new_page_label[NameObject("/St")] = NumberObject(start)
3711 if NameObject(CatalogAttributes.PAGE_LABELS) not in self._root_object:
3712 nums = ArrayObject()
3713 nums_insert(NumberObject(0), default_page_label, nums)
3714 page_labels = TreeObject()
3715 page_labels[NameObject("/Nums")] = nums
3716 self._root_object[NameObject(CatalogAttributes.PAGE_LABELS)] = page_labels
3718 page_labels = cast(
3719 TreeObject, self._root_object[NameObject(CatalogAttributes.PAGE_LABELS)]
3720 )
3721 nums = cast(ArrayObject, page_labels[NameObject("/Nums")])
3723 nums_insert(NumberObject(page_index_from), new_page_label, nums)
3724 nums_clear_range(NumberObject(page_index_from), page_index_to, nums)
3725 next_label_pos, *_ = nums_next(NumberObject(page_index_from), nums)
3726 if next_label_pos != page_index_to + 1 and page_index_to + 1 < len(self.pages):
3727 nums_insert(NumberObject(page_index_to + 1), default_page_label, nums)
3729 page_labels[NameObject("/Nums")] = nums
3730 self._root_object[NameObject(CatalogAttributes.PAGE_LABELS)] = page_labels
3732 def _get_pdf_bytes(self) -> bytes:
3733 """Write the document into memory and return its bytes."""
3734 pdf_data = BytesIO()
3735 self.write(pdf_data)
3736 return pdf_data.getvalue()
3739def _pdf_objectify(obj: dict[str, Any] | str | float | list[Any]) -> PdfObject:
3740 if isinstance(obj, PdfObject):
3741 return obj
3742 if isinstance(obj, dict):
3743 to_add = DictionaryObject()
3744 for key, value in obj.items():
3745 to_add[NameObject(key)] = _pdf_objectify(value)
3746 return to_add
3747 if isinstance(obj, str):
3748 if obj.startswith("/"):
3749 return NameObject(obj)
3750 return TextStringObject(obj)
3751 if isinstance(obj, (float, int)):
3752 return FloatObject(obj)
3753 if isinstance(obj, list):
3754 return ArrayObject(_pdf_objectify(i) for i in obj)
3755 raise NotImplementedError(
3756 f"{type(obj)=} could not be cast to a PdfObject"
3757 )
3760def _create_outline_item(
3761 action_ref: IndirectObject | None,
3762 title: str,
3763 color: tuple[float, float, float] | str | None,
3764 italic: bool,
3765 bold: bool,
3766) -> TreeObject:
3767 outline_item = TreeObject()
3768 if action_ref is not None:
3769 outline_item[NameObject("/A")] = action_ref
3770 outline_item.update(
3771 {
3772 NameObject("/Title"): create_string_object(title),
3773 }
3774 )
3775 if color:
3776 if isinstance(color, str):
3777 color = hex_to_rgb(color)
3778 outline_item.update(
3779 {NameObject("/C"): ArrayObject([FloatObject(c) for c in color])}
3780 )
3781 if italic or bold:
3782 format_flag = 0
3783 if italic:
3784 format_flag += OutlineFontFlag.italic
3785 if bold:
3786 format_flag += OutlineFontFlag.bold
3787 outline_item.update({NameObject("/F"): NumberObject(format_flag)})
3788 return outline_item