Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/pypdf/_page.py: 16%
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 math
31from collections.abc import Callable, Iterable, Iterator, Sequence
32from copy import deepcopy
33from dataclasses import asdict, dataclass
34from decimal import Decimal
35from io import BytesIO
36from pathlib import Path
37from typing import (
38 Any,
39 Literal,
40 NoReturn,
41 cast,
42 overload,
43)
45from ._configuration import get_configuration
46from ._protocols import PdfCommonDocProtocol
47from ._text_extraction import (
48 _layout_mode,
49)
50from ._text_extraction._text_extractor import TextExtraction
51from ._utils import (
52 CompressedTransformationMatrix,
53 TransformationMatrixType,
54 _human_readable_bytes,
55 _TraversalState,
56 deprecation,
57 deprecation_no_replacement,
58 deprecation_with_replacement,
59 logger_warning,
60 matrix_multiply,
61)
62from .actions import Action, PageTrigger
63from .constants import (
64 _INLINE_IMAGE_KEY_MAPPING,
65 _INLINE_IMAGE_VALUE_MAPPING,
66 AnnotationDictionaryAttributes,
67 ImageAttributes,
68)
69from .constants import PageAttributes as PG
70from .constants import Resources as RES
71from .errors import PageSizeNotDefinedError, PdfReadError
72from .generic import (
73 ArrayObject,
74 ContentStream,
75 DictionaryObject,
76 EncodedStreamObject,
77 FloatObject,
78 IndirectObject,
79 NameObject,
80 NullObject,
81 NumberObject,
82 PdfObject,
83 RectangleObject,
84 StreamObject,
85 is_null_or_none,
86)
87from .generic._font import Font
89try:
90 from PIL.Image import Image
92 pil_not_imported = False
93except ImportError:
94 Image = object # type: ignore[assignment,misc,unused-ignore] # TODO: Remove unused-ignore on Python 3.10
95 pil_not_imported = True # error will be raised only when using images
97MERGE_CROP_BOX = "cropbox" # DEPRECATED: Use pypdf.Configuration.
100def _get_page_resources(obj: Any) -> DictionaryObject:
101 """Return the inherited /Resources, or an empty dictionary if malformed."""
102 resources = obj.get_inherited(key=PG.RESOURCES, default=DictionaryObject())
103 if is_null_or_none(resources):
104 return DictionaryObject()
105 if not isinstance(resources, DictionaryObject):
106 logger_warning(
107 "Page resources are not a dictionary: %(resources)s",
108 source=__name__,
109 resources=resources,
110 )
111 return DictionaryObject()
112 return resources
115def _get_font_resources(resources: Any) -> DictionaryObject:
116 """Return the /Font resources, or an empty dictionary if missing or malformed."""
117 fonts = resources.get(RES.FONT)
118 if is_null_or_none(fonts):
119 return DictionaryObject()
120 fonts = fonts.get_object()
121 if not isinstance(fonts, DictionaryObject):
122 logger_warning(
123 "Font resources are not a dictionary: %(fonts)s",
124 source=__name__,
125 fonts=fonts,
126 )
127 return DictionaryObject()
128 return fonts
131def _get_rectangle(self: Any, name: str, defaults: Iterable[str]) -> RectangleObject:
132 retval: PdfObject | None = self.get(name)
133 if isinstance(retval, RectangleObject):
134 return retval
135 if is_null_or_none(retval):
136 for d in defaults:
137 retval = self.get(d)
138 if retval is not None:
139 break
140 if isinstance(retval, IndirectObject):
141 # Pages of a writer have no `pdf`, the reference knows its own document.
142 retval = retval.get_object()
143 if not isinstance(retval, ArrayObject):
144 raise ValueError(f"Expected an array of four values for {name}, got {retval}")
145 if (length := len(retval)) != 4:
146 if length > 4:
147 # Keep backwards-compatibility with files previously written in a
148 # broken way by pypdf, which carried more than four values.
149 logger_warning(
150 "Expected four values, got %(length)d: %(retval)s",
151 source=__name__,
152 length=length,
153 retval=retval,
154 )
155 retval = RectangleObject(tuple(retval[:4]))
156 else:
157 raise ValueError(
158 f"Expected four values for {name}, got {length}: {retval}"
159 )
160 else:
161 retval = RectangleObject(retval)
162 _set_rectangle(self, name, retval)
163 return retval
166def _set_rectangle(self: Any, name: str, value: RectangleObject | float) -> None:
167 if isinstance(value, (list, tuple)) and len(value) < 4:
168 # The getter tolerates more than four values for backwards compatibility
169 # but cannot do anything with fewer, so writing them would produce a page
170 # whose box cannot be read back.
171 raise ValueError(
172 f"Expected four values for {name}, got {len(value)}: {value}"
173 )
174 self[NameObject(name)] = value
177def _delete_rectangle(self: Any, name: str) -> None:
178 del self[name]
181def _create_rectangle_accessor(name: str, fallback: Iterable[str]) -> property:
182 return property(
183 lambda self: _get_rectangle(self, name, fallback),
184 lambda self, value: _set_rectangle(self, name, value),
185 lambda self: _delete_rectangle(self, name),
186 )
189class Transformation:
190 """
191 Represent a 2D transformation.
193 The transformation between two coordinate systems is represented by a 3-by-3
194 transformation matrix with the following form::
196 a b 0
197 c d 0
198 e f 1
200 Because a transformation matrix has only six elements that can be changed,
201 it is usually specified in PDF as the six-element array [ a b c d e f ].
203 Coordinate transformations are expressed as matrix multiplications::
205 a b 0
206 [ x′ y′ 1 ] = [ x y 1 ] × c d 0
207 e f 1
210 Example:
211 >>> from pypdf import PdfWriter, Transformation
212 >>> page = PdfWriter().add_blank_page(800, 600)
213 >>> op = Transformation().scale(sx=2, sy=3).translate(tx=10, ty=20)
214 >>> page.add_transformation(op)
216 """
218 def __init__(self, ctm: CompressedTransformationMatrix = (1, 0, 0, 1, 0, 0)) -> None:
219 self.ctm = ctm
221 @property
222 def matrix(self) -> TransformationMatrixType:
223 """
224 Return the transformation matrix as a tuple of tuples in the form:
226 ((a, b, 0), (c, d, 0), (e, f, 1))
227 """
228 return (
229 (self.ctm[0], self.ctm[1], 0),
230 (self.ctm[2], self.ctm[3], 0),
231 (self.ctm[4], self.ctm[5], 1),
232 )
234 @staticmethod
235 def compress(matrix: TransformationMatrixType) -> CompressedTransformationMatrix:
236 """
237 Compresses the transformation matrix into a tuple of (a, b, c, d, e, f).
239 Args:
240 matrix: The transformation matrix as a tuple of tuples.
242 Returns:
243 A tuple representing the transformation matrix as (a, b, c, d, e, f)
245 """
246 return (
247 matrix[0][0],
248 matrix[0][1],
249 matrix[1][0],
250 matrix[1][1],
251 matrix[2][0],
252 matrix[2][1],
253 )
255 def _to_cm(self) -> str:
256 # Returns the cm operation string for the given transformation matrix
257 return (
258 f"{self.ctm[0]:.4f} {self.ctm[1]:.4f} {self.ctm[2]:.4f} "
259 f"{self.ctm[3]:.4f} {self.ctm[4]:.4f} {self.ctm[5]:.4f} cm"
260 )
262 def transform(self, m: "Transformation") -> "Transformation":
263 """
264 Apply one transformation to another.
266 Args:
267 m: a Transformation to apply.
269 Returns:
270 A new ``Transformation`` instance
272 Example:
273 >>> from pypdf import PdfWriter, Transformation
274 >>> height, width = 40, 50
275 >>> page = PdfWriter().add_blank_page(800, 600)
276 >>> op = Transformation((1, 0, 0, -1, 0, height)) # vertical mirror
277 >>> op = Transformation().transform(Transformation((-1, 0, 0, 1, width, 0))) # horizontal mirror
278 >>> page.add_transformation(op)
280 """
281 ctm = Transformation.compress(matrix_multiply(self.matrix, m.matrix))
282 return Transformation(ctm)
284 def translate(self, tx: float = 0, ty: float = 0) -> "Transformation":
285 """
286 Translate the contents of a page.
288 Args:
289 tx: The translation along the x-axis.
290 ty: The translation along the y-axis.
292 Returns:
293 A new ``Transformation`` instance
295 """
296 m = self.ctm
297 return Transformation(ctm=(m[0], m[1], m[2], m[3], m[4] + tx, m[5] + ty))
299 def scale(
300 self, sx: float | None = None, sy: float | None = None
301 ) -> "Transformation":
302 """
303 Scale the contents of a page towards the origin of the coordinate system.
305 Typically, that is the lower-left corner of the page. That can be
306 changed by translating the contents / the page boxes.
308 Args:
309 sx: The scale factor along the x-axis.
310 sy: The scale factor along the y-axis.
312 Returns:
313 A new Transformation instance with the scaled matrix.
315 """
316 if sx is None and sy is None:
317 raise ValueError("Either sx or sy must be specified")
318 if sx is None:
319 sx = sy
320 if sy is None:
321 sy = sx
322 assert sx is not None
323 assert sy is not None
324 op: TransformationMatrixType = ((sx, 0, 0), (0, sy, 0), (0, 0, 1))
325 ctm = Transformation.compress(matrix_multiply(self.matrix, op))
326 return Transformation(ctm)
328 def rotate(self, rotation: float) -> "Transformation":
329 """
330 Rotate the contents of a page.
332 Args:
333 rotation: The angle of rotation in degrees.
335 Returns:
336 A new ``Transformation`` instance with the rotated matrix.
338 """
339 rotation = math.radians(rotation)
340 op: TransformationMatrixType = (
341 (math.cos(rotation), math.sin(rotation), 0),
342 (-math.sin(rotation), math.cos(rotation), 0),
343 (0, 0, 1),
344 )
345 ctm = Transformation.compress(matrix_multiply(self.matrix, op))
346 return Transformation(ctm)
348 def __repr__(self) -> str:
349 return f"Transformation(ctm={self.ctm})"
351 @overload
352 def apply_on(self, pt: list[float], as_object: bool = False) -> list[float]:
353 ...
355 @overload
356 def apply_on(
357 self, pt: tuple[float, float], as_object: bool = False
358 ) -> tuple[float, float]:
359 ...
361 def apply_on(
362 self,
363 pt: tuple[float, float] | list[float],
364 as_object: bool = False,
365 ) -> tuple[float, float] | list[float]:
366 """
367 Apply the transformation matrix on the given point.
369 Args:
370 pt: A tuple or list representing the point in the form (x, y).
371 as_object: If True, return items as FloatObject, otherwise as plain floats.
373 Returns:
374 A tuple or list representing the transformed point in the form (x', y')
376 """
377 typ = FloatObject if as_object else float
378 pt1 = (
379 typ(float(pt[0]) * self.ctm[0] + float(pt[1]) * self.ctm[2] + self.ctm[4]),
380 typ(float(pt[0]) * self.ctm[1] + float(pt[1]) * self.ctm[3] + self.ctm[5]),
381 )
382 return list(pt1) if isinstance(pt, list) else pt1
385@dataclass
386class ImageFile:
387 """
388 Image within the PDF file. *This object is not designed to be built.*
390 This object should not be modified except using :func:`ImageFile.replace` to replace the image with a new one.
391 """
393 name: str = ""
394 """
395 Filename as identified within the PDF file.
397 .. warning::
399 This value can contain arbitrary characters. Please make sure to sanitize it before
400 using it to write the file content to the disk for example.
401 """
403 data: bytes = b""
404 """
405 Data as bytes.
406 """
408 image: Image | None = None
409 """
410 Data as PIL image.
411 """
413 indirect_reference: IndirectObject | None = None
414 """
415 Reference to the object storing the stream.
416 """
418 is_inline: bool = False
419 """
420 True if this is an inline image (~0~, ~1~, etc.).
421 """
423 is_displayed: bool = False
424 """
425 True if this image is displayed in the page content stream.
426 """
428 def replace(self, new_image: Image, **kwargs: Any) -> None:
429 """
430 Replace the image with a new PIL image.
432 Args:
433 new_image (PIL.Image.Image): The new PIL image to replace the existing image.
434 **kwargs: Additional keyword arguments to pass to `Image.save()`.
436 Raises:
437 TypeError: If the image is inline or in a PdfReader.
438 TypeError: If the image does not belong to a PdfWriter.
439 TypeError: If `new_image` is not a PIL Image.
441 Note:
442 This method replaces the existing image with a new image.
443 It is not allowed for inline images or images within a PdfReader.
444 The `kwargs` parameter allows passing additional parameters
445 to `Image.save()`, such as quality.
447 """
448 if pil_not_imported:
449 raise ImportError(
450 "pillow is required to do image extraction. "
451 "It can be installed via 'pip install pypdf[image]'"
452 )
454 from ._reader import PdfReader # noqa: PLC0415
455 from .generic import DictionaryObject, PdfObject # noqa: PLC0415
456 from .generic._image_xobject import _xobj_to_image # noqa: PLC0415
458 if self.indirect_reference is None:
459 raise TypeError("Cannot update an inline image.")
460 if not hasattr(self.indirect_reference.pdf, "_id_translated"):
461 raise TypeError("Cannot update an image not belonging to a PdfWriter.")
462 if not isinstance(new_image, Image):
463 raise TypeError("new_image shall be a PIL Image")
464 b = BytesIO()
465 new_image.save(b, "PDF", **kwargs)
466 reader = PdfReader(b)
467 page_image = reader.pages[0].images[0]
468 assert page_image.indirect_reference is not None
469 self.indirect_reference.pdf._objects[self.indirect_reference.idnum - 1] = (
470 page_image.indirect_reference.get_object()
471 )
472 cast(
473 PdfObject, self.indirect_reference.get_object()
474 ).indirect_reference = self.indirect_reference
475 # change the object attributes
476 extension, byte_stream, img = _xobj_to_image(
477 cast(DictionaryObject, self.indirect_reference.get_object()),
478 pillow_parameters=kwargs,
479 )
480 assert extension is not None
481 self.name = self.name[: self.name.rfind(".")] + extension
482 self.data = byte_stream
483 self.image = img
485 def __str__(self) -> str:
486 return f"{self.__class__.__name__}(name={self.name}, data: {_human_readable_bytes(len(self.data))})"
488 def __repr__(self) -> str:
489 return self.__str__()[:-1] + f", hash: {hash(self.data)})"
492class VirtualListImages(Sequence[ImageFile]):
493 """
494 Provides access to images referenced within a page.
495 Only one copy will be returned if the usage is used on the same page multiple times.
496 See :func:`PageObject.images` for more details.
497 """
499 def __init__(
500 self,
501 ids_function: Callable[[], list[str | list[str]]],
502 get_function: Callable[[str | list[str] | tuple[str]], ImageFile],
503 ) -> None:
504 self.ids_function = ids_function
505 self.get_function = get_function
506 self.current = -1
508 def __len__(self) -> int:
509 return len(self.ids_function())
511 def keys(self) -> list[str | list[str]]:
512 return self.ids_function()
514 def items(self) -> list[tuple[str | list[str], ImageFile]]:
515 return [(x, self[x]) for x in self.ids_function()]
517 @overload
518 def __getitem__(self, index: int | str | list[str]) -> ImageFile:
519 ...
521 @overload
522 def __getitem__(self, index: slice) -> Sequence[ImageFile]:
523 ...
525 def __getitem__(
526 self, index: int | slice | str | list[str] | tuple[str]
527 ) -> ImageFile | Sequence[ImageFile]:
528 lst = self.ids_function()
529 if isinstance(index, slice):
530 indices = range(*index.indices(len(self)))
531 lst = [lst[x] for x in indices]
532 cls = type(self)
533 return cls((lambda: lst), self.get_function)
534 if isinstance(index, (str, list, tuple)):
535 return self.get_function(index)
536 if not isinstance(index, int):
537 raise TypeError("Invalid sequence indices type")
538 len_self = len(lst)
539 if index < 0:
540 # support negative indexes
541 index += len_self
542 if not (0 <= index < len_self):
543 raise IndexError("Sequence index out of range")
544 return self.get_function(lst[index])
546 def __iter__(self) -> Iterator[ImageFile]:
547 for i in range(len(self)):
548 yield self[i]
550 def __str__(self) -> str:
551 p = [f"Image_{i}={n}" for i, n in enumerate(self.ids_function())]
552 return f"[{', '.join(p)}]"
555class PageObject(DictionaryObject):
556 """
557 PageObject represents a single page within a PDF file.
559 Typically these objects will be created by accessing the
560 :attr:`pages<pypdf.PdfReader.pages>` property of the
561 :class:`PdfReader<pypdf.PdfReader>` class, but it is
562 also possible to create an empty page with the
563 :meth:`create_blank_page()<pypdf._page.PageObject.create_blank_page>` static method.
565 Args:
566 pdf: PDF file the page belongs to.
567 indirect_reference: Stores the original indirect reference to
568 this object in its source PDF
570 """
572 original_page: "PageObject" # very local use in writer when appending
574 def __init__(
575 self,
576 pdf: PdfCommonDocProtocol | None = None,
577 indirect_reference: IndirectObject | None = None,
578 ) -> None:
579 DictionaryObject.__init__(self)
580 self.pdf = pdf
581 self._content_stream_images: dict[str, ImageFile | None] | None = None
582 self.indirect_reference = indirect_reference
583 if not is_null_or_none(indirect_reference):
584 assert indirect_reference is not None, "mypy"
585 self.update(cast(DictionaryObject, indirect_reference.get_object()))
587 def hash_bin(self) -> int:
588 """
589 Used to detect modified object.
591 Note: this function is overloaded to return the same results
592 as a DictionaryObject.
594 Returns:
595 Hash considering type and value.
597 """
598 return hash(
599 (DictionaryObject, tuple(((k, v.hash_bin()) for k, v in self.items())))
600 )
602 def hash_value_data(self) -> bytes:
603 data = super().hash_value_data()
604 data += f"{id(self)}".encode()
605 return data
607 @property
608 def user_unit(self) -> float:
609 """
610 A read-only positive number giving the size of user space units.
612 It is in multiples of 1/72 inch. Hence a value of 1 means a user
613 space unit is 1/72 inch, and a value of 3 means that a user
614 space unit is 3/72 inch.
615 """
616 return cast(float, self.get(PG.USER_UNIT, 1))
618 @staticmethod
619 def create_blank_page(
620 pdf: PdfCommonDocProtocol | None = None,
621 width: float | Decimal | None = None,
622 height: float | Decimal | None = None,
623 ) -> "PageObject":
624 """
625 Return a new blank page.
627 If ``width`` or ``height`` is ``None``, try to get the page size
628 from the last page of *pdf*.
630 Args:
631 pdf: PDF file the page is within.
632 width: The width of the new page expressed in default user
633 space units.
634 height: The height of the new page expressed in default user
635 space units.
637 Returns:
638 The new blank page
640 Raises:
641 PageSizeNotDefinedError: if ``pdf`` is ``None`` or contains
642 no page
644 """
645 page = PageObject(pdf)
647 # Creates a new page (cf PDF Reference §7.7.3.3)
648 page.__setitem__(NameObject(PG.TYPE), NameObject("/Page"))
649 page.__setitem__(NameObject(PG.PARENT), NullObject())
650 page.__setitem__(NameObject(PG.RESOURCES), DictionaryObject())
651 if width is None or height is None:
652 if pdf is not None and len(pdf.pages) > 0:
653 lastpage = pdf.pages[len(pdf.pages) - 1]
654 width = lastpage.mediabox.width
655 height = lastpage.mediabox.height
656 else:
657 raise PageSizeNotDefinedError
658 page.__setitem__(
659 NameObject(PG.MEDIABOX), RectangleObject((0, 0, width, height))
660 )
662 return page
664 def _get_ids_image(
665 self,
666 obj: DictionaryObject | None = None,
667 ancest: list[str] | None = None,
668 call_stack: list[Any] | None = None,
669 ) -> list[str | list[str]]:
670 if call_stack is None:
671 call_stack = []
672 _i = getattr(obj, "indirect_reference", None)
673 if _i in call_stack:
674 return []
675 call_stack.append(_i)
676 if self._content_stream_images is None:
677 self._content_stream_images = self._parse_images_from_content_stream()
678 if obj is None:
679 obj = self
680 if ancest is None:
681 ancest = []
682 lst: list[str | list[str]] = []
683 if (
684 PG.RESOURCES not in obj or
685 is_null_or_none(resources := cast(DictionaryObject, obj[PG.RESOURCES])) or
686 RES.XOBJECT not in resources
687 ):
688 # Forms without XObject resources have no images inside them
689 if len(ancest) > 0:
690 return []
691 # for inline images, cache dict entries are not None
692 return [image_name for image_name, image_value in self._content_stream_images.items() if image_value]
694 x_object = resources[RES.XOBJECT].get_object()
695 if not isinstance(x_object, DictionaryObject):
696 logger_warning(
697 "XObject resources are not a dictionary: %(x_object)s",
698 source=__name__,
699 x_object=x_object,
700 )
701 return []
703 # Iterate through all XObject resources
704 for o in x_object:
705 entry = x_object[o]
706 # Skip non-stream objects (only process StreamObject)
707 if not isinstance(entry, StreamObject):
708 continue
709 if entry.get(ImageAttributes.SUBTYPE, "") == "/Image":
710 # If it's an image, add it to lst for further processing
711 lst.append(o if len(ancest) == 0 else [*ancest, o])
712 else:
713 # If it's a form, recursively search for images inside it
714 # Forms may contain images that are Do-referenced in their content stream
715 lst.extend(self._get_ids_image(entry, [*ancest, o], call_stack))
717 # Removes duplicates and preserves order
718 deduplicated = lst.copy()
720 # Add inline images from _content_stream_images
721 for object_name, object_value in self._content_stream_images.items():
722 # inline images have cache populated
723 if object_name not in deduplicated and object_value:
724 deduplicated.append(object_name)
726 return deduplicated
728 def _get_image(
729 self,
730 image_id: str | list[str] | tuple[str],
731 obj: DictionaryObject | None = None,
732 ) -> ImageFile:
733 if obj is None:
734 obj = cast(DictionaryObject, self)
735 if isinstance(image_id, tuple):
736 image_id = list(image_id)
737 if isinstance(image_id, list) and len(image_id) == 1:
738 image_id = image_id[0]
739 xobjs: DictionaryObject | None = None
740 try:
741 xobjs = cast(
742 DictionaryObject, cast(DictionaryObject, obj[PG.RESOURCES])[RES.XOBJECT]
743 )
744 except KeyError as exc:
745 if not (image_id[0] == "~" and image_id[-1] == "~"):
746 raise KeyError(
747 f"Cannot access image object {image_id} without XObject resources"
748 ) from exc
749 if isinstance(image_id, str):
750 if image_id[0] == "~" and image_id[-1] == "~":
751 if self._content_stream_images is None:
752 self._content_stream_images = self._parse_images_from_content_stream()
753 if image_id not in self._content_stream_images:
754 raise KeyError(f"Image {image_id} not found")
755 image_file = self._content_stream_images[image_id]
756 assert image_file is not None
757 return image_file
759 # Do-referenced image name (non-inline string keys like /Im0)
760 assert xobjs is not None
761 if image_id not in xobjs:
762 raise KeyError(f"Image {image_id} not found")
763 xobj = cast(DictionaryObject, xobjs[image_id])
764 if xobj.get(ImageAttributes.SUBTYPE, "") != "/Image":
765 raise KeyError(f"XObject {image_id} is not an image")
767 # Check if displayed (in content stream)
768 is_displayed = self._content_stream_images is not None and image_id in self._content_stream_images
770 from .generic._image_xobject import _xobj_to_image # noqa: PLC0415
771 extension, byte_stream, img = _xobj_to_image(xobj)
772 return ImageFile(
773 name=f"{image_id[1:]}{extension}",
774 data=byte_stream,
775 image=img,
776 indirect_reference=xobj.indirect_reference,
777 is_inline=False,
778 is_displayed=is_displayed,
779 )
780 # in a subobject
781 assert xobjs is not None
782 ids = image_id[1:]
783 return self._get_image(ids, cast(DictionaryObject, xobjs[image_id[0]]))
785 @property
786 def images(self) -> VirtualListImages:
787 """
788 Read-only property emulating a list of images on a page.
790 Get a list of all images on the page. The key can be:
791 - A string (for the top object)
792 - A tuple (for images within XObject forms)
793 - An integer
795 Examples:
796 * `reader.pages[0].images[0]` # return first image
797 * `reader.pages[0].images['/I0']` # return image '/I0'
798 * `reader.pages[0].images['/TP1','/Image1']` # return image '/Image1' within '/TP1' XObject form
799 * `for img in reader.pages[0].images:` # loops through all objects
801 Example usage:
803 >>> from pypdf import PdfWriter
804 >>> writer = PdfWriter()
805 >>> page = writer.add_blank_page(800, 600)
806 >>> images = page.images
808 """
809 return VirtualListImages(self._get_ids_image, self._get_image)
811 @property
812 def inline_images(self) -> NoReturn:
813 """
814 Return only inline images from the page.
816 .. deprecated::
817 Use :attr:`images` and filter by :attr:`ImageFile.is_inline` instead.
818 This property has been removed in pypdf 7.0.
820 Examples:
821 >>> from pypdf import PdfWriter
822 >>> writer = PdfWriter()
823 >>> page = writer.add_blank_page(800,600)
824 >>> for image_name, image_file in page.images.items():
825 ... if image_file.is_inline:
826 ... print(f"{image_name} is inline")
827 """
828 deprecation_with_replacement(
829 "PageObject.inline_images",
830 "PageObject.images",
831 "7.0.0",
832 )
834 @inline_images.setter
835 def inline_images(self, value: dict[str, ImageFile] | None) -> NoReturn:
836 deprecation_no_replacement(
837 "PageObject.inline_images",
838 "7.0.0",
839 )
841 def _translate_value_inline_image(self, k: str, v: PdfObject) -> PdfObject:
842 """Translate values used in inline image"""
843 try:
844 v = NameObject(_INLINE_IMAGE_VALUE_MAPPING[cast(str, v)])
845 except (TypeError, KeyError) as exception:
846 if isinstance(v, NameObject):
847 # It is a custom name, thus we have to look in resources.
848 # The only applicable case is for ColorSpace.
849 if "/Resources" in self:
850 resources = cast(DictionaryObject, self["/Resources"])
851 if "/ColorSpace" in resources and v in cast(DictionaryObject, resources["/ColorSpace"]):
852 color_space = cast(DictionaryObject, resources["/ColorSpace"])
853 return color_space[v]
854 raise PdfReadError(f"Cannot find resource entry {v} for {k}") from exception
855 return v
857 def _parse_images_from_content_stream(self) -> dict[str, ImageFile | None]:
858 """Load images from content stream. Includes both inline images and Do-referenced images.
860 This method scans the page content stream and extracts:
862 1. **Inline images** (~0~, ~1~...): Embedded directly in content stream via BI/EI operators
863 - is_inline=True, is_displayed=True, indirect_reference=None
865 2. **Do-referenced objects** (/Im0, /Im1..., /Form1...): Referenced via "Do" operator
866 - is_inline=False, is_displayed=True, indirect_reference=<image object>
868 3. **Pure XObject images** (/I0, /Image1...): Defined in Resources only (not in content stream)
869 - is_inline=False, is_displayed=False, indirect_reference=<image object>
871 Returns:
872 Dictionary mapping names to ImageFile instances (inline) or None (Do-referenced).
873 """
874 content = self.get_contents()
875 if is_null_or_none(content):
876 return {}
877 imgs_data = []
878 do_image_names: list[bytes] = []
879 assert content is not None, "mypy"
880 for param, ope in content.operations:
881 if ope == b"INLINE IMAGE":
882 imgs_data.append(
883 {"settings": param["settings"], "__streamdata__": param["data"]}
884 )
885 elif ope == b"Do" and param:
886 do_image_names.append(param[0]) # First operand is the XObject name
887 elif ope in (b"BI", b"EI", b"ID"): # pragma: no cover
888 raise PdfReadError(
889 f"{ope!r} operator met whereas not expected, "
890 "please share use case with pypdf dev team"
891 )
893 files: dict[str, ImageFile | None] = {}
894 # Process Do-referenced objects first (images + forms, no subtype check)
895 files = dict.fromkeys(list(map(str, do_image_names)), None)
897 # Then process inline images
898 for num, ii in enumerate(imgs_data):
899 init = {
900 "__streamdata__": ii["__streamdata__"],
901 "/Length": len(ii["__streamdata__"]),
902 }
903 for k, v in ii["settings"].items():
904 if k in {"/Length", "/L"}: # no length is expected
905 continue
906 if isinstance(v, list):
907 v = ArrayObject(
908 [self._translate_value_inline_image(k, x) for x in v]
909 )
910 else:
911 v = self._translate_value_inline_image(k, v)
912 if k in _INLINE_IMAGE_KEY_MAPPING:
913 k = NameObject(_INLINE_IMAGE_KEY_MAPPING[k])
914 else:
915 logger_warning(
916 "Unknown inline image key %(key)s, keeping it as-is.",
917 source=__name__,
918 key=k,
919 )
920 k = NameObject(k)
921 if k not in init:
922 init[k] = v
923 ii["object"] = EncodedStreamObject.initialize_from_dictionary(init)
924 from .generic._image_xobject import _xobj_to_image # noqa: PLC0415
925 extension, byte_stream, img = _xobj_to_image(ii["object"])
926 files[f"~{num}~"] = ImageFile(
927 name=f"~{num}~{extension}",
928 data=byte_stream,
929 image=img,
930 indirect_reference=None,
931 is_inline=True,
932 is_displayed=True,
933 )
935 return files
937 @property
938 def rotation(self) -> int:
939 """
940 The visual rotation of the page.
942 This number has to be a multiple of 90 degrees: 0, 90, 180, or 270 are
943 valid values. This property does not affect ``/Contents``.
944 """
945 rotate_obj = self.get(PG.ROTATE, 0)
946 return rotate_obj if isinstance(rotate_obj, int) else rotate_obj.get_object()
948 @rotation.setter
949 def rotation(self, r: float) -> None:
950 self[NameObject(PG.ROTATE)] = NumberObject((((int(r) + 45) // 90) * 90) % 360)
952 def transfer_rotation_to_content(self) -> None:
953 """
954 Apply the rotation of the page to the content and the media/crop/...
955 boxes.
957 It is recommended to apply this function before page merging.
958 """
959 r = -self.rotation # rotation to apply is in the otherway
960 self.rotation = 0
961 mb = RectangleObject(self.mediabox)
962 trsf = (
963 Transformation()
964 .translate(
965 -float(mb.left + mb.width / 2), -float(mb.bottom + mb.height / 2)
966 )
967 .rotate(r)
968 )
969 pt1 = trsf.apply_on(mb.lower_left)
970 pt2 = trsf.apply_on(mb.upper_right)
971 trsf = trsf.translate(-min(pt1[0], pt2[0]), -min(pt1[1], pt2[1]))
972 self.add_transformation(trsf, False)
973 for b in ["/MediaBox", "/CropBox", "/BleedBox", "/TrimBox", "/ArtBox"]:
974 if b in self:
975 rr = RectangleObject(self[b]) # type: ignore[arg-type]
976 pt1 = trsf.apply_on(rr.lower_left)
977 pt2 = trsf.apply_on(rr.upper_right)
978 self[NameObject(b)] = RectangleObject(
979 (
980 min(pt1[0], pt2[0]),
981 min(pt1[1], pt2[1]),
982 max(pt1[0], pt2[0]),
983 max(pt1[1], pt2[1]),
984 )
985 )
987 def rotate(self, angle: int) -> "PageObject":
988 """
989 Rotate a page clockwise by increments of 90 degrees.
991 Args:
992 angle: Angle to rotate the page. Must be an increment of 90 deg.
994 Returns:
995 The rotated PageObject
997 """
998 if angle % 90 != 0:
999 raise ValueError("Rotation angle must be a multiple of 90")
1000 self[NameObject(PG.ROTATE)] = NumberObject(self.rotation + angle)
1001 return self
1003 def _merge_resources(
1004 self,
1005 res1: DictionaryObject,
1006 res2: DictionaryObject,
1007 resource: Any,
1008 new_res1: bool = True,
1009 ) -> tuple[dict[str, Any], dict[str, Any]]:
1010 try:
1011 assert isinstance(self.indirect_reference, IndirectObject)
1012 pdf = self.indirect_reference.pdf
1013 is_pdf_writer = hasattr(
1014 pdf, "_add_object"
1015 ) # expect isinstance(pdf, PdfWriter)
1016 except (AssertionError, AttributeError):
1017 pdf = None
1018 is_pdf_writer = False
1020 def compute_unique_key(base_key: str) -> tuple[str, bool]:
1021 """
1022 Find a key that either doesn't already exist or has the same value
1023 (indicated by the bool)
1025 Args:
1026 base_key: An index is added to this to get the computed key
1028 Returns:
1029 A tuple (computed key, bool) where the boolean indicates
1030 if there is a resource of the given computed_key with the same
1031 value.
1033 """
1034 value = page2res.raw_get(base_key)
1035 # TODO: a possible improvement for writer, the indirect_reference
1036 # cannot be found because translated
1038 # try the current key first (e.g. "foo"), but otherwise iterate
1039 # through "foo-0", "foo-1", etc. new_res can contain only finitely
1040 # many keys, thus this'll eventually end, even if it's been crafted
1041 # to be maximally annoying.
1042 computed_key = base_key
1043 idx = 0
1044 while computed_key in new_res:
1045 if new_res.raw_get(computed_key) == value:
1046 # there's already a resource of this name, with the exact
1047 # same value
1048 return computed_key, True
1049 computed_key = f"{base_key}-{idx}"
1050 idx += 1
1051 return computed_key, False
1053 if new_res1:
1054 new_res = DictionaryObject()
1055 new_res.update(res1.get(resource, DictionaryObject()).get_object())
1056 else:
1057 new_res = cast(DictionaryObject, res1[resource])
1058 page2res = cast(
1059 DictionaryObject, res2.get(resource, DictionaryObject()).get_object()
1060 )
1061 rename_res = {}
1062 for key in page2res:
1063 unique_key, same_value = compute_unique_key(key)
1064 newname = NameObject(unique_key)
1065 if key != unique_key:
1066 # we have to use a different name for this
1067 rename_res[key] = newname
1069 if not same_value:
1070 if is_pdf_writer:
1071 new_res[newname] = page2res.raw_get(key).clone(pdf)
1072 try:
1073 new_res[newname] = new_res[newname].indirect_reference
1074 except AttributeError:
1075 pass
1076 else:
1077 new_res[newname] = page2res.raw_get(key)
1078 lst = sorted(new_res.items())
1079 new_res.clear()
1080 for el in lst:
1081 new_res[el[0]] = el[1]
1082 return new_res, rename_res
1084 @staticmethod
1085 def _content_stream_rename(
1086 stream: ContentStream,
1087 rename: dict[Any, Any],
1088 pdf: PdfCommonDocProtocol | None,
1089 ) -> ContentStream:
1090 if not rename:
1091 return stream
1092 stream = ContentStream(stream, pdf)
1093 for operands, _operator in stream.operations:
1094 if isinstance(operands, list):
1095 for i, op in enumerate(operands):
1096 if isinstance(op, NameObject):
1097 operands[i] = rename.get(op, op)
1098 elif isinstance(operands, dict):
1099 for i, op in operands.items():
1100 if isinstance(op, NameObject):
1101 operands[i] = rename.get(op, op)
1102 else:
1103 raise KeyError(f"Type of operands is {type(operands)}")
1104 return stream
1106 @staticmethod
1107 def _add_transformation_matrix(
1108 contents: Any,
1109 pdf: PdfCommonDocProtocol | None,
1110 ctm: CompressedTransformationMatrix,
1111 ) -> ContentStream:
1112 """Add transformation matrix at the beginning of the given contents stream."""
1113 content_stream = ContentStream(contents, pdf)
1114 content_stream.operations.insert(
1115 0,
1116 (
1117 [FloatObject(x) for x in ctm],
1118 b"cm",
1119 ),
1120 )
1121 return content_stream
1123 def _get_contents_as_bytes(self) -> bytes | None:
1124 """
1125 Return the page contents as bytes.
1127 Returns:
1128 The ``/Contents`` object as bytes, or ``None`` if it doesn't exist.
1130 """
1131 if PG.CONTENTS in self:
1132 obj = self[PG.CONTENTS].get_object()
1133 if isinstance(obj, list):
1134 return b"".join(x.get_object().get_data() for x in obj)
1135 return cast(EncodedStreamObject, obj).get_data()
1136 return None
1138 def get_contents(self) -> ContentStream | None:
1139 """
1140 Access the page contents.
1142 Returns:
1143 The ``/Contents`` object, or ``None`` if it does not exist.
1144 ``/Contents`` is optional, as described in §7.7.3.3 of the PDF Reference.
1146 """
1147 if PG.CONTENTS in self:
1148 try:
1149 pdf = cast(IndirectObject, self.indirect_reference).pdf
1150 except AttributeError:
1151 pdf = None
1152 obj = self[PG.CONTENTS]
1153 if is_null_or_none(obj):
1154 return None
1155 resolved_object = obj.get_object()
1156 return ContentStream(resolved_object, pdf)
1157 return None
1159 def replace_contents(
1160 self, content: ContentStream | EncodedStreamObject | ArrayObject | None
1161 ) -> None:
1162 """
1163 Replace the page contents with the new content and nullify old objects
1164 Args:
1165 content: new content; if None delete the content field.
1166 """
1167 if not hasattr(self, "indirect_reference") or self.indirect_reference is None:
1168 # the page is not attached : the content is directly attached.
1169 self[NameObject(PG.CONTENTS)] = content
1170 return
1172 from pypdf._writer import PdfWriter # noqa: PLC0415
1173 if not isinstance(self.indirect_reference.pdf, PdfWriter):
1174 deprecation(
1175 "Calling `PageObject.replace_contents()` for pages not assigned to a writer is deprecated "
1176 "and has been removed in pypdf 7.0.0. Attach the page to the writer first or use "
1177 "`PdfWriter(clone_from=...)` directly. The existing approach has proved being unreliable."
1178 )
1180 writer = self.indirect_reference.pdf
1181 # Resolve /Contents because it may be an indirect reference to an
1182 # ArrayObject. Without resolving it, an indirect contents array is not
1183 # recognized and its stream objects are left in the writer's object list.
1184 old_contents = self.get(PG.CONTENTS, None)
1185 if old_contents is not None:
1186 old_contents = old_contents.get_object()
1187 if isinstance(old_contents, ArrayObject):
1188 for reference in old_contents:
1189 if not isinstance(reference, IndirectObject):
1190 # Direct objects are not part of the writer's object list.
1191 continue
1192 writer._replace_object(indirect_reference=reference, obj=NullObject())
1194 if isinstance(content, ArrayObject):
1195 content = ArrayObject(writer._add_object(obj) for obj in content)
1197 if is_null_or_none(content):
1198 if PG.CONTENTS not in self:
1199 return
1200 contents_reference = self[PG.CONTENTS].indirect_reference
1201 assert contents_reference is not None, "mypy"
1202 writer._replace_object(indirect_reference=contents_reference, obj=NullObject())
1203 del self[PG.CONTENTS]
1204 elif not hasattr(self.get(PG.CONTENTS, None), "indirect_reference"):
1205 assert content is not None, "mypy"
1206 self[NameObject(PG.CONTENTS)] = writer._add_object(content)
1207 else:
1208 assert content is not None, "mypy"
1209 content.indirect_reference = self[
1210 PG.CONTENTS
1211 ].indirect_reference # TODO: in the future may require generation management
1212 assert content.indirect_reference is not None, "mypy"
1213 writer._replace_object(indirect_reference=content.indirect_reference, obj=content)
1214 # forces recalculation of images
1215 self._content_stream_images = None
1217 def merge_page(
1218 self, page2: "PageObject", expand: bool = False, over: bool = True
1219 ) -> None:
1220 """
1221 Merge the content streams of two pages into one.
1223 Resource references (e.g. fonts) are maintained from both pages.
1224 The mediabox, cropbox, etc of this page are not altered.
1225 The parameter page's content stream will
1226 be added to the end of this page's content stream,
1227 meaning that it will be drawn after, or "on top" of this page.
1229 Args:
1230 page2: The page to be merged into this one. Should be
1231 an instance of :class:`PageObject<PageObject>`.
1232 over: set the page2 content over page1 if True (default) else under
1233 expand: If True, the current page dimensions will be
1234 expanded to accommodate the dimensions of the page to be merged.
1236 """
1237 self._merge_page(page2, over=over, expand=expand)
1239 def _merge_page(
1240 self,
1241 page2: "PageObject",
1242 page2_transformation: Callable[[Any], ContentStream] | None = None,
1243 ctm: CompressedTransformationMatrix | None = None,
1244 over: bool = True,
1245 expand: bool = False,
1246 ) -> None:
1247 # First we work on merging the resource dictionaries. This allows us
1248 # to find out what symbols in the content streams we might need to
1249 # rename.
1250 try:
1251 assert isinstance(self.indirect_reference, IndirectObject)
1252 if hasattr(self.indirect_reference.pdf, "_add_object"): # to detect PdfWriter
1253 return self._merge_page_writer(
1254 page2, page2_transformation, ctm, over, expand
1255 )
1256 except (AssertionError, AttributeError):
1257 pass
1259 new_resources = DictionaryObject()
1260 rename: dict[str, Any] = {}
1261 original_resources = cast(DictionaryObject, self.get(PG.RESOURCES, DictionaryObject()).get_object())
1262 page2_resources = cast(DictionaryObject, page2.get(PG.RESOURCES, DictionaryObject()).get_object())
1263 new_annots = ArrayObject()
1265 for page in (self, page2):
1266 if PG.ANNOTS in page:
1267 annots = page[PG.ANNOTS]
1268 if isinstance(annots, ArrayObject):
1269 new_annots.extend(annots)
1270 self[NameObject(PG.ANNOTS)] = new_annots
1272 for res in (
1273 RES.EXT_G_STATE,
1274 RES.COLOR_SPACE,
1275 RES.PATTERN,
1276 RES.SHADING,
1277 RES.XOBJECT,
1278 RES.FONT,
1279 RES.PROPERTIES,
1280 ):
1281 new, new_resource_name = self._merge_resources(
1282 original_resources, page2_resources, res
1283 )
1284 if new:
1285 new_resources[NameObject(res)] = new
1286 rename.update(new_resource_name)
1288 # Combine /ProcSet sets, making sure there is a consistent order
1289 new_resources[NameObject(RES.PROC_SET)] = ArrayObject(
1290 sorted(
1291 set(
1292 original_resources.get(RES.PROC_SET, ArrayObject()).get_object()
1293 ).union(
1294 set(page2_resources.get(RES.PROC_SET, ArrayObject()).get_object())
1295 )
1296 )
1297 )
1299 new_content_array = ArrayObject()
1300 original_content = self.get_contents()
1301 if original_content is not None:
1302 original_content.isolate_graphics_state()
1303 new_content_array.append(original_content)
1305 page2_content = page2.get_contents()
1306 if page2_content is not None:
1307 configuration = get_configuration()
1308 rect = getattr(page2, configuration.page_merge_box)
1309 page2_content.operations.insert(
1310 0,
1311 (
1312 map(
1313 FloatObject,
1314 [
1315 rect.left,
1316 rect.bottom,
1317 rect.width,
1318 rect.height,
1319 ],
1320 ),
1321 b"re",
1322 ),
1323 )
1324 page2_content.operations.insert(1, ([], b"W"))
1325 page2_content.operations.insert(2, ([], b"n"))
1326 if page2_transformation is not None:
1327 page2_content = page2_transformation(page2_content)
1328 page2_content = PageObject._content_stream_rename(
1329 page2_content, rename, self.pdf
1330 )
1331 page2_content.isolate_graphics_state()
1332 if over:
1333 new_content_array.append(page2_content)
1334 else:
1335 new_content_array.insert(0, page2_content)
1337 # if expanding the page to fit a new page, calculate the new media box size
1338 if expand:
1339 self._expand_mediabox(page2, ctm)
1341 self.replace_contents(ContentStream(new_content_array, self.pdf))
1342 self[NameObject(PG.RESOURCES)] = new_resources
1344 return None
1346 def _merge_page_writer(
1347 self,
1348 page2: "PageObject",
1349 page2transformation: Callable[[Any], ContentStream] | None = None,
1350 ctm: CompressedTransformationMatrix | None = None,
1351 over: bool = True,
1352 expand: bool = False,
1353 ) -> None:
1354 # First we work on merging the resource dictionaries. This allows us
1355 # to find which symbols in the content streams we might need to
1356 # rename.
1357 assert isinstance(self.indirect_reference, IndirectObject)
1358 pdf = self.indirect_reference.pdf
1360 if PG.RESOURCES not in self:
1361 self[NameObject(PG.RESOURCES)] = DictionaryObject()
1362 original_resources = cast(DictionaryObject, self[PG.RESOURCES].get_object())
1363 if PG.RESOURCES not in page2:
1364 page2resources = DictionaryObject()
1365 else:
1366 page2resources = cast(DictionaryObject, page2[PG.RESOURCES].get_object())
1368 rename = {}
1369 for res in (
1370 RES.EXT_G_STATE,
1371 RES.COLOR_SPACE,
1372 RES.PATTERN,
1373 RES.SHADING,
1374 RES.XOBJECT,
1375 RES.FONT,
1376 RES.PROPERTIES,
1377 ):
1378 if res in page2resources:
1379 if res not in original_resources:
1380 original_resources[NameObject(res)] = DictionaryObject()
1381 _, newrename = self._merge_resources(
1382 original_resources, page2resources, res, False
1383 )
1384 rename.update(newrename)
1385 # Combine /ProcSet sets
1386 if RES.PROC_SET in page2resources:
1387 if RES.PROC_SET not in original_resources:
1388 original_resources[NameObject(RES.PROC_SET)] = ArrayObject()
1389 arr = cast(ArrayObject, original_resources[RES.PROC_SET])
1390 for x in cast(ArrayObject, page2resources[RES.PROC_SET]):
1391 if x not in arr:
1392 arr.append(x)
1393 arr.sort()
1395 if not is_null_or_none(page2.get(PG.ANNOTS, None)):
1396 if PG.ANNOTS not in self:
1397 self[NameObject(PG.ANNOTS)] = ArrayObject()
1398 annots = cast(ArrayObject, self[PG.ANNOTS].get_object())
1399 if ctm is None:
1400 trsf = Transformation()
1401 else:
1402 trsf = Transformation(ctm)
1403 # Ensure we are working on a copy of the list. Otherwise, if both pages
1404 # are the same object, we might run into an infinite loop.
1405 for a in cast(ArrayObject, deepcopy(page2[PG.ANNOTS])):
1406 a = a.get_object()
1407 aa = a.clone(
1408 pdf,
1409 ignore_fields=("/P", "/StructParent", "/Parent"),
1410 force_duplicate=True,
1411 )
1412 r = cast(ArrayObject, a["/Rect"])
1413 pt1 = trsf.apply_on((r[0], r[1]), True)
1414 pt2 = trsf.apply_on((r[2], r[3]), True)
1415 aa[NameObject("/Rect")] = ArrayObject(
1416 (
1417 min(pt1[0], pt2[0]),
1418 min(pt1[1], pt2[1]),
1419 max(pt1[0], pt2[0]),
1420 max(pt1[1], pt2[1]),
1421 )
1422 )
1423 if "/QuadPoints" in a:
1424 q = cast(ArrayObject, a["/QuadPoints"])
1425 aa[NameObject("/QuadPoints")] = ArrayObject(
1426 value
1427 for i in range(0, len(q), 2)
1428 for value in trsf.apply_on((q[i], q[i + 1]), True)
1429 )
1430 # The /Rect update above only repositions and resizes the
1431 # annotation's bounding box; it does not touch the
1432 # appearance stream's own coordinate system. See
1433 # transform_annotation_appearance for why that matters.
1434 from pypdf.generic._appearance_stream import ( # noqa: PLC0415
1435 transform_annotation_appearance,
1436 )
1437 transform_annotation_appearance(aa, trsf)
1438 try:
1439 aa["/Popup"][NameObject("/Parent")] = aa.indirect_reference
1440 except KeyError:
1441 pass
1442 try:
1443 aa[NameObject("/P")] = self.indirect_reference
1444 annots.append(aa.indirect_reference)
1445 except AttributeError:
1446 pass
1448 new_content_array = ArrayObject()
1449 original_content = self.get_contents()
1450 if original_content is not None:
1451 original_content.isolate_graphics_state()
1452 new_content_array.append(original_content)
1454 page2content = page2.get_contents()
1455 if page2content is not None:
1456 configuration = get_configuration()
1457 rect = getattr(page2, configuration.page_merge_box)
1458 page2content.operations.insert(
1459 0,
1460 (
1461 map(
1462 FloatObject,
1463 [
1464 rect.left,
1465 rect.bottom,
1466 rect.width,
1467 rect.height,
1468 ],
1469 ),
1470 b"re",
1471 ),
1472 )
1473 page2content.operations.insert(1, ([], b"W"))
1474 page2content.operations.insert(2, ([], b"n"))
1475 if page2transformation is not None:
1476 page2content = page2transformation(page2content)
1477 page2content = PageObject._content_stream_rename(
1478 page2content, rename, self.pdf
1479 )
1480 page2content.isolate_graphics_state()
1481 if over:
1482 new_content_array.append(page2content)
1483 else:
1484 new_content_array.insert(0, page2content)
1486 # if expanding the page to fit a new page, calculate the new media box size
1487 if expand:
1488 self._expand_mediabox(page2, ctm)
1490 self.replace_contents(new_content_array)
1492 def _expand_mediabox(
1493 self, page2: "PageObject", ctm: CompressedTransformationMatrix | None
1494 ) -> None:
1495 corners1 = (
1496 self.mediabox.left.as_numeric(),
1497 self.mediabox.bottom.as_numeric(),
1498 self.mediabox.right.as_numeric(),
1499 self.mediabox.top.as_numeric(),
1500 )
1501 corners2 = (
1502 page2.mediabox.left.as_numeric(),
1503 page2.mediabox.bottom.as_numeric(),
1504 page2.mediabox.left.as_numeric(),
1505 page2.mediabox.top.as_numeric(),
1506 page2.mediabox.right.as_numeric(),
1507 page2.mediabox.top.as_numeric(),
1508 page2.mediabox.right.as_numeric(),
1509 page2.mediabox.bottom.as_numeric(),
1510 )
1511 if ctm is not None:
1512 ctm = tuple(float(x) for x in ctm) # type: ignore[assignment]
1513 new_x = tuple(
1514 ctm[0] * corners2[i] + ctm[2] * corners2[i + 1] + ctm[4]
1515 for i in range(0, 8, 2)
1516 )
1517 new_y = tuple(
1518 ctm[1] * corners2[i] + ctm[3] * corners2[i + 1] + ctm[5]
1519 for i in range(0, 8, 2)
1520 )
1521 else:
1522 new_x = corners2[0:8:2]
1523 new_y = corners2[1:8:2]
1524 lowerleft = (min(new_x), min(new_y))
1525 upperright = (max(new_x), max(new_y))
1526 lowerleft = (min(corners1[0], lowerleft[0]), min(corners1[1], lowerleft[1]))
1527 upperright = (
1528 max(corners1[2], upperright[0]),
1529 max(corners1[3], upperright[1]),
1530 )
1532 self.mediabox.lower_left = lowerleft
1533 self.mediabox.upper_right = upperright
1535 def merge_transformed_page(
1536 self,
1537 page2: "PageObject",
1538 ctm: CompressedTransformationMatrix | Transformation,
1539 over: bool = True,
1540 expand: bool = False,
1541 ) -> None:
1542 """
1543 Similar to :meth:`~pypdf._page.PageObject.merge_page`, but a transformation
1544 matrix is applied to the merged stream.
1546 Args:
1547 page2: The page to be merged into this one.
1548 ctm: a 6-element tuple containing the operands of the
1549 transformation matrix
1550 over: set the page2 content over page1 if True (default) else under
1551 expand: Whether the page should be expanded to fit the dimensions
1552 of the page to be merged.
1554 """
1555 if isinstance(ctm, Transformation):
1556 ctm = ctm.ctm
1557 self._merge_page(
1558 page2,
1559 lambda page2_content: PageObject._add_transformation_matrix(
1560 page2_content, page2.pdf, ctm
1561 ),
1562 ctm,
1563 over,
1564 expand,
1565 )
1567 def merge_scaled_page(
1568 self, page2: "PageObject", scale: float, over: bool = True, expand: bool = False
1569 ) -> None:
1570 """
1571 Similar to :meth:`~pypdf._page.PageObject.merge_page`, but the stream to be merged
1572 is scaled by applying a transformation matrix.
1574 Args:
1575 page2: The page to be merged into this one.
1576 scale: The scaling factor
1577 over: set the page2 content over page1 if True (default) else under
1578 expand: Whether the page should be expanded to fit the
1579 dimensions of the page to be merged.
1581 """
1582 op = Transformation().scale(scale, scale)
1583 self.merge_transformed_page(page2, op, over, expand)
1585 def merge_rotated_page(
1586 self,
1587 page2: "PageObject",
1588 rotation: float,
1589 over: bool = True,
1590 expand: bool = False,
1591 ) -> None:
1592 """
1593 Similar to :meth:`~pypdf._page.PageObject.merge_page`, but the stream to be merged
1594 is rotated by applying a transformation matrix.
1596 Args:
1597 page2: The page to be merged into this one.
1598 rotation: The angle of the rotation, in degrees
1599 over: set the page2 content over page1 if True (default) else under
1600 expand: Whether the page should be expanded to fit the
1601 dimensions of the page to be merged.
1603 """
1604 op = Transformation().rotate(rotation)
1605 self.merge_transformed_page(page2, op, over, expand)
1607 def merge_translated_page(
1608 self,
1609 page2: "PageObject",
1610 tx: float,
1611 ty: float,
1612 over: bool = True,
1613 expand: bool = False,
1614 ) -> None:
1615 """
1616 Similar to :meth:`~pypdf._page.PageObject.merge_page`, but the stream to be
1617 merged is translated by applying a transformation matrix.
1619 Args:
1620 page2: the page to be merged into this one.
1621 tx: The translation on X axis
1622 ty: The translation on Y axis
1623 over: set the page2 content over page1 if True (default) else under
1624 expand: Whether the page should be expanded to fit the
1625 dimensions of the page to be merged.
1627 """
1628 op = Transformation().translate(tx, ty)
1629 self.merge_transformed_page(page2, op, over, expand)
1631 def add_transformation(
1632 self,
1633 ctm: Transformation | CompressedTransformationMatrix,
1634 expand: bool = False,
1635 ) -> None:
1636 """
1637 Apply a transformation matrix to the page.
1639 Args:
1640 ctm: A 6-element tuple containing the operands of the
1641 transformation matrix. Alternatively, a
1642 :py:class:`Transformation<pypdf.Transformation>`
1643 object can be passed.
1645 See :doc:`/user/cropping-and-transforming`.
1647 """
1648 if isinstance(ctm, Transformation):
1649 ctm = ctm.ctm
1650 content = self.get_contents()
1651 if content is not None:
1652 content = PageObject._add_transformation_matrix(content, self.pdf, ctm)
1653 content.isolate_graphics_state()
1654 self.replace_contents(content)
1655 # if expanding the page to fit a new page, calculate the new media box size
1656 if expand:
1657 corners = [
1658 self.mediabox.left.as_numeric(),
1659 self.mediabox.bottom.as_numeric(),
1660 self.mediabox.left.as_numeric(),
1661 self.mediabox.top.as_numeric(),
1662 self.mediabox.right.as_numeric(),
1663 self.mediabox.top.as_numeric(),
1664 self.mediabox.right.as_numeric(),
1665 self.mediabox.bottom.as_numeric(),
1666 ]
1668 ctm = tuple(float(x) for x in ctm) # type: ignore[assignment]
1669 new_x = [
1670 ctm[0] * corners[i] + ctm[2] * corners[i + 1] + ctm[4]
1671 for i in range(0, 8, 2)
1672 ]
1673 new_y = [
1674 ctm[1] * corners[i] + ctm[3] * corners[i + 1] + ctm[5]
1675 for i in range(0, 8, 2)
1676 ]
1678 self.mediabox.lower_left = (min(new_x), min(new_y))
1679 self.mediabox.upper_right = (max(new_x), max(new_y))
1681 def scale(self, sx: float, sy: float) -> None:
1682 """
1683 Scale a page by the given factors by applying a transformation matrix
1684 to its content and updating the page size.
1686 This updates the various page boundaries (bleedbox, trimbox, etc.)
1687 and the contents of the page.
1689 Args:
1690 sx: The scaling factor on horizontal axis.
1691 sy: The scaling factor on vertical axis.
1693 """
1694 self.add_transformation((sx, 0, 0, sy, 0, 0))
1695 self.bleedbox = self.bleedbox.scale(sx, sy)
1696 self.trimbox = self.trimbox.scale(sx, sy)
1697 self.artbox = self.artbox.scale(sx, sy)
1698 self.cropbox = self.cropbox.scale(sx, sy)
1699 self.mediabox = self.mediabox.scale(sx, sy)
1701 if PG.ANNOTS in self:
1702 annotations = self[PG.ANNOTS]
1703 if isinstance(annotations, ArrayObject):
1704 for annotation in annotations:
1705 annotation_obj = annotation.get_object()
1706 if AnnotationDictionaryAttributes.Rect in annotation_obj:
1707 rectangle = annotation_obj[AnnotationDictionaryAttributes.Rect]
1708 if isinstance(rectangle, ArrayObject):
1709 rectangle[0] = FloatObject(float(rectangle[0]) * sx)
1710 rectangle[1] = FloatObject(float(rectangle[1]) * sy)
1711 rectangle[2] = FloatObject(float(rectangle[2]) * sx)
1712 rectangle[3] = FloatObject(float(rectangle[3]) * sy)
1714 if PG.VP in self:
1715 viewport = self[PG.VP]
1716 if isinstance(viewport, ArrayObject):
1717 bbox = viewport[0]["/BBox"]
1718 else:
1719 bbox = viewport["/BBox"] # type: ignore[index]
1720 scaled_bbox = RectangleObject(
1721 (
1722 float(bbox[0]) * sx,
1723 float(bbox[1]) * sy,
1724 float(bbox[2]) * sx,
1725 float(bbox[3]) * sy,
1726 )
1727 )
1728 if isinstance(viewport, ArrayObject):
1729 self[NameObject(PG.VP)][NumberObject(0)][ # type: ignore[index]
1730 NameObject("/BBox")
1731 ] = scaled_bbox
1732 else:
1733 self[NameObject(PG.VP)][NameObject("/BBox")] = scaled_bbox # type: ignore[index]
1735 def scale_by(self, factor: float) -> None:
1736 """
1737 Scale a page by the given factor by applying a transformation matrix to
1738 its content and updating the page size.
1740 Args:
1741 factor: The scaling factor (for both X and Y axis).
1743 """
1744 self.scale(factor, factor)
1746 def scale_to(self, width: float, height: float) -> None:
1747 """
1748 Scale a page to the specified dimensions by applying a transformation
1749 matrix to its content and updating the page size.
1751 Args:
1752 width: The new width.
1753 height: The new height.
1755 """
1756 sx = width / float(self.mediabox.width)
1757 sy = height / float(self.mediabox.height)
1758 self.scale(sx, sy)
1760 def compress_content_streams(self, level: int = -1) -> None:
1761 """
1762 Compress the size of this page by joining all content streams and
1763 applying a FlateDecode filter.
1765 However, it is possible that this function will perform no action if
1766 content stream compression becomes "automatic".
1767 """
1768 content = self.get_contents()
1769 if content is not None:
1770 content_obj = content.flate_encode(level)
1771 try:
1772 content.indirect_reference.pdf._objects[ # type: ignore[union-attr]
1773 content.indirect_reference.idnum - 1 # type: ignore[union-attr]
1774 ] = content_obj
1775 except AttributeError as exception:
1776 if self.indirect_reference is not None and hasattr(
1777 self.indirect_reference.pdf, "_add_object"
1778 ):
1779 self.replace_contents(content_obj)
1780 else:
1781 raise ValueError("Page must be part of a PdfWriter") from exception
1783 @property
1784 def page_number(self) -> int | None:
1785 """
1786 Read-only property which returns the page number within the PDF file.
1788 Returns:
1789 Page number; None if the page is not attached to a PDF.
1791 """
1792 if self.indirect_reference is None:
1793 return None
1794 # Compare the indirect references, not the pages themselves: two pages
1795 # with identical contents compare equal, so `list.index` would return
1796 # the position of the first match for all of them.
1797 for number, page in enumerate(self.indirect_reference.pdf.pages):
1798 if page.indirect_reference == self.indirect_reference:
1799 return number
1800 return None
1802 def _debug_for_extract(self) -> str: # pragma: no cover
1803 out = ""
1804 for ope, op in ContentStream(
1805 self["/Contents"].get_object(), self.pdf, "bytes"
1806 ).operations:
1807 if op == b"TJ":
1808 s = [x for x in ope[0] if isinstance(x, str)]
1809 else:
1810 s = []
1811 out += op.decode("utf-8") + " " + "".join(s) + ope.__repr__() + "\n"
1812 out += "\n=============================\n"
1813 try:
1814 for fo in self[PG.RESOURCES]["/Font"]: # type: ignore[index]
1815 out += fo + "\n"
1816 out += self[PG.RESOURCES]["/Font"][fo].__repr__() + "\n" # type: ignore[index]
1817 try:
1818 enc_repr = self[PG.RESOURCES]["/Font"][fo][ # type: ignore[index]
1819 "/Encoding"
1820 ].__repr__()
1821 out += enc_repr + "\n"
1822 except MemoryError: # pragma: no cover # TODO: BLE001
1823 raise
1824 except Exception:
1825 pass
1826 try:
1827 out += (
1828 self[PG.RESOURCES]["/Font"][fo][ # type: ignore[index]
1829 "/ToUnicode"
1830 ]
1831 .get_data()
1832 .decode()
1833 + "\n"
1834 )
1835 except MemoryError: # pragma: no cover # TODO: BLE001
1836 raise
1837 except Exception:
1838 pass
1840 except KeyError:
1841 out += "No Font\n"
1842 return out
1844 def _extract_text(
1845 self,
1846 obj: DictionaryObject,
1847 pdf: Any,
1848 orientations: tuple[int, ...] = (0, 90, 180, 270),
1849 space_width: float = 200.0,
1850 content_key: str | None = PG.CONTENTS,
1851 visitor_operand_before: Callable[[Any, Any, Any, Any], None] | None = None,
1852 visitor_operand_after: Callable[[Any, Any, Any, Any], None] | None = None,
1853 visitor_text: Callable[[Any, Any, Any, Any, Any], None] | None = None,
1854 *,
1855 known_ids: set[int] | None = None,
1856 traversal_state: _TraversalState | None = None
1857 ) -> str:
1858 """
1859 See extract_text for most arguments.
1861 Args:
1862 content_key: indicate the default key where to extract data
1863 None = the object; this allows reusing the function on an XObject
1864 default = "/Content"
1866 """
1867 if known_ids is None:
1868 known_ids = set()
1869 if traversal_state is None:
1870 traversal_state = _TraversalState()
1872 extractor = TextExtraction()
1873 font_resources: dict[str, DictionaryObject] = {}
1874 fonts: dict[str, Font] = {}
1876 resources_dict = _get_page_resources(obj)
1877 if not resources_dict:
1878 # No resources means no text is possible (no font); we consider the
1879 # file as not damaged, no need to check for TJ or Tj
1880 return ""
1882 if font_resources_dict := _get_font_resources(resources_dict):
1883 for font_resource in font_resources_dict:
1884 try:
1885 font_resource_object = cast(DictionaryObject, font_resources_dict[font_resource].get_object())
1886 font_resources[font_resource] = font_resource_object
1887 fonts[font_resource] = Font.from_font_resource(font_resource_object)
1888 # Override space width, if applicable
1889 if fonts[font_resource].character_widths.get(fonts[font_resource].space_char, 0) == 0:
1890 fonts[font_resource].space_width = space_width
1891 except (AttributeError, TypeError):
1892 pass
1894 try:
1895 content = (
1896 obj[content_key].get_object() if isinstance(content_key, str) else obj
1897 )
1898 if not isinstance(content, ContentStream):
1899 content = ContentStream(content, pdf, "bytes")
1900 except (AttributeError, KeyError): # no content can be extracted (certainly empty page)
1901 return ""
1902 # We check all strings are TextStringObjects. ByteStringObjects
1903 # are strings where the byte->string encoding was unknown, so adding
1904 # them to the text here would be gibberish.
1906 # Initialize the extractor with the necessary parameters
1907 extractor.initialize_extraction(orientations, visitor_text, font_resources, fonts)
1909 for operands, operator in content.operations:
1910 if visitor_operand_before is not None:
1911 visitor_operand_before(operator, operands, extractor.cm_matrix, extractor.tm_matrix)
1912 # Multiple operators are handled here
1913 if operator == b"'":
1914 extractor.process_operation(b"T*", [])
1915 extractor.process_operation(b"Tj", operands)
1916 elif operator == b'"' and len(operands) >= 3:
1917 extractor.process_operation(b"Tw", [operands[0]])
1918 extractor.process_operation(b"Tc", [operands[1]])
1919 extractor.process_operation(b"T*", [])
1920 extractor.process_operation(b"Tj", operands[2:])
1921 elif operator == b"TJ":
1922 # The space width may be smaller than the font width, so the width should be 95%.
1923 _confirm_space_width = extractor._space_width * 0.95
1924 if operands and isinstance(operands[0], ArrayObject):
1925 for op in operands[0]:
1926 # A name is a str too, but not text to show
1927 if isinstance(op, (str, bytes)) and not isinstance(op, NameObject):
1928 extractor.process_operation(b"Tj", [op])
1929 if isinstance(op, (int, float, NumberObject, FloatObject)) and (
1930 abs(float(op)) >= _confirm_space_width
1931 and extractor.text
1932 and extractor.text[-1] != " "
1933 ):
1934 extractor.process_operation(b"Tj", [" "])
1935 elif operator == b"TD" and len(operands) >= 2:
1936 # a non-numeric ty leaves the leading unchanged, like a non-numeric TL
1937 if isinstance(operands[1], (int, float)):
1938 extractor.process_operation(b"TL", [-operands[1]])
1939 extractor.process_operation(b"Td", operands)
1940 elif operator == b"Do" and operands:
1941 extractor.output += extractor.text
1942 if visitor_text is not None:
1943 visitor_text(
1944 extractor.text,
1945 extractor.memo_cm,
1946 extractor.memo_tm,
1947 extractor.font_resource,
1948 extractor.font_size,
1949 )
1950 try:
1951 if extractor.output[-1] != "\n":
1952 extractor.output += "\n"
1953 if visitor_text is not None:
1954 visitor_text(
1955 "\n",
1956 extractor.memo_cm,
1957 extractor.memo_tm,
1958 extractor.font_resource,
1959 extractor.font_size,
1960 )
1961 except IndexError:
1962 pass
1963 try:
1964 xform_text = self._extract_text__xform(
1965 resources_dict=resources_dict,
1966 operands=operands,
1967 orientations=orientations,
1968 space_width=space_width,
1969 visitor_operand_before=visitor_operand_before,
1970 visitor_operand_after=visitor_operand_after,
1971 visitor_text=visitor_text,
1972 known_ids=known_ids,
1973 traversal_state=traversal_state
1974 )
1975 if xform_text is not None:
1976 text = xform_text
1977 extractor.output += text
1978 # Nothing else to do: each text piece inside the form has
1979 # already been reported via visitor_text while the form was
1980 # being extracted recursively (issue #4079).
1981 except MemoryError: # pragma: no cover # TODO: BLE001
1982 raise
1983 except Exception as exception:
1984 logger_warning(
1985 "Impossible to decode XFormObject %(operand)s: %(exception)s",
1986 source=__name__,
1987 operand=operands[0],
1988 exception=exception,
1989 )
1990 finally:
1991 extractor.text = ""
1992 extractor.memo_cm = extractor.cm_matrix.copy()
1993 extractor.memo_tm = extractor.tm_matrix.copy()
1994 else:
1995 extractor.process_operation(operator, operands)
1996 if visitor_operand_after is not None:
1997 visitor_operand_after(operator, operands, extractor.cm_matrix, extractor.tm_matrix)
1998 extractor.output += extractor.text # just in case
1999 if extractor.text != "" and visitor_text is not None:
2000 visitor_text(
2001 extractor.text,
2002 extractor.memo_cm,
2003 extractor.memo_tm,
2004 extractor.font_resource,
2005 extractor.font_size,
2006 )
2007 return extractor.output
2009 def _extract_text__xform(
2010 self,
2011 *,
2012 resources_dict: DictionaryObject,
2013 operands: Any,
2014 orientations: tuple[int, ...] = (0, 90, 180, 270),
2015 space_width: float = 200.0,
2016 visitor_operand_before: Callable[[Any, Any, Any, Any], None] | None = None,
2017 visitor_operand_after: Callable[[Any, Any, Any, Any], None] | None = None,
2018 visitor_text: Callable[[Any, Any, Any, Any, Any], None] | None = None,
2019 known_ids: set[int],
2020 traversal_state: _TraversalState
2021 ) -> str | None:
2022 xobj = cast(DictionaryObject, resources_dict["/XObject"])
2023 xform = cast(EncodedStreamObject, xobj[operands[0]])
2024 if xform["/Subtype"] == NameObject("/Image"):
2025 return None
2027 xform_id = id(xform)
2028 if xform_id in known_ids:
2029 logger_warning(
2030 "Detected cyclic form XObject reference, skipping %(operand)s.",
2031 source=__name__,
2032 operand=operands[0]
2033 )
2034 return ""
2036 configuration = get_configuration()
2037 if traversal_state.entry_count >= configuration.xform_maximum_invocations_per_extraction:
2038 if not traversal_state.has_logged:
2039 traversal_state.has_logged = True
2040 logger_warning(
2041 (
2042 "Exceeded %(limit)d form XObject invocations while extracting text; "
2043 "further form content is skipped."
2044 ),
2045 source=__name__,
2046 limit=configuration.xform_maximum_invocations_per_extraction
2047 )
2048 return ""
2050 traversal_state.entry_count += 1
2051 known_ids.add(xform_id)
2052 try:
2053 text = self.extract_xform_text(
2054 xform,
2055 orientations,
2056 space_width,
2057 visitor_operand_before,
2058 visitor_operand_after,
2059 visitor_text,
2060 known_ids=known_ids,
2061 traversal_state=traversal_state,
2062 )
2063 finally:
2064 known_ids.discard(xform_id)
2065 return text
2067 def _layout_mode_fonts(self) -> dict[str, Font]:
2068 """
2069 Get fonts formatted for "layout" mode text extraction.
2071 Returns:
2072 Dict[str, Font]: dictionary of Font instances keyed by font name
2074 """
2075 # Font retrieval logic adapted from pypdf.PageObject._extract_text()
2076 obj: Any = self
2077 fonts: dict[str, Font] = {}
2078 visited: set[int] = set()
2079 while True:
2080 obj_id = id(obj)
2081 if obj_id in visited:
2082 logger_warning("Detected cycle in /Parent hierarchy when retrieving fonts.", source=__name__)
2083 break
2084 visited.add(obj_id)
2086 resources_dict: Any = obj.get(PG.RESOURCES, DictionaryObject()).get_object()
2087 if not isinstance(resources_dict, DictionaryObject):
2088 logger_warning(
2089 "Page resources are not a dictionary: %(resources)s",
2090 source=__name__,
2091 resources=resources_dict,
2092 )
2093 resources_dict = DictionaryObject()
2094 if self.pdf is not None and (font_resources := _get_font_resources(resources_dict)):
2095 for font_name in font_resources:
2096 font_object = font_resources[font_name].get_object()
2097 if isinstance(font_object, DictionaryObject):
2098 fonts[font_name] = Font.from_font_resource(font_object)
2100 parent = obj.get("/Parent", NullObject()).get_object()
2101 if not isinstance(parent, DictionaryObject):
2102 break
2103 obj = parent
2105 return fonts
2107 def _layout_mode_text(
2108 self,
2109 space_vertically: bool = True,
2110 scale_weight: float = 1.25,
2111 strip_rotated: bool = True,
2112 debug_path: Path | None = None,
2113 font_height_weight: float = 1,
2114 ) -> str:
2115 """
2116 Get text preserving fidelity to source PDF text layout.
2118 Args:
2119 space_vertically: include blank lines inferred from y distance + font
2120 height. Defaults to True.
2121 scale_weight: multiplier for string length when calculating weighted
2122 average character width. Defaults to 1.25.
2123 strip_rotated: Removes text that is rotated w.r.t. to the page from
2124 layout mode output. Defaults to True.
2125 debug_path (Path | None): if supplied, must target a directory.
2126 creates the following files with debug information for layout mode
2127 functions if supplied:
2128 - fonts.json: output of self._layout_mode_fonts
2129 - tjs.json: individual text render ops with corresponding transform matrices
2130 - bts.json: text render ops left justified and grouped by BT/ET operators
2131 - bt_groups.json: BT/ET operations grouped by rendered y-coord (aka lines)
2132 Defaults to None.
2133 font_height_weight: multiplier for font height when calculating
2134 blank lines. Defaults to 1.
2136 Returns:
2137 str: multiline string containing page text in a fixed width format that
2138 closely adheres to the rendered layout in the source pdf.
2140 """
2141 fonts = self._layout_mode_fonts()
2142 if debug_path: # pragma: no cover
2143 import json # noqa: PLC0415
2145 debug_path.joinpath("fonts.json").write_text(
2146 json.dumps(fonts, indent=2, default=asdict),
2147 "utf-8"
2148 )
2150 contents = self.get("/Contents")
2151 if contents is not None:
2152 contents = contents.get_object()
2153 if not isinstance(contents, (ArrayObject, StreamObject)):
2154 # No content can be extracted (certainly an empty page).
2155 return ""
2157 ops = iter(ContentStream(contents, self.pdf, "bytes").operations)
2158 bt_groups = _layout_mode.text_show_operations(
2159 ops, fonts, strip_rotated, debug_path
2160 )
2162 if not bt_groups:
2163 return ""
2165 ty_groups = _layout_mode.y_coordinate_groups(bt_groups, debug_path)
2167 char_width = _layout_mode.fixed_char_width(bt_groups, scale_weight)
2169 return _layout_mode.fixed_width_page(ty_groups, char_width, space_vertically, font_height_weight)
2171 def extract_text(
2172 self,
2173 *args: Any,
2174 orientations: int | tuple[int, ...] = (0, 90, 180, 270),
2175 space_width: float = 200.0,
2176 visitor_operand_before: Callable[[Any, Any, Any, Any], None] | None = None,
2177 visitor_operand_after: Callable[[Any, Any, Any, Any], None] | None = None,
2178 visitor_text: Callable[[Any, Any, Any, Any, Any], None] | None = None,
2179 extraction_mode: Literal["plain", "layout"] = "plain",
2180 **kwargs: Any,
2181 ) -> str:
2182 """
2183 Locate all text drawing commands, in the order they are provided in the
2184 content stream, and extract the text.
2186 This works well for some PDF files, but poorly for others, depending on
2187 the generator used. This will be refined in the future.
2189 Do not rely on the order of text coming out of this function, as it
2190 will change if this function is made more sophisticated.
2192 Arabic and Hebrew are extracted in the correct order.
2193 If required a custom RTL range of characters can be defined;
2194 see function set_custom_rtl.
2196 Additionally you can provide visitor methods to get informed on all
2197 operations and all text objects.
2198 For example in some PDF files this can be useful to parse tables.
2200 Args:
2201 orientations: list of orientations extract_text will look for
2202 default = (0, 90, 180, 270)
2203 note: currently only 0 (up),90 (turned left), 180 (upside down),
2204 270 (turned right)
2205 Silently ignored in "layout" mode.
2206 space_width: force default space width
2207 if not extracted from font (default: 200)
2208 Silently ignored in "layout" mode.
2209 visitor_operand_before: function to be called before processing an operation.
2210 It has four arguments: operator, operand-arguments,
2211 current transformation matrix and text matrix.
2212 Ignored with a warning in "layout" mode.
2213 visitor_operand_after: function to be called after processing an operation.
2214 It has four arguments: operator, operand-arguments,
2215 current transformation matrix and text matrix.
2216 Ignored with a warning in "layout" mode.
2217 visitor_text: function to be called when extracting some text at some position.
2218 It has five arguments: text, current transformation matrix,
2219 text matrix, font-dictionary and font-size.
2220 The font-dictionary may be None in case of unknown fonts.
2221 If not None it may e.g. contain key "/BaseFont" with value "/Arial,Bold".
2222 Ignored with a warning in "layout" mode.
2223 extraction_mode (Literal["plain", "layout"]): "plain" for legacy functionality,
2224 "layout" for experimental layout mode functionality.
2225 NOTE: orientations, space_width, and visitor_* parameters are NOT respected
2226 in "layout" mode.
2228 kwargs:
2229 layout_mode_space_vertically (bool): include blank lines inferred from
2230 y distance + font height. Defaults to True.
2231 layout_mode_scale_weight (float): multiplier for string length when calculating
2232 weighted average character width. Defaults to 1.25.
2233 layout_mode_strip_rotated (bool): layout mode does not support rotated text.
2234 Set to False to include rotated text anyway. If rotated text is discovered,
2235 layout will be degraded and a warning will result. Defaults to True.
2236 layout_mode_debug_path (Path | None): if supplied, must target a directory.
2237 creates the following files with debug information for layout mode
2238 functions if supplied:
2240 - fonts.json: output of self._layout_mode_fonts
2241 - tjs.json: individual text render ops with corresponding transform matrices
2242 - bts.json: text render ops left justified and grouped by BT/ET operators
2243 - bt_groups.json: BT/ET operations grouped by rendered y-coord (aka lines)
2244 layout_mode_font_height_weight (float): multiplier for font height when calculating
2245 blank lines. Defaults to 1.
2247 Returns:
2248 The extracted text
2250 """
2251 if extraction_mode not in ["plain", "layout"]:
2252 raise ValueError(f"Invalid text extraction mode '{extraction_mode}'")
2253 if extraction_mode == "layout":
2254 for visitor in (
2255 "visitor_operand_before",
2256 "visitor_operand_after",
2257 "visitor_text",
2258 ):
2259 if locals()[visitor]:
2260 logger_warning(
2261 "Argument %(visitor)s is ignored in layout mode",
2262 source=__name__,
2263 visitor=visitor,
2264 )
2265 return self._layout_mode_text(
2266 space_vertically=kwargs.get("layout_mode_space_vertically", True),
2267 scale_weight=kwargs.get("layout_mode_scale_weight", 1.25),
2268 strip_rotated=kwargs.get("layout_mode_strip_rotated", True),
2269 debug_path=kwargs.get("layout_mode_debug_path"),
2270 font_height_weight=kwargs.get("layout_mode_font_height_weight", 1)
2271 )
2272 if len(args) >= 1:
2273 if isinstance(args[0], str):
2274 if len(args) >= 3:
2275 if isinstance(args[2], (tuple, int)):
2276 orientations = args[2]
2277 else:
2278 raise TypeError(f"Invalid positional parameter {args[2]}")
2279 if len(args) >= 4:
2280 if isinstance(args[3], (float, int)):
2281 space_width = args[3]
2282 else:
2283 raise TypeError(f"Invalid positional parameter {args[3]}")
2284 elif isinstance(args[0], (tuple, int)):
2285 orientations = args[0]
2286 if len(args) >= 2:
2287 if isinstance(args[1], (float, int)):
2288 space_width = args[1]
2289 else:
2290 raise TypeError(f"Invalid positional parameter {args[1]}")
2291 else:
2292 raise TypeError(f"Invalid positional parameter {args[0]}")
2294 if isinstance(orientations, int):
2295 orientations = (orientations,)
2297 return self._extract_text(
2298 self,
2299 self.pdf,
2300 orientations,
2301 space_width,
2302 PG.CONTENTS,
2303 visitor_operand_before,
2304 visitor_operand_after,
2305 visitor_text,
2306 )
2308 def extract_xform_text(
2309 self,
2310 xform: EncodedStreamObject,
2311 orientations: tuple[int, ...] = (0, 90, 270, 360),
2312 space_width: float = 200.0,
2313 visitor_operand_before: Callable[[Any, Any, Any, Any], None] | None = None,
2314 visitor_operand_after: Callable[[Any, Any, Any, Any], None] | None = None,
2315 visitor_text: Callable[[Any, Any, Any, Any, Any], None] | None = None,
2316 *,
2317 known_ids: set[int] | None = None,
2318 traversal_state: Any | None = None
2319 ) -> str:
2320 """
2321 Extract text from an XObject.
2323 Args:
2324 xform:
2325 orientations:
2326 space_width: force default space width (if not extracted from font (default 200)
2327 visitor_operand_before:
2328 visitor_operand_after:
2329 visitor_text:
2330 known_ids:
2331 traversal_state:
2333 Returns:
2334 The extracted text
2336 """
2337 # The type hint would have to use an internal type otherwise, which is not desired.
2338 assert traversal_state is None or isinstance(traversal_state, _TraversalState)
2339 return self._extract_text(
2340 xform,
2341 self.pdf,
2342 orientations,
2343 space_width,
2344 None,
2345 visitor_operand_before,
2346 visitor_operand_after,
2347 visitor_text,
2348 known_ids=known_ids,
2349 traversal_state=traversal_state,
2350 )
2352 def _get_fonts(self) -> tuple[set[str], set[str]]:
2353 """
2354 Get the names of embedded fonts and unembedded fonts.
2356 Returns:
2357 A tuple (set of embedded fonts, set of unembedded fonts)
2359 """
2360 obj = self.get_object()
2361 assert isinstance(obj, DictionaryObject)
2362 fonts: set[str] = set()
2363 embedded: set[str] = set()
2364 fonts, embedded = _get_fonts_walk(obj, fonts, embedded)
2365 unembedded = fonts - embedded
2366 return embedded, unembedded
2368 mediabox = _create_rectangle_accessor(PG.MEDIABOX, ())
2369 """A :class:`RectangleObject<pypdf.generic.RectangleObject>`, expressed in
2370 default user space units, defining the boundaries of the physical medium on
2371 which the page is intended to be displayed or printed."""
2373 cropbox = _create_rectangle_accessor("/CropBox", (PG.MEDIABOX,))
2374 """
2375 A :class:`RectangleObject<pypdf.generic.RectangleObject>`, expressed in
2376 default user space units, defining the visible region of default user
2377 space.
2379 When the page is displayed or printed, its contents are to be clipped
2380 (cropped) to this rectangle and then imposed on the output medium in some
2381 implementation-defined manner. Default value: same as
2382 :attr:`mediabox<mediabox>`.
2383 """
2385 bleedbox = _create_rectangle_accessor("/BleedBox", ("/CropBox", PG.MEDIABOX))
2386 """A :class:`RectangleObject<pypdf.generic.RectangleObject>`, expressed in
2387 default user space units, defining the region to which the contents of the
2388 page should be clipped when output in a production environment."""
2390 trimbox = _create_rectangle_accessor("/TrimBox", ("/CropBox", PG.MEDIABOX))
2391 """A :class:`RectangleObject<pypdf.generic.RectangleObject>`, expressed in
2392 default user space units, defining the intended dimensions of the finished
2393 page after trimming."""
2395 artbox = _create_rectangle_accessor("/ArtBox", ("/CropBox", PG.MEDIABOX))
2396 """A :class:`RectangleObject<pypdf.generic.RectangleObject>`, expressed in
2397 default user space units, defining the extent of the page's meaningful
2398 content as intended by the page's creator."""
2400 @property
2401 def annotations(self) -> ArrayObject | None:
2402 if "/Annots" not in self:
2403 return None
2404 annotations = self["/Annots"].get_object()
2405 if not isinstance(annotations, ArrayObject):
2406 logger_warning(
2407 "Annotations are not an array: %(annotations)s",
2408 source=__name__,
2409 annotations=annotations,
2410 )
2411 return None
2412 return annotations
2414 @annotations.setter
2415 def annotations(self, value: ArrayObject | None) -> None:
2416 """
2417 Set the annotations array of the page.
2419 Typically you do not want to set this value, but append to it.
2420 If you append to it, remember to add the object first to the writer
2421 and only add the indirect object.
2422 """
2423 if value is None:
2424 if "/Annots" not in self:
2425 return
2426 del self[NameObject("/Annots")]
2427 else:
2428 self[NameObject("/Annots")] = value
2430 def add_action(self, trigger: PageTrigger, action: Action) -> None:
2431 """
2432 Add an action which will launch on the given trigger event of this page.
2434 Args:
2435 trigger: The action trigger to use.
2436 action: The action to be done.
2438 Example:
2439 >>> from pypdf import PdfWriter
2440 >>> from pypdf.actions import JavaScript, PageTrigger
2441 >>> writer = PdfWriter()
2442 >>> page = writer.add_blank_page(595, 842)
2443 >>> # Display the page number when the page is opened
2444 >>> page.add_action(PageTrigger("open"), JavaScript("app.alert('This is page ' + this.pageNum);"))
2445 >>> # Display the page number when the page is closed
2446 >>> page.add_action(PageTrigger("close"), JavaScript("app.alert('This is page ' + this.pageNum);"))
2447 """
2448 return Action._create_new(self, trigger, action)
2450 def delete_action(self, trigger: PageTrigger) -> None:
2451 """
2452 Delete all actions associated with an open or close trigger event of this page.
2454 Args:
2455 trigger: An open or close trigger.
2457 Example:
2458 >>> from pypdf import PdfWriter
2459 >>> from pypdf.actions import JavaScript, PageTrigger
2460 >>> writer = PdfWriter()
2461 >>> page = writer.add_blank_page(595, 842)
2462 >>> page.add_action(PageTrigger("open"), JavaScript("app.alert('This is page ' + this.pageNum);"))
2463 >>> page.add_action(PageTrigger("close"), JavaScript("app.alert('This is page ' + this.pageNum);"))
2464 >>> # Delete all actions triggered by a page open
2465 >>> page.delete_action(PageTrigger("open"))
2466 >>> # Delete all actions triggered by a page close
2467 >>> page.delete_action(PageTrigger("close"))
2468 """
2469 return Action._delete(self, trigger)
2472class _VirtualList(Sequence[PageObject]):
2473 def __init__(
2474 self,
2475 length_function: Callable[[], int],
2476 get_function: Callable[[int], PageObject],
2477 ) -> None:
2478 self.length_function = length_function
2479 self.get_function = get_function
2480 self.current = -1
2482 def __len__(self) -> int:
2483 return self.length_function()
2485 @overload
2486 def __getitem__(self, index: int) -> PageObject:
2487 ...
2489 @overload
2490 def __getitem__(self, index: slice) -> Sequence[PageObject]:
2491 ...
2493 def __getitem__(
2494 self, index: int | slice
2495 ) -> PageObject | Sequence[PageObject]:
2496 if isinstance(index, slice):
2497 indices = range(*index.indices(len(self)))
2498 cls = type(self)
2499 return cls(indices.__len__, lambda idx: self[indices[idx]])
2500 if not isinstance(index, int):
2501 raise TypeError("Sequence indices must be integers")
2502 len_self = len(self)
2503 if index < 0:
2504 # support negative indexes
2505 index += len_self
2506 if not (0 <= index < len_self):
2507 raise IndexError("Sequence index out of range")
2508 return self.get_function(index)
2510 def __delitem__(self, index: int | slice) -> None:
2511 if isinstance(index, slice):
2512 r = list(range(*index.indices(len(self))))
2513 # pages have to be deleted from last to first
2514 r.sort()
2515 r.reverse()
2516 for p in r:
2517 del self[p] # recursive call
2518 return
2519 if not isinstance(index, int):
2520 raise TypeError("Index must be integers")
2521 len_self = len(self)
2522 if index < 0:
2523 # support negative indexes
2524 index += len_self
2525 if not (0 <= index < len_self):
2526 raise IndexError("Index out of range")
2527 ind = self[index].indirect_reference
2528 assert ind is not None
2529 parent: PdfObject | None = cast(DictionaryObject, ind.get_object()).get(
2530 "/Parent", None
2531 )
2532 first = True
2533 while parent is not None:
2534 parent = cast(DictionaryObject, parent.get_object())
2535 try:
2536 i = cast(ArrayObject, parent["/Kids"]).index(ind)
2537 del cast(ArrayObject, parent["/Kids"])[i]
2538 first = False
2539 try:
2540 assert ind is not None
2541 del ind.pdf.flattened_pages[index] # case of page in a Reader
2542 except MemoryError: # pragma: no cover # TODO: BLE001
2543 raise
2544 except Exception: # pragma: no cover
2545 pass
2546 if "/Count" in parent:
2547 parent[NameObject("/Count")] = NumberObject(
2548 cast(int, parent["/Count"]) - 1
2549 )
2550 if len(cast(ArrayObject, parent["/Kids"])) == 0:
2551 # No more objects in this part of this subtree
2552 ind = parent.indirect_reference
2553 parent = parent.get("/Parent", None)
2554 except ValueError as exception: # from index
2555 if first:
2556 raise PdfReadError(f"Page not found in page tree: {ind}") from exception
2557 break
2559 def __iter__(self) -> Iterator[PageObject]:
2560 for i in range(len(self)):
2561 yield self[i]
2563 def __str__(self) -> str:
2564 p = [f"PageObject({i})" for i in range(self.length_function())]
2565 return f"[{', '.join(p)}]"
2568def _get_fonts_walk(
2569 obj: DictionaryObject,
2570 fnt: set[str],
2571 emb: set[str],
2572) -> tuple[set[str], set[str]]:
2573 """
2574 Get the set of all fonts and all embedded fonts.
2576 Args:
2577 obj: Page resources dictionary
2578 fnt: font
2579 emb: embedded fonts
2581 Returns:
2582 A tuple (fnt, emb)
2584 If there is a key called 'BaseFont', that is a font that is used in the document.
2585 If there is a key called 'FontName' and another key in the same dictionary object
2586 that is called 'FontFilex' (where x is null, 2, or 3), then that fontname is
2587 embedded.
2589 We create and add to two sets, fnt = fonts used and emb = fonts embedded.
2591 """
2592 fontkeys = ("/FontFile", "/FontFile2", "/FontFile3")
2594 def process_font(f: PdfObject) -> None:
2595 nonlocal fnt, emb
2596 f = cast(DictionaryObject, f.get_object()) # to be sure
2597 if "/BaseFont" in f:
2598 fnt.add(cast(str, f["/BaseFont"]))
2600 if (
2601 ("/CharProcs" in f)
2602 or (
2603 "/FontDescriptor" in f
2604 and any(
2605 x in cast(DictionaryObject, f["/FontDescriptor"]) for x in fontkeys
2606 )
2607 )
2608 or (
2609 "/DescendantFonts" in f
2610 and "/FontDescriptor"
2611 in cast(
2612 DictionaryObject,
2613 cast(ArrayObject, f["/DescendantFonts"])[0].get_object(),
2614 )
2615 and any(
2616 x
2617 in cast(
2618 DictionaryObject,
2619 cast(
2620 DictionaryObject,
2621 cast(ArrayObject, f["/DescendantFonts"])[0].get_object(),
2622 )["/FontDescriptor"],
2623 )
2624 for x in fontkeys
2625 )
2626 )
2627 ):
2628 # the list comprehension ensures there is FontFile
2629 try:
2630 emb.add(cast(str, f["/BaseFont"]))
2631 except KeyError:
2632 emb.add("(" + cast(str, f["/Subtype"]) + ")")
2634 if "/DR" in obj and "/Font" in cast(DictionaryObject, obj["/DR"]):
2635 for f in cast(
2636 DictionaryObject, cast(DictionaryObject, obj["/DR"])["/Font"]
2637 ).values():
2638 process_font(f)
2639 if "/Resources" in obj:
2640 if "/Font" in cast(DictionaryObject, obj["/Resources"]):
2641 for f in cast(
2642 DictionaryObject, cast(DictionaryObject, obj["/Resources"])["/Font"]
2643 ).values():
2644 process_font(f)
2645 if "/XObject" in cast(DictionaryObject, obj["/Resources"]):
2646 for x in cast(
2647 DictionaryObject, cast(DictionaryObject, obj["/Resources"])["/XObject"]
2648 ).values():
2649 _get_fonts_walk(cast(DictionaryObject, x.get_object()), fnt, emb)
2650 if "/Annots" in obj:
2651 for a in cast(ArrayObject, obj["/Annots"]):
2652 _get_fonts_walk(cast(DictionaryObject, a.get_object()), fnt, emb)
2653 if "/AP" in obj:
2654 if (
2655 cast(DictionaryObject, cast(DictionaryObject, obj["/AP"])["/N"]).get(
2656 "/Type"
2657 )
2658 == "/XObject"
2659 ):
2660 _get_fonts_walk(
2661 cast(DictionaryObject, cast(DictionaryObject, obj["/AP"])["/N"]),
2662 fnt,
2663 emb,
2664 )
2665 else:
2666 for a in cast(DictionaryObject, cast(DictionaryObject, obj["/AP"])["/N"]):
2667 _get_fonts_walk(cast(DictionaryObject, a), fnt, emb)
2668 return fnt, emb # return the sets for each page