Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/pypdf/_page.py: 15%

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

1043 statements  

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. 

29 

30import contextlib 

31import math 

32from collections.abc import Callable, Iterable, Iterator, Sequence 

33from copy import deepcopy 

34from dataclasses import asdict, dataclass 

35from decimal import Decimal 

36from io import BytesIO 

37from pathlib import Path 

38from typing import ( 

39 Any, 

40 Literal, 

41 NoReturn, 

42 cast, 

43 overload, 

44) 

45 

46from ._configuration import get_configuration 

47from ._protocols import PdfCommonDocProtocol 

48from ._text_extraction import ( 

49 _layout_mode, 

50) 

51from ._text_extraction._text_extractor import TextExtraction 

52from ._utils import ( 

53 CompressedTransformationMatrix, 

54 TransformationMatrixType, 

55 _human_readable_bytes, 

56 _TraversalState, 

57 deprecation, 

58 deprecation_no_replacement, 

59 deprecation_with_replacement, 

60 logger_warning, 

61 matrix_multiply, 

62) 

63from .actions import Action, PageTrigger 

64from .constants import ( 

65 _INLINE_IMAGE_KEY_MAPPING, 

66 _INLINE_IMAGE_VALUE_MAPPING, 

67 AnnotationDictionaryAttributes, 

68 ImageAttributes, 

69 PageAttributes, 

70 Resources, 

71) 

72from .errors import LimitReachedError, PageSizeNotDefinedError, PdfReadError 

73from .generic import ( 

74 ArrayObject, 

75 ContentStream, 

76 DictionaryObject, 

77 EncodedStreamObject, 

78 FloatObject, 

79 IndirectObject, 

80 NameObject, 

81 NullObject, 

82 NumberObject, 

83 PdfObject, 

84 RectangleObject, 

85 StreamObject, 

86 is_null_or_none, 

87) 

88from .generic._font import Font 

89 

90try: 

91 from PIL.Image import Image 

92 

93 pil_not_imported = False 

94except ImportError: 

95 Image = object # type: ignore[assignment,misc,unused-ignore] # TODO: Remove unused-ignore on Python 3.10 

96 pil_not_imported = True # error will be raised only when using images 

97 

98MERGE_CROP_BOX = "cropbox" # DEPRECATED: Use pypdf.Configuration. 

99 

100 

101def _get_page_resources(obj: Any, inherit: bool = True) -> DictionaryObject: 

102 """ 

103 Return the /Resources, or an empty dictionary if missing or malformed. 

104 

105 With ``inherit=False``, only the /Resources set on the page itself are used, 

106 not those inherited from its parents. 

107 """ 

108 if inherit: 

109 resources = obj.get_inherited(key=PageAttributes.RESOURCES, default=DictionaryObject()) 

110 else: 

111 resources = obj.get(PageAttributes.RESOURCES) 

112 if is_null_or_none(resources): 

113 return DictionaryObject() 

114 resources = resources.get_object() 

115 if not isinstance(resources, DictionaryObject): 

116 logger_warning( 

117 "Page resources are not a dictionary: %(resources)s", 

118 source=__name__, 

119 resources=resources, 

120 ) 

121 return DictionaryObject() 

122 return resources 

123 

124 

125def _get_font_resources(resources: Any) -> DictionaryObject: 

126 """Return the /Font resources, or an empty dictionary if missing or malformed.""" 

127 fonts = resources.get(Resources.FONT) 

128 if is_null_or_none(fonts): 

129 return DictionaryObject() 

130 fonts = fonts.get_object() 

131 if not isinstance(fonts, DictionaryObject): 

132 logger_warning( 

133 "Font resources are not a dictionary: %(fonts)s", 

134 source=__name__, 

135 fonts=fonts, 

136 ) 

137 return DictionaryObject() 

138 return fonts 

139 

140 

141def _get_rectangle(self: Any, name: str, defaults: Iterable[str]) -> RectangleObject: 

142 retval: PdfObject = self.get(name, NullObject()).get_object() 

143 if isinstance(retval, RectangleObject): 

144 return retval 

145 if is_null_or_none(retval): 

146 for d in defaults: 

147 retval = self.get(d, NullObject()).get_object() 

148 if not is_null_or_none(retval): 

149 break 

150 if not isinstance(retval, ArrayObject): 

151 raise TypeError(f"Expected an array of four values for {name}, got {retval}") 

152 if (length := len(retval)) != 4: 

153 if length > 4: 

154 # Keep backwards-compatibility with files previously written in a 

155 # broken way by pypdf, which carried more than four values. 

156 logger_warning( 

157 "Expected four values, got %(length)d: %(retval)s", 

158 source=__name__, 

159 length=length, 

160 retval=retval, 

161 ) 

162 retval = RectangleObject(tuple(retval[:4])) 

163 else: 

164 raise ValueError( 

165 f"Expected four values for {name}, got {length}: {retval}" 

166 ) 

167 else: 

168 retval = RectangleObject(retval) 

169 _set_rectangle(self, name, retval) 

170 return retval 

171 

172 

173def _set_rectangle(self: Any, name: str, value: RectangleObject | float) -> None: 

174 if isinstance(value, (list, tuple)) and len(value) < 4: 

175 # The getter tolerates more than four values for backwards compatibility 

176 # but cannot do anything with fewer, so writing them would produce a page 

177 # whose box cannot be read back. 

178 raise ValueError( 

179 f"Expected four values for {name}, got {len(value)}: {value}" 

180 ) 

181 self[NameObject(name)] = value 

182 

183 

184def _delete_rectangle(self: Any, name: str) -> None: 

185 del self[name] 

186 

187 

188def _create_rectangle_accessor(name: str, fallback: Iterable[str]) -> property: 

189 return property( 

190 lambda self: _get_rectangle(self, name, fallback), 

191 lambda self, value: _set_rectangle(self, name, value), 

192 lambda self: _delete_rectangle(self, name), 

193 ) 

194 

195 

196class Transformation: 

197 """ 

198 Represent a 2D transformation. 

199 

200 The transformation between two coordinate systems is represented by a 3-by-3 

201 transformation matrix with the following form:: 

202 

203 a b 0 

204 c d 0 

205 e f 1 

206 

207 Because a transformation matrix has only six elements that can be changed, 

208 it is usually specified in PDF as the six-element array [ a b c d e f ]. 

209 

210 Coordinate transformations are expressed as matrix multiplications:: 

211 

212 a b 0 

213 [ x′ y′ 1 ] = [ x y 1 ] × c d 0 

214 e f 1 

215 

216 

217 Example: 

218 >>> from pypdf import PdfWriter, Transformation 

219 >>> page = PdfWriter().add_blank_page(800, 600) 

220 >>> op = Transformation().scale(sx=2, sy=3).translate(tx=10, ty=20) 

221 >>> page.add_transformation(op) 

222 

223 """ 

224 

225 def __init__(self, ctm: CompressedTransformationMatrix = (1, 0, 0, 1, 0, 0)) -> None: 

226 self.ctm = ctm 

227 

228 @property 

229 def matrix(self) -> TransformationMatrixType: 

230 """ 

231 Return the transformation matrix as a tuple of tuples in the form: 

232 

233 ((a, b, 0), (c, d, 0), (e, f, 1)) 

234 """ 

235 return ( 

236 (self.ctm[0], self.ctm[1], 0), 

237 (self.ctm[2], self.ctm[3], 0), 

238 (self.ctm[4], self.ctm[5], 1), 

239 ) 

240 

241 @staticmethod 

242 def compress(matrix: TransformationMatrixType) -> CompressedTransformationMatrix: 

243 """ 

244 Compresses the transformation matrix into a tuple of (a, b, c, d, e, f). 

245 

246 Args: 

247 matrix: The transformation matrix as a tuple of tuples. 

248 

249 Returns: 

250 A tuple representing the transformation matrix as (a, b, c, d, e, f) 

251 

252 """ 

253 return ( 

254 matrix[0][0], 

255 matrix[0][1], 

256 matrix[1][0], 

257 matrix[1][1], 

258 matrix[2][0], 

259 matrix[2][1], 

260 ) 

261 

262 def _to_cm(self) -> str: 

263 # Returns the cm operation string for the given transformation matrix 

264 return ( 

265 f"{self.ctm[0]:.4f} {self.ctm[1]:.4f} {self.ctm[2]:.4f} " 

266 f"{self.ctm[3]:.4f} {self.ctm[4]:.4f} {self.ctm[5]:.4f} cm" 

267 ) 

268 

269 def transform(self, m: "Transformation") -> "Transformation": 

270 """ 

271 Apply one transformation to another. 

272 

273 Args: 

274 m: a Transformation to apply. 

275 

276 Returns: 

277 A new ``Transformation`` instance 

278 

279 Example: 

280 >>> from pypdf import PdfWriter, Transformation 

281 >>> height, width = 40, 50 

282 >>> page = PdfWriter().add_blank_page(800, 600) 

283 >>> op = Transformation((1, 0, 0, -1, 0, height)) # vertical mirror 

284 >>> op = Transformation().transform(Transformation((-1, 0, 0, 1, width, 0))) # horizontal mirror 

285 >>> page.add_transformation(op) 

286 

287 """ 

288 ctm = Transformation.compress(matrix_multiply(self.matrix, m.matrix)) 

289 return Transformation(ctm) 

290 

291 def translate(self, tx: float = 0, ty: float = 0) -> "Transformation": 

292 """ 

293 Translate the contents of a page. 

294 

295 Args: 

296 tx: The translation along the x-axis. 

297 ty: The translation along the y-axis. 

298 

299 Returns: 

300 A new ``Transformation`` instance 

301 

302 """ 

303 m = self.ctm 

304 return Transformation(ctm=(m[0], m[1], m[2], m[3], m[4] + tx, m[5] + ty)) 

305 

306 def scale( 

307 self, sx: float | None = None, sy: float | None = None 

308 ) -> "Transformation": 

309 """ 

310 Scale the contents of a page towards the origin of the coordinate system. 

311 

312 Typically, that is the lower-left corner of the page. That can be 

313 changed by translating the contents / the page boxes. 

314 

315 Args: 

316 sx: The scale factor along the x-axis. 

317 sy: The scale factor along the y-axis. 

318 

319 Returns: 

320 A new Transformation instance with the scaled matrix. 

321 

322 """ 

323 if sx is None and sy is None: 

324 raise ValueError("Either sx or sy must be specified") 

325 if sx is None: 

326 sx = sy 

327 if sy is None: 

328 sy = sx 

329 assert sx is not None 

330 assert sy is not None 

331 op: TransformationMatrixType = ((sx, 0, 0), (0, sy, 0), (0, 0, 1)) 

332 ctm = Transformation.compress(matrix_multiply(self.matrix, op)) 

333 return Transformation(ctm) 

334 

335 def rotate(self, rotation: float) -> "Transformation": 

336 """ 

337 Rotate the contents of a page. 

338 

339 Args: 

340 rotation: The angle of rotation in degrees. 

341 

342 Returns: 

343 A new ``Transformation`` instance with the rotated matrix. 

344 

345 """ 

346 rotation = math.radians(rotation) 

347 op: TransformationMatrixType = ( 

348 (math.cos(rotation), math.sin(rotation), 0), 

349 (-math.sin(rotation), math.cos(rotation), 0), 

350 (0, 0, 1), 

351 ) 

352 ctm = Transformation.compress(matrix_multiply(self.matrix, op)) 

353 return Transformation(ctm) 

354 

355 def __repr__(self) -> str: 

356 return f"Transformation(ctm={self.ctm})" 

357 

358 @overload 

359 def apply_on(self, pt: list[float], as_object: bool = False) -> list[float]: 

360 ... 

361 

362 @overload 

363 def apply_on( 

364 self, pt: tuple[float, float], as_object: bool = False 

365 ) -> tuple[float, float]: 

366 ... 

367 

368 def apply_on( 

369 self, 

370 pt: tuple[float, float] | list[float], 

371 as_object: bool = False, 

372 ) -> tuple[float, float] | list[float]: 

373 """ 

374 Apply the transformation matrix on the given point. 

375 

376 Args: 

377 pt: A tuple or list representing the point in the form (x, y). 

378 as_object: If True, return items as FloatObject, otherwise as plain floats. 

379 

380 Returns: 

381 A tuple or list representing the transformed point in the form (x', y') 

382 

383 """ 

384 typ = FloatObject if as_object else float 

385 pt1 = ( 

386 typ(float(pt[0]) * self.ctm[0] + float(pt[1]) * self.ctm[2] + self.ctm[4]), 

387 typ(float(pt[0]) * self.ctm[1] + float(pt[1]) * self.ctm[3] + self.ctm[5]), 

388 ) 

389 return list(pt1) if isinstance(pt, list) else pt1 

390 

391 

392@dataclass 

393class ImageFile: 

394 """ 

395 Image within the PDF file. *This object is not designed to be built.* 

396 

397 This object should not be modified except using :func:`ImageFile.replace` to replace the image with a new one. 

398 """ 

399 

400 name: str = "" 

401 """ 

402 Filename as identified within the PDF file. 

403 

404 .. warning:: 

405 

406 This value can contain arbitrary characters. Please make sure to sanitize it before 

407 using it to write the file content to the disk for example. 

408 """ 

409 

410 data: bytes = b"" 

411 """ 

412 Data as bytes. 

413 """ 

414 

415 image: Image | None = None 

416 """ 

417 Data as PIL image. 

418 """ 

419 

420 indirect_reference: IndirectObject | None = None 

421 """ 

422 Reference to the object storing the stream. 

423 """ 

424 

425 is_inline: bool = False 

426 """ 

427 True if this is an inline image (~0~, ~1~, etc.). 

428 """ 

429 

430 is_displayed: bool = False 

431 """ 

432 True if this image is displayed in the page content stream. 

433 """ 

434 

435 def replace(self, new_image: Image, **kwargs: Any) -> None: 

436 """ 

437 Replace the image with a new PIL image. 

438 

439 Args: 

440 new_image (PIL.Image.Image): The new PIL image to replace the existing image. 

441 **kwargs: Additional keyword arguments to pass to `Image.save()`. 

442 

443 Raises: 

444 TypeError: If the image is inline or in a PdfReader. 

445 TypeError: If the image does not belong to a PdfWriter. 

446 TypeError: If `new_image` is not a PIL Image. 

447 

448 Note: 

449 This method replaces the existing image with a new image. 

450 It is not allowed for inline images or images within a PdfReader. 

451 The `kwargs` parameter allows passing additional parameters 

452 to `Image.save()`, such as quality. 

453 

454 """ 

455 if pil_not_imported: 

456 raise ImportError( 

457 "pillow is required to do image extraction. " 

458 "It can be installed via 'pip install pypdf[image]'" 

459 ) 

460 

461 from ._reader import PdfReader # noqa: PLC0415 

462 from .generic import DictionaryObject, PdfObject # noqa: PLC0415 

463 from .generic._image_xobject import _xobj_to_image # noqa: PLC0415 

464 

465 if self.indirect_reference is None: 

466 raise TypeError("Cannot update an inline image.") 

467 if not hasattr(self.indirect_reference.pdf, "_id_translated"): 

468 raise TypeError("Cannot update an image not belonging to a PdfWriter.") 

469 if not isinstance(new_image, Image): 

470 raise TypeError("new_image shall be a PIL Image") 

471 b = BytesIO() 

472 new_image.save(b, "PDF", **kwargs) 

473 reader = PdfReader(b) 

474 page_image = reader.pages[0].images[0] 

475 assert page_image.indirect_reference is not None 

476 self.indirect_reference.pdf._objects[self.indirect_reference.idnum - 1] = ( 

477 page_image.indirect_reference.get_object() 

478 ) 

479 cast( 

480 PdfObject, self.indirect_reference.get_object() 

481 ).indirect_reference = self.indirect_reference 

482 # change the object attributes 

483 extension, byte_stream, img = _xobj_to_image( 

484 cast(DictionaryObject, self.indirect_reference.get_object()), 

485 pillow_parameters=kwargs, 

486 ) 

487 assert extension is not None 

488 self.name = self.name[: self.name.rfind(".")] + extension 

489 self.data = byte_stream 

490 self.image = img 

491 

492 def __str__(self) -> str: 

493 return f"{self.__class__.__name__}(name={self.name}, data: {_human_readable_bytes(len(self.data))})" 

494 

495 def __repr__(self) -> str: 

496 return self.__str__()[:-1] + f", hash: {hash(self.data)})" 

497 

498 

499class VirtualListImages(Sequence[ImageFile]): 

500 """ 

501 Provides access to images referenced within a page. 

502 Only one copy will be returned if the usage is used on the same page multiple times. 

503 See :func:`PageObject.images` for more details. 

504 """ 

505 

506 def __init__( 

507 self, 

508 ids_function: Callable[[], list[str | list[str]]], 

509 get_function: Callable[[str | list[str] | tuple[str]], ImageFile], 

510 ) -> None: 

511 self.ids_function = ids_function 

512 self.get_function = get_function 

513 self.current = -1 

514 

515 def __len__(self) -> int: 

516 return len(self.ids_function()) 

517 

518 def keys(self) -> list[str | list[str]]: 

519 return self.ids_function() 

520 

521 def items(self) -> list[tuple[str | list[str], ImageFile]]: 

522 return [(x, self.get_function(x)) for x in self.ids_function()] 

523 

524 @overload 

525 def __getitem__(self, index: int | str | list[str]) -> ImageFile: 

526 ... 

527 

528 @overload 

529 def __getitem__(self, index: slice) -> Sequence[ImageFile]: 

530 ... 

531 

532 def __getitem__( 

533 self, index: int | slice | str | list[str] | tuple[str] 

534 ) -> ImageFile | Sequence[ImageFile]: 

535 lst = self.ids_function() 

536 if isinstance(index, slice): 

537 indices = range(*index.indices(len(self))) 

538 lst = [lst[x] for x in indices] 

539 cls = type(self) 

540 return cls((lambda: lst), self.get_function) 

541 if isinstance(index, (str, list, tuple)): 

542 return self.get_function(index) 

543 if not isinstance(index, int): 

544 raise TypeError("Invalid sequence indices type") 

545 len_self = len(lst) 

546 if index < 0: 

547 # support negative indexes 

548 index += len_self 

549 if not (0 <= index < len_self): 

550 raise IndexError("Sequence index out of range") 

551 return self.get_function(lst[index]) 

552 

553 def __iter__(self) -> Iterator[ImageFile]: 

554 for image_id in self.ids_function(): 

555 yield self.get_function(image_id) 

556 

557 def __str__(self) -> str: 

558 p = [f"Image_{i}={n}" for i, n in enumerate(self.ids_function())] 

559 return f"[{', '.join(p)}]" 

560 

561 

562class PageObject(DictionaryObject): 

563 """ 

564 PageObject represents a single page within a PDF file. 

565 

566 Typically these objects will be created by accessing the 

567 :attr:`pages<pypdf.PdfReader.pages>` property of the 

568 :class:`PdfReader<pypdf.PdfReader>` class, but it is 

569 also possible to create an empty page with the 

570 :meth:`create_blank_page()<pypdf._page.PageObject.create_blank_page>` static method. 

571 

572 Args: 

573 pdf: PDF file the page belongs to. 

574 indirect_reference: Stores the original indirect reference to 

575 this object in its source PDF 

576 

577 """ 

578 

579 original_page: "PageObject" # very local use in writer when appending 

580 

581 def __init__( 

582 self, 

583 pdf: PdfCommonDocProtocol | None = None, 

584 indirect_reference: IndirectObject | None = None, 

585 ) -> None: 

586 DictionaryObject.__init__(self) 

587 self.pdf = pdf 

588 self._content_stream_images: dict[str, ImageFile | None] | None = None 

589 self.indirect_reference = indirect_reference 

590 if not is_null_or_none(indirect_reference): 

591 assert indirect_reference is not None, "mypy" 

592 self.update(cast(DictionaryObject, indirect_reference.get_object())) 

593 

594 def hash_bin(self) -> int: 

595 """ 

596 Used to detect modified object. 

597 

598 Note: this function is overloaded to return the same results 

599 as a DictionaryObject. 

600 

601 Returns: 

602 Hash considering type and value. 

603 

604 """ 

605 return hash( 

606 (DictionaryObject, tuple(((k, v.hash_bin()) for k, v in self.items()))) 

607 ) 

608 

609 def hash_value_data(self) -> bytes: 

610 data = super().hash_value_data() 

611 data += f"{id(self)}".encode() 

612 return data 

613 

614 @property 

615 def user_unit(self) -> float: 

616 """ 

617 A read-only positive number giving the size of user space units. 

618 

619 It is in multiples of 1/72 inch. Hence a value of 1 means a user 

620 space unit is 1/72 inch, and a value of 3 means that a user 

621 space unit is 3/72 inch. 

622 """ 

623 return cast(float, self.get(PageAttributes.USER_UNIT, 1)) 

624 

625 @staticmethod 

626 def create_blank_page( 

627 pdf: PdfCommonDocProtocol | None = None, 

628 width: float | Decimal | None = None, 

629 height: float | Decimal | None = None, 

630 ) -> "PageObject": 

631 """ 

632 Return a new blank page. 

633 

634 If ``width`` or ``height`` is ``None``, try to get the page size 

635 from the last page of *pdf*. 

636 

637 Args: 

638 pdf: PDF file the page is within. 

639 width: The width of the new page expressed in default user 

640 space units. 

641 height: The height of the new page expressed in default user 

642 space units. 

643 

644 Returns: 

645 The new blank page 

646 

647 Raises: 

648 PageSizeNotDefinedError: if ``pdf`` is ``None`` or contains 

649 no page 

650 

651 """ 

652 page = PageObject(pdf) 

653 

654 # Creates a new page (cf PDF Reference §7.7.3.3) 

655 page.__setitem__(NameObject(PageAttributes.TYPE), NameObject("/Page")) 

656 page.__setitem__(NameObject(PageAttributes.PARENT), NullObject()) 

657 page.__setitem__(NameObject(PageAttributes.RESOURCES), DictionaryObject()) 

658 if width is None or height is None: 

659 if pdf is not None and len(pdf.pages) > 0: 

660 lastpage = pdf.pages[len(pdf.pages) - 1] 

661 width = lastpage.mediabox.width 

662 height = lastpage.mediabox.height 

663 else: 

664 raise PageSizeNotDefinedError 

665 page.__setitem__( 

666 NameObject(PageAttributes.MEDIABOX), RectangleObject((0, 0, width, height)) 

667 ) 

668 

669 return page 

670 

671 def _get_ids_image( 

672 self, 

673 obj: DictionaryObject | None = None, 

674 ancest: list[str] | None = None, 

675 call_stack: list[Any] | None = None, 

676 ) -> list[str | list[str]]: 

677 if call_stack is None: 

678 call_stack = [] 

679 _i = getattr(obj, "indirect_reference", None) 

680 if _i in call_stack: 

681 return [] 

682 call_stack.append(_i) 

683 if self._content_stream_images is None: 

684 self._content_stream_images = self._parse_images_from_content_stream() 

685 if obj is None: 

686 obj = self 

687 if ancest is None: 

688 ancest = [] 

689 lst: list[str | list[str]] = [] 

690 resources = obj.get(PageAttributes.RESOURCES, NullObject()).get_object() 

691 if not isinstance(resources, DictionaryObject): 

692 if not is_null_or_none(resources): 

693 logger_warning( 

694 "Resources are not a dictionary: %(resources)s", 

695 source=__name__, 

696 resources=resources, 

697 ) 

698 resources = DictionaryObject() 

699 if Resources.XOBJECT not in resources: 

700 # Forms without XObject resources have no images inside them 

701 if len(ancest) > 0: 

702 return [] 

703 # for inline images, cache dict entries are not None 

704 return [image_name for image_name, image_value in self._content_stream_images.items() if image_value] 

705 

706 x_object = resources[Resources.XOBJECT].get_object() 

707 if not isinstance(x_object, DictionaryObject): 

708 logger_warning( 

709 "XObject resources are not a dictionary: %(x_object)s", 

710 source=__name__, 

711 x_object=x_object, 

712 ) 

713 return [] 

714 

715 # Iterate through all XObject resources 

716 for o in x_object: 

717 entry = x_object[o] 

718 # Skip non-stream objects (only process StreamObject) 

719 if not isinstance(entry, StreamObject): 

720 continue 

721 if entry.get(ImageAttributes.SUBTYPE, "") == "/Image": 

722 # If it's an image, add it to lst for further processing 

723 lst.append(o if len(ancest) == 0 else [*ancest, o]) 

724 else: 

725 # If it's a form, recursively search for images inside it 

726 # Forms may contain images that are Do-referenced in their content stream 

727 lst.extend(self._get_ids_image(entry, [*ancest, o], call_stack)) 

728 

729 # Removes duplicates and preserves order 

730 deduplicated = lst.copy() 

731 # A set for the membership check below; a list makes it O(n) per image. 

732 # lst can already hold inline image names: a form XObject with its own 

733 # /XObject resources returns them from the recursive call. 

734 # The lists in lst are images inside forms. They are unhashable and 

735 # never equal an inline image name, so they are left out. 

736 seen = {name for name in lst if isinstance(name, str)} 

737 

738 # Add inline images from _content_stream_images 

739 for object_name, object_value in self._content_stream_images.items(): 

740 # inline images have cache populated 

741 if object_name not in seen and object_value: 

742 deduplicated.append(object_name) 

743 seen.add(object_name) 

744 

745 return deduplicated 

746 

747 def _get_image( 

748 self, 

749 image_id: str | list[str] | tuple[str], 

750 obj: DictionaryObject | None = None, 

751 ) -> ImageFile: 

752 if obj is None: 

753 obj = cast(DictionaryObject, self) 

754 if isinstance(image_id, tuple): 

755 image_id = list(image_id) 

756 if isinstance(image_id, list) and len(image_id) == 1: 

757 image_id = image_id[0] 

758 xobjs: DictionaryObject | None = None 

759 resources = obj.get(PageAttributes.RESOURCES, NullObject()).get_object() 

760 if isinstance(resources, DictionaryObject) and Resources.XOBJECT in resources: 

761 xobjs = cast(DictionaryObject, resources[Resources.XOBJECT]) 

762 elif not (image_id[0] == "~" and image_id[-1] == "~"): 

763 raise KeyError( 

764 f"Cannot access image object {image_id} without XObject resources" 

765 ) 

766 if isinstance(image_id, str): 

767 if image_id[0] == "~" and image_id[-1] == "~": 

768 if self._content_stream_images is None: 

769 self._content_stream_images = self._parse_images_from_content_stream() 

770 if image_id not in self._content_stream_images: 

771 raise KeyError(f"Image {image_id} not found") 

772 image_file = self._content_stream_images[image_id] 

773 assert image_file is not None 

774 return image_file 

775 

776 # Do-referenced image name (non-inline string keys like /Im0) 

777 assert xobjs is not None 

778 if image_id not in xobjs: 

779 raise KeyError(f"Image {image_id} not found") 

780 xobj = cast(DictionaryObject, xobjs[image_id]) 

781 if xobj.get(ImageAttributes.SUBTYPE, "") != "/Image": 

782 raise KeyError(f"XObject {image_id} is not an image") 

783 

784 # Check if displayed (in content stream) 

785 is_displayed = self._content_stream_images is not None and image_id in self._content_stream_images 

786 

787 from .generic._image_xobject import _xobj_to_image # noqa: PLC0415 

788 extension, byte_stream, img = _xobj_to_image(xobj) 

789 return ImageFile( 

790 name=f"{image_id[1:]}{extension}", 

791 data=byte_stream, 

792 image=img, 

793 indirect_reference=xobj.indirect_reference, 

794 is_inline=False, 

795 is_displayed=is_displayed, 

796 ) 

797 # in a subobject 

798 assert xobjs is not None 

799 ids = image_id[1:] 

800 return self._get_image(ids, cast(DictionaryObject, xobjs[image_id[0]])) 

801 

802 @property 

803 def images(self) -> VirtualListImages: 

804 """ 

805 Read-only property emulating a list of images on a page. 

806 

807 Get a list of all images on the page. The key can be: 

808 - A string (for the top object) 

809 - A tuple (for images within XObject forms) 

810 - An integer 

811 

812 Examples: 

813 * `reader.pages[0].images[0]` # return first image 

814 * `reader.pages[0].images['/I0']` # return image '/I0' 

815 * `reader.pages[0].images['/TP1','/Image1']` # return image '/Image1' within '/TP1' XObject form 

816 * `for img in reader.pages[0].images:` # loops through all objects 

817 

818 Example usage: 

819 

820 >>> from pypdf import PdfWriter 

821 >>> writer = PdfWriter() 

822 >>> page = writer.add_blank_page(800, 600) 

823 >>> images = page.images 

824 

825 """ 

826 return VirtualListImages(self._get_ids_image, self._get_image) 

827 

828 @property 

829 def inline_images(self) -> NoReturn: 

830 """ 

831 Return only inline images from the page. 

832 

833 .. deprecated:: 

834 Use :attr:`images` and filter by :attr:`ImageFile.is_inline` instead. 

835 This property has been removed in pypdf 7.0. 

836 

837 Examples: 

838 >>> from pypdf import PdfWriter 

839 >>> writer = PdfWriter() 

840 >>> page = writer.add_blank_page(800,600) 

841 >>> for image_name, image_file in page.images.items(): 

842 ... if image_file.is_inline: 

843 ... print(f"{image_name} is inline") 

844 """ 

845 deprecation_with_replacement( 

846 "PageObject.inline_images", 

847 "PageObject.images", 

848 "7.0.0", 

849 ) 

850 

851 @inline_images.setter 

852 def inline_images(self, value: dict[str, ImageFile] | None) -> NoReturn: 

853 deprecation_no_replacement( 

854 "PageObject.inline_images", 

855 "7.0.0", 

856 ) 

857 

858 def _translate_value_inline_image(self, k: str, v: PdfObject) -> PdfObject: 

859 """Translate values used in inline image""" 

860 try: 

861 v = NameObject(_INLINE_IMAGE_VALUE_MAPPING[cast(str, v)]) 

862 except (TypeError, KeyError) as exception: 

863 if isinstance(v, NameObject): 

864 # It is a custom name, thus we have to look in resources. 

865 # The only applicable case is for ColorSpace. 

866 resources = self.get("/Resources", NullObject()).get_object() 

867 if not isinstance(resources, DictionaryObject): 

868 if not is_null_or_none(resources): 

869 logger_warning( 

870 "Resources are not a dictionary: %(resources)s", 

871 source=__name__, 

872 resources=resources, 

873 ) 

874 resources = DictionaryObject() 

875 if "/ColorSpace" in resources and v in ( 

876 color_space := cast(DictionaryObject, resources["/ColorSpace"]) 

877 ): 

878 return color_space[v] 

879 raise PdfReadError(f"Cannot find resource entry {v} for {k}") from exception 

880 return v 

881 

882 def _parse_images_from_content_stream(self) -> dict[str, ImageFile | None]: 

883 """Load images from content stream. Includes both inline images and Do-referenced images. 

884 

885 This method scans the page content stream and extracts: 

886 

887 1. **Inline images** (~0~, ~1~...): Embedded directly in content stream via BI/EI operators 

888 - is_inline=True, is_displayed=True, indirect_reference=None 

889 

890 2. **Do-referenced objects** (/Im0, /Im1..., /Form1...): Referenced via "Do" operator 

891 - is_inline=False, is_displayed=True, indirect_reference=<image object> 

892 

893 3. **Pure XObject images** (/I0, /Image1...): Defined in Resources only (not in content stream) 

894 - is_inline=False, is_displayed=False, indirect_reference=<image object> 

895 

896 Returns: 

897 Dictionary mapping names to ImageFile instances (inline) or None (Do-referenced). 

898 """ 

899 content = self.get_contents() 

900 if is_null_or_none(content): 

901 return {} 

902 imgs_data = [] 

903 do_image_names: list[bytes] = [] 

904 assert content is not None, "mypy" 

905 for param, ope in content.operations: 

906 if ope == b"INLINE IMAGE": 

907 imgs_data.append( 

908 {"settings": param["settings"], "__streamdata__": param["data"]} 

909 ) 

910 elif ope == b"Do" and param: 

911 do_image_names.append(param[0]) # First operand is the XObject name 

912 elif ope in (b"BI", b"EI", b"ID"): # pragma: no cover 

913 raise PdfReadError( 

914 f"{ope!r} operator met whereas not expected, " 

915 "please share use case with pypdf dev team" 

916 ) 

917 

918 files: dict[str, ImageFile | None] = {} 

919 # Process Do-referenced objects first (images + forms, no subtype check) 

920 files = dict.fromkeys(list(map(str, do_image_names)), None) 

921 

922 # Then process inline images 

923 for num, ii in enumerate(imgs_data): 

924 init = { 

925 "__streamdata__": ii["__streamdata__"], 

926 "/Length": len(ii["__streamdata__"]), 

927 } 

928 for k, v in ii["settings"].items(): 

929 if k in {"/Length", "/L"}: # no length is expected 

930 continue 

931 if isinstance(v, list): 

932 v = ArrayObject( 

933 [self._translate_value_inline_image(k, x) for x in v] 

934 ) 

935 else: 

936 v = self._translate_value_inline_image(k, v) 

937 if k in _INLINE_IMAGE_KEY_MAPPING: 

938 k = NameObject(_INLINE_IMAGE_KEY_MAPPING[k]) 

939 else: 

940 logger_warning( 

941 "Unknown inline image key %(key)s, keeping it as-is.", 

942 source=__name__, 

943 key=k, 

944 ) 

945 k = NameObject(k) 

946 if k not in init: 

947 init[k] = v 

948 ii["object"] = EncodedStreamObject.initialize_from_dictionary(init) 

949 from .generic._image_xobject import _xobj_to_image # noqa: PLC0415 

950 extension, byte_stream, img = _xobj_to_image(ii["object"]) 

951 files[f"~{num}~"] = ImageFile( 

952 name=f"~{num}~{extension}", 

953 data=byte_stream, 

954 image=img, 

955 indirect_reference=None, 

956 is_inline=True, 

957 is_displayed=True, 

958 ) 

959 

960 return files 

961 

962 @property 

963 def rotation(self) -> int: 

964 """ 

965 The visual rotation of the page. 

966 

967 This number has to be a multiple of 90 degrees: 0, 90, 180, or 270 are 

968 valid values. This property does not affect ``/Contents``. 

969 """ 

970 rotate_obj = self.get(PageAttributes.ROTATE, 0) 

971 return rotate_obj if isinstance(rotate_obj, int) else rotate_obj.get_object() 

972 

973 @rotation.setter 

974 def rotation(self, r: float) -> None: 

975 self[NameObject(PageAttributes.ROTATE)] = NumberObject((((int(r) + 45) // 90) * 90) % 360) 

976 

977 def transfer_rotation_to_content(self) -> None: 

978 """ 

979 Apply the rotation of the page to the content and the media/crop/... 

980 boxes. 

981 

982 It is recommended to apply this function before page merging. 

983 """ 

984 r = -self.rotation # rotation to apply is in the otherway 

985 self.rotation = 0 

986 mb = RectangleObject(self.mediabox) 

987 trsf = ( 

988 Transformation() 

989 .translate( 

990 -float(mb.left + mb.width / 2), -float(mb.bottom + mb.height / 2) 

991 ) 

992 .rotate(r) 

993 ) 

994 pt1 = trsf.apply_on(mb.lower_left) 

995 pt2 = trsf.apply_on(mb.upper_right) 

996 trsf = trsf.translate(-min(pt1[0], pt2[0]), -min(pt1[1], pt2[1])) 

997 self.add_transformation(trsf, False) 

998 for b in ["/MediaBox", "/CropBox", "/BleedBox", "/TrimBox", "/ArtBox"]: 

999 if b in self: 

1000 rr = RectangleObject(self[b]) # type: ignore[arg-type] 

1001 pt1 = trsf.apply_on(rr.lower_left) 

1002 pt2 = trsf.apply_on(rr.upper_right) 

1003 self[NameObject(b)] = RectangleObject( 

1004 ( 

1005 min(pt1[0], pt2[0]), 

1006 min(pt1[1], pt2[1]), 

1007 max(pt1[0], pt2[0]), 

1008 max(pt1[1], pt2[1]), 

1009 ) 

1010 ) 

1011 

1012 def rotate(self, angle: int) -> "PageObject": 

1013 """ 

1014 Rotate a page clockwise by increments of 90 degrees. 

1015 

1016 Args: 

1017 angle: Angle to rotate the page. Must be an increment of 90 deg. 

1018 

1019 Returns: 

1020 The rotated PageObject 

1021 

1022 """ 

1023 if angle % 90 != 0: 

1024 raise ValueError("Rotation angle must be a multiple of 90") 

1025 self[NameObject(PageAttributes.ROTATE)] = NumberObject(self.rotation + angle) 

1026 return self 

1027 

1028 def _merge_resources( 

1029 self, 

1030 original_resources: DictionaryObject, 

1031 page2_resources: DictionaryObject, 

1032 resource_type: Any, 

1033 copy_original: bool = True, 

1034 ) -> tuple[dict[str, Any], dict[str, Any]]: 

1035 try: 

1036 assert isinstance(self.indirect_reference, IndirectObject) 

1037 pdf = self.indirect_reference.pdf 

1038 is_pdf_writer = hasattr( 

1039 pdf, "_add_object" 

1040 ) # expect isinstance(pdf, PdfWriter) 

1041 except (AssertionError, AttributeError): 

1042 pdf = None 

1043 is_pdf_writer = False 

1044 

1045 def compute_unique_key(base_key: str) -> tuple[str, bool]: 

1046 """ 

1047 Find a key that either doesn't already exist or has the same value 

1048 (indicated by the bool) 

1049 

1050 Args: 

1051 base_key: An index is added to this to get the computed key 

1052 

1053 Returns: 

1054 A tuple (computed key, bool) where the boolean indicates 

1055 if there is a resource of the given computed_key with the same 

1056 value. 

1057 

1058 """ 

1059 value = page2_type_resources.raw_get(base_key) 

1060 # TODO: a possible improvement for writer, the indirect_reference 

1061 # cannot be found because translated 

1062 

1063 # try the current key first (e.g. "foo"), but otherwise iterate 

1064 # through "foo-0", "foo-1", etc. new_res can contain only finitely 

1065 # many keys, thus this'll eventually end, even if it's been crafted 

1066 # to be maximally annoying. 

1067 computed_key = base_key 

1068 idx = 0 

1069 while computed_key in merged_type_resources: 

1070 if merged_type_resources.raw_get(computed_key) == value: 

1071 # there's already a resource of this name, with the exact 

1072 # same value 

1073 return computed_key, True 

1074 computed_key = f"{base_key}-{idx}" 

1075 idx += 1 

1076 return computed_key, False 

1077 

1078 if copy_original: 

1079 merged_type_resources = DictionaryObject() 

1080 merged_type_resources.update(original_resources.get(resource_type, DictionaryObject()).get_object()) 

1081 else: 

1082 merged_type_resources = cast(DictionaryObject, original_resources[resource_type]) 

1083 page2_type_resources = cast( 

1084 DictionaryObject, page2_resources.get(resource_type, DictionaryObject()).get_object() 

1085 ) 

1086 rename_mapping = {} 

1087 for key in page2_type_resources: 

1088 unique_key, same_value = compute_unique_key(key) 

1089 new_name = NameObject(unique_key) 

1090 if key != unique_key: 

1091 # we have to use a different name for this 

1092 rename_mapping[key] = new_name 

1093 

1094 if not same_value: 

1095 if is_pdf_writer: 

1096 merged_type_resources[new_name] = page2_type_resources.raw_get(key).clone(pdf) 

1097 with contextlib.suppress(AttributeError): 

1098 merged_type_resources[new_name] = merged_type_resources[new_name].indirect_reference 

1099 else: 

1100 merged_type_resources[new_name] = page2_type_resources.raw_get(key) 

1101 lst = sorted(merged_type_resources.items()) 

1102 merged_type_resources.clear() 

1103 for el in lst: 

1104 merged_type_resources[el[0]] = el[1] 

1105 return merged_type_resources, rename_mapping 

1106 

1107 @staticmethod 

1108 def _content_stream_rename( 

1109 stream: ContentStream, 

1110 rename: dict[Any, Any], 

1111 pdf: PdfCommonDocProtocol | None, 

1112 ) -> ContentStream: 

1113 if not rename: 

1114 return stream 

1115 stream = ContentStream(stream, pdf) 

1116 for operands, _operator in stream.operations: 

1117 if isinstance(operands, list): 

1118 for i, op in enumerate(operands): 

1119 if isinstance(op, NameObject): 

1120 operands[i] = rename.get(op, op) 

1121 elif isinstance(operands, dict): 

1122 for i, op in operands.items(): 

1123 if isinstance(op, NameObject): 

1124 operands[i] = rename.get(op, op) 

1125 else: 

1126 # It's not expected to ever hit this branch. 

1127 # The new content stream parses the data of the old one instead 

1128 # of copying its operations, so the operands are a list or the 

1129 # dictionary of an inline image. 

1130 raise AssertionError(f"Type of operands is {type(operands)}") # noqa: TRY004 

1131 return stream 

1132 

1133 @staticmethod 

1134 def _add_transformation_matrix( 

1135 contents: Any, 

1136 pdf: PdfCommonDocProtocol | None, 

1137 ctm: CompressedTransformationMatrix, 

1138 ) -> ContentStream: 

1139 """Add transformation matrix at the beginning of the given contents stream.""" 

1140 content_stream = ContentStream(contents, pdf) 

1141 content_stream.operations.insert( 

1142 0, 

1143 ( 

1144 [FloatObject(x) for x in ctm], 

1145 b"cm", 

1146 ), 

1147 ) 

1148 return content_stream 

1149 

1150 def _get_contents_as_bytes(self) -> bytes | None: 

1151 """ 

1152 Return the page contents as bytes. 

1153 

1154 Returns: 

1155 The ``/Contents`` object as bytes, or ``None`` if it doesn't exist. 

1156 

1157 """ 

1158 if PageAttributes.CONTENTS in self: 

1159 obj = self[PageAttributes.CONTENTS].get_object() 

1160 if isinstance(obj, list): 

1161 return b"".join(x.get_object().get_data() for x in obj) 

1162 return cast(EncodedStreamObject, obj).get_data() 

1163 return None 

1164 

1165 def get_contents(self) -> ContentStream | None: 

1166 """ 

1167 Access the page contents. 

1168 

1169 Returns: 

1170 The ``/Contents`` object, or ``None`` if it does not exist. 

1171 ``/Contents`` is optional, as described in §7.7.3.3 of the PDF Reference. 

1172 

1173 """ 

1174 if PageAttributes.CONTENTS in self: 

1175 try: 

1176 pdf = cast(IndirectObject, self.indirect_reference).pdf 

1177 except AttributeError: 

1178 pdf = None 

1179 obj = self[PageAttributes.CONTENTS] 

1180 if is_null_or_none(obj): 

1181 return None 

1182 resolved_object = obj.get_object() 

1183 if not isinstance(resolved_object, (ArrayObject, StreamObject)): 

1184 logger_warning( 

1185 "Page contents are not a stream or an array: %(contents)s", 

1186 source=__name__, 

1187 contents=resolved_object, 

1188 ) 

1189 return None 

1190 return ContentStream(resolved_object, pdf) 

1191 return None 

1192 

1193 def replace_contents( 

1194 self, content: ContentStream | EncodedStreamObject | ArrayObject | None 

1195 ) -> None: 

1196 """ 

1197 Replace the page contents with the new content and nullify old objects 

1198 Args: 

1199 content: new content; if None delete the content field. 

1200 """ 

1201 if not hasattr(self, "indirect_reference") or self.indirect_reference is None: 

1202 # the page is not attached : the content is directly attached. 

1203 self[NameObject(PageAttributes.CONTENTS)] = content 

1204 return 

1205 

1206 from pypdf._writer import PdfWriter # noqa: PLC0415 

1207 if not isinstance(self.indirect_reference.pdf, PdfWriter): 

1208 deprecation( 

1209 "Calling `PageObject.replace_contents()` for pages not assigned to a writer is deprecated " 

1210 "and has been removed in pypdf 7.0.0. Attach the page to the writer first or use " 

1211 "`PdfWriter(clone_from=...)` directly. The existing approach has proved being unreliable." 

1212 ) 

1213 

1214 writer = self.indirect_reference.pdf 

1215 # Resolve /Contents because it may be an indirect reference to an 

1216 # ArrayObject. Without resolving it, an indirect contents array is not 

1217 # recognized and its stream objects are left in the writer's object list. 

1218 old_contents = self.get(PageAttributes.CONTENTS, None) 

1219 if old_contents is not None: 

1220 old_contents = old_contents.get_object() 

1221 if isinstance(old_contents, ArrayObject): 

1222 for reference in old_contents: 

1223 if not isinstance(reference, IndirectObject): 

1224 # Direct objects are not part of the writer's object list. 

1225 continue 

1226 writer._replace_object(indirect_reference=reference, obj=NullObject()) 

1227 

1228 if isinstance(content, ArrayObject): 

1229 content = ArrayObject(writer._add_object(obj) for obj in content) 

1230 

1231 if is_null_or_none(content): 

1232 if PageAttributes.CONTENTS not in self: 

1233 return 

1234 contents_reference = self[PageAttributes.CONTENTS].indirect_reference 

1235 assert contents_reference is not None, "mypy" 

1236 writer._replace_object(indirect_reference=contents_reference, obj=NullObject()) 

1237 del self[PageAttributes.CONTENTS] 

1238 elif not hasattr(self.get(PageAttributes.CONTENTS, None), "indirect_reference"): 

1239 assert content is not None, "mypy" 

1240 self[NameObject(PageAttributes.CONTENTS)] = writer._add_object(content) 

1241 else: 

1242 assert content is not None, "mypy" 

1243 content.indirect_reference = self[ 

1244 PageAttributes.CONTENTS 

1245 ].indirect_reference # TODO: in the future may require generation management 

1246 assert content.indirect_reference is not None, "mypy" 

1247 writer._replace_object(indirect_reference=content.indirect_reference, obj=content) 

1248 # forces recalculation of images 

1249 self._content_stream_images = None 

1250 

1251 def merge_page( 

1252 self, page2: "PageObject", expand: bool = False, over: bool = True 

1253 ) -> None: 

1254 """ 

1255 Merge the content streams of two pages into one. 

1256 

1257 Resource references (e.g. fonts) are maintained from both pages. 

1258 The mediabox, cropbox, etc of this page are not altered. 

1259 The parameter page's content stream will 

1260 be added to the end of this page's content stream, 

1261 meaning that it will be drawn after, or "on top" of this page. 

1262 

1263 Args: 

1264 page2: The page to be merged into this one. Should be 

1265 an instance of :class:`PageObject<PageObject>`. 

1266 over: set the page2 content over page1 if True (default) else under 

1267 expand: If True, the current page dimensions will be 

1268 expanded to accommodate the dimensions of the page to be merged. 

1269 

1270 """ 

1271 self._merge_page(page2, over=over, expand=expand) 

1272 

1273 def _merge_page( 

1274 self, 

1275 page2: "PageObject", 

1276 page2_transformation: Callable[[Any], ContentStream] | None = None, 

1277 ctm: CompressedTransformationMatrix | None = None, 

1278 over: bool = True, 

1279 expand: bool = False, 

1280 ) -> None: 

1281 # First we work on merging the resource dictionaries. This allows us 

1282 # to find out what symbols in the content streams we might need to 

1283 # rename. 

1284 try: 

1285 assert isinstance(self.indirect_reference, IndirectObject) 

1286 if hasattr(self.indirect_reference.pdf, "_add_object"): # to detect PdfWriter 

1287 return self._merge_page_writer( 

1288 page2, page2_transformation, ctm, over, expand 

1289 ) 

1290 except (AssertionError, AttributeError): 

1291 pass 

1292 

1293 new_resources = DictionaryObject() 

1294 rename: dict[str, Any] = {} 

1295 original_resources = cast(DictionaryObject, self.get(PageAttributes.RESOURCES, DictionaryObject()).get_object()) 

1296 page2_resources = cast(DictionaryObject, page2.get(PageAttributes.RESOURCES, DictionaryObject()).get_object()) 

1297 new_annotations = ArrayObject() 

1298 

1299 for page in (self, page2): 

1300 if PageAttributes.ANNOTS in page: 

1301 annotations = page[PageAttributes.ANNOTS] 

1302 if isinstance(annotations, ArrayObject): 

1303 new_annotations.extend(annotations) 

1304 self[NameObject(PageAttributes.ANNOTS)] = new_annotations 

1305 

1306 for resource_type in ( 

1307 Resources.EXT_G_STATE, 

1308 Resources.COLOR_SPACE, 

1309 Resources.PATTERN, 

1310 Resources.SHADING, 

1311 Resources.XOBJECT, 

1312 Resources.FONT, 

1313 Resources.PROPERTIES, 

1314 ): 

1315 merged_type_resources, rename_mapping = self._merge_resources( 

1316 original_resources, page2_resources, resource_type 

1317 ) 

1318 if merged_type_resources: 

1319 new_resources[NameObject(resource_type)] = merged_type_resources 

1320 rename.update(rename_mapping) 

1321 

1322 # Combine /ProcSet sets, making sure there is a consistent order 

1323 new_resources[NameObject(Resources.PROC_SET)] = ArrayObject( 

1324 sorted( 

1325 set( 

1326 original_resources.get(Resources.PROC_SET, ArrayObject()).get_object() 

1327 ).union( 

1328 set(page2_resources.get(Resources.PROC_SET, ArrayObject()).get_object()) 

1329 ) 

1330 ) 

1331 ) 

1332 

1333 new_content_array = ArrayObject() 

1334 original_content = self.get_contents() 

1335 if original_content is not None: 

1336 original_content.isolate_graphics_state() 

1337 new_content_array.append(original_content) 

1338 

1339 page2_content = page2.get_contents() 

1340 if page2_content is not None: 

1341 configuration = get_configuration() 

1342 rect = getattr(page2, configuration.page_merge_box) 

1343 page2_content.operations.insert( 

1344 0, 

1345 ( 

1346 map( 

1347 FloatObject, 

1348 [ 

1349 rect.left, 

1350 rect.bottom, 

1351 rect.width, 

1352 rect.height, 

1353 ], 

1354 ), 

1355 b"re", 

1356 ), 

1357 ) 

1358 page2_content.operations.insert(1, ([], b"W")) 

1359 page2_content.operations.insert(2, ([], b"n")) 

1360 if page2_transformation is not None: 

1361 page2_content = page2_transformation(page2_content) 

1362 page2_content = PageObject._content_stream_rename( 

1363 page2_content, rename, self.pdf 

1364 ) 

1365 page2_content.isolate_graphics_state() 

1366 if over: 

1367 new_content_array.append(page2_content) 

1368 else: 

1369 new_content_array.insert(0, page2_content) 

1370 

1371 # if expanding the page to fit a new page, calculate the new media box size 

1372 if expand: 

1373 self._expand_mediabox(page2, ctm) 

1374 

1375 self.replace_contents(ContentStream(new_content_array, self.pdf)) 

1376 self[NameObject(PageAttributes.RESOURCES)] = new_resources 

1377 

1378 return None 

1379 

1380 def _merge_page_writer( 

1381 self, 

1382 page2: "PageObject", 

1383 page2_transformation: Callable[[Any], ContentStream] | None = None, 

1384 ctm: CompressedTransformationMatrix | None = None, 

1385 over: bool = True, 

1386 expand: bool = False, 

1387 ) -> None: 

1388 # First we work on merging the resource dictionaries. This allows us 

1389 # to find which symbols in the content streams we might need to 

1390 # rename. 

1391 assert isinstance(self.indirect_reference, IndirectObject) 

1392 pdf = self.indirect_reference.pdf 

1393 

1394 original_resources = _get_page_resources(self, inherit=False) 

1395 if self.get(PageAttributes.RESOURCES, NullObject()).get_object() is not original_resources: 

1396 # missing, null or malformed: the merged resources are stored in a new dictionary 

1397 self[NameObject(PageAttributes.RESOURCES)] = original_resources 

1398 page2_resources = _get_page_resources(page2, inherit=False) 

1399 

1400 rename = {} 

1401 for resource_type in ( 

1402 Resources.EXT_G_STATE, 

1403 Resources.COLOR_SPACE, 

1404 Resources.PATTERN, 

1405 Resources.SHADING, 

1406 Resources.XOBJECT, 

1407 Resources.FONT, 

1408 Resources.PROPERTIES, 

1409 ): 

1410 if resource_type in page2_resources: 

1411 if resource_type not in original_resources: 

1412 original_resources[NameObject(resource_type)] = DictionaryObject() 

1413 _, new_rename = self._merge_resources( 

1414 original_resources, page2_resources, resource_type, False 

1415 ) 

1416 rename.update(new_rename) 

1417 # Combine /ProcSet sets 

1418 if Resources.PROC_SET in page2_resources: 

1419 if Resources.PROC_SET not in original_resources: 

1420 original_resources[NameObject(Resources.PROC_SET)] = ArrayObject() 

1421 procedure_sets = cast(ArrayObject, original_resources[Resources.PROC_SET]) 

1422 for procedure_set in cast(ArrayObject, page2_resources[Resources.PROC_SET]): 

1423 if procedure_set not in procedure_sets: 

1424 procedure_sets.append(procedure_set) 

1425 procedure_sets.sort() 

1426 

1427 if not is_null_or_none(page2.get(PageAttributes.ANNOTS, None)): 

1428 annotations = self.get(PageAttributes.ANNOTS, NullObject()).get_object() 

1429 if not isinstance(annotations, ArrayObject): 

1430 if not is_null_or_none(annotations): 

1431 logger_warning( 

1432 "Annotations are not an array: %(annotations)s", 

1433 source=__name__, 

1434 annotations=annotations, 

1435 ) 

1436 annotations = ArrayObject() 

1437 self[NameObject(PageAttributes.ANNOTS)] = annotations 

1438 if ctm is None: 

1439 transformation = Transformation() 

1440 else: 

1441 transformation = Transformation(ctm) 

1442 page2_annotations = cast(ArrayObject, page2[PageAttributes.ANNOTS]) 

1443 configuration = get_configuration() 

1444 if len(page2_annotations) > configuration.annotations_maximum_per_page: 

1445 raise LimitReachedError( 

1446 f"Maximum annotations per page exceeded: " 

1447 f"{len(page2_annotations)} > {configuration.annotations_maximum_per_page}." 

1448 ) 

1449 # Ensure we are working on a copy of the list. Otherwise, if both pages 

1450 # are the same object, we might run into an infinite loop. 

1451 for annotation in deepcopy(page2_annotations): 

1452 annotation = annotation.get_object() 

1453 annotation_copy = annotation.clone( 

1454 pdf, 

1455 ignore_fields=("/P", "/StructParent", "/Parent"), 

1456 force_duplicate=True, 

1457 ) 

1458 rectangle = cast(ArrayObject, annotation["/Rect"]) 

1459 # Rotation and shear can move the other corners beyond this diagonal. 

1460 points = [ 

1461 transformation.apply_on((rectangle[0], rectangle[1]), True), # Original lower-left corner. 

1462 transformation.apply_on((rectangle[2], rectangle[1]), True), # Original lower-right corner. 

1463 transformation.apply_on((rectangle[0], rectangle[3]), True), # Original upper-left corner. 

1464 transformation.apply_on((rectangle[2], rectangle[3]), True), # Original upper-right corner. 

1465 ] 

1466 x_coordinates = [point[0] for point in points] 

1467 y_coordinates = [point[1] for point in points] 

1468 annotation_copy[NameObject("/Rect")] = ArrayObject( 

1469 ( 

1470 min(x_coordinates), 

1471 min(y_coordinates), 

1472 max(x_coordinates), 

1473 max(y_coordinates), 

1474 ) 

1475 ) 

1476 if "/QuadPoints" in annotation: 

1477 quad_points = cast(ArrayObject, annotation["/QuadPoints"]) 

1478 annotation_copy[NameObject("/QuadPoints")] = ArrayObject( 

1479 value 

1480 for i in range(0, len(quad_points), 2) 

1481 for value in transformation.apply_on((quad_points[i], quad_points[i + 1]), True) 

1482 ) 

1483 # The /Rect update above only repositions and resizes the 

1484 # annotation's bounding box; it does not touch the 

1485 # appearance stream's own coordinate system. See 

1486 # transform_annotation_appearance for why that matters. 

1487 from pypdf.generic._appearance_stream import ( # noqa: PLC0415 

1488 transform_annotation_appearance, 

1489 ) 

1490 transform_annotation_appearance(annotation_copy, transformation) 

1491 with contextlib.suppress(KeyError): 

1492 annotation_copy["/Popup"][NameObject("/Parent")] = annotation_copy.indirect_reference 

1493 annotation_copy[NameObject("/P")] = self.indirect_reference 

1494 annotations.append(annotation_copy.indirect_reference) 

1495 

1496 new_content_array = ArrayObject() 

1497 original_content = self.get_contents() 

1498 if original_content is not None: 

1499 original_content.isolate_graphics_state() 

1500 new_content_array.append(original_content) 

1501 

1502 page2_content = page2.get_contents() 

1503 if page2_content is not None: 

1504 configuration = get_configuration() 

1505 rect = getattr(page2, configuration.page_merge_box) 

1506 page2_content.operations.insert( 

1507 0, 

1508 ( 

1509 map( 

1510 FloatObject, 

1511 [ 

1512 rect.left, 

1513 rect.bottom, 

1514 rect.width, 

1515 rect.height, 

1516 ], 

1517 ), 

1518 b"re", 

1519 ), 

1520 ) 

1521 page2_content.operations.insert(1, ([], b"W")) 

1522 page2_content.operations.insert(2, ([], b"n")) 

1523 if page2_transformation is not None: 

1524 page2_content = page2_transformation(page2_content) 

1525 page2_content = PageObject._content_stream_rename( 

1526 page2_content, rename, self.pdf 

1527 ) 

1528 page2_content.isolate_graphics_state() 

1529 if over: 

1530 new_content_array.append(page2_content) 

1531 else: 

1532 new_content_array.insert(0, page2_content) 

1533 

1534 # if expanding the page to fit a new page, calculate the new media box size 

1535 if expand: 

1536 self._expand_mediabox(page2, ctm) 

1537 

1538 self.replace_contents(new_content_array) 

1539 

1540 def _expand_mediabox( 

1541 self, page2: "PageObject", ctm: CompressedTransformationMatrix | None 

1542 ) -> None: 

1543 corners1 = ( 

1544 self.mediabox.left.as_numeric(), 

1545 self.mediabox.bottom.as_numeric(), 

1546 self.mediabox.right.as_numeric(), 

1547 self.mediabox.top.as_numeric(), 

1548 ) 

1549 corners2 = ( 

1550 page2.mediabox.left.as_numeric(), 

1551 page2.mediabox.bottom.as_numeric(), 

1552 page2.mediabox.left.as_numeric(), 

1553 page2.mediabox.top.as_numeric(), 

1554 page2.mediabox.right.as_numeric(), 

1555 page2.mediabox.top.as_numeric(), 

1556 page2.mediabox.right.as_numeric(), 

1557 page2.mediabox.bottom.as_numeric(), 

1558 ) 

1559 if ctm is not None: 

1560 ctm = tuple(float(x) for x in ctm) # type: ignore[assignment] 

1561 new_x = tuple( 

1562 ctm[0] * corners2[i] + ctm[2] * corners2[i + 1] + ctm[4] 

1563 for i in range(0, 8, 2) 

1564 ) 

1565 new_y = tuple( 

1566 ctm[1] * corners2[i] + ctm[3] * corners2[i + 1] + ctm[5] 

1567 for i in range(0, 8, 2) 

1568 ) 

1569 else: 

1570 new_x = corners2[0:8:2] 

1571 new_y = corners2[1:8:2] 

1572 lowerleft = (min(new_x), min(new_y)) 

1573 upperright = (max(new_x), max(new_y)) 

1574 lowerleft = (min(corners1[0], lowerleft[0]), min(corners1[1], lowerleft[1])) 

1575 upperright = ( 

1576 max(corners1[2], upperright[0]), 

1577 max(corners1[3], upperright[1]), 

1578 ) 

1579 

1580 self.mediabox.lower_left = lowerleft 

1581 self.mediabox.upper_right = upperright 

1582 

1583 def merge_transformed_page( 

1584 self, 

1585 page2: "PageObject", 

1586 ctm: CompressedTransformationMatrix | Transformation, 

1587 over: bool = True, 

1588 expand: bool = False, 

1589 ) -> None: 

1590 """ 

1591 Similar to :meth:`~pypdf._page.PageObject.merge_page`, but a transformation 

1592 matrix is applied to the merged stream. 

1593 

1594 Args: 

1595 page2: The page to be merged into this one. 

1596 ctm: a 6-element tuple containing the operands of the 

1597 transformation matrix 

1598 over: set the page2 content over page1 if True (default) else under 

1599 expand: Whether the page should be expanded to fit the dimensions 

1600 of the page to be merged. 

1601 

1602 """ 

1603 if isinstance(ctm, Transformation): 

1604 ctm = ctm.ctm 

1605 self._merge_page( 

1606 page2, 

1607 lambda page2_content: PageObject._add_transformation_matrix( 

1608 page2_content, page2.pdf, ctm 

1609 ), 

1610 ctm, 

1611 over, 

1612 expand, 

1613 ) 

1614 

1615 def merge_scaled_page( 

1616 self, page2: "PageObject", scale: float, over: bool = True, expand: bool = False 

1617 ) -> None: 

1618 """ 

1619 Similar to :meth:`~pypdf._page.PageObject.merge_page`, but the stream to be merged 

1620 is scaled by applying a transformation matrix. 

1621 

1622 Args: 

1623 page2: The page to be merged into this one. 

1624 scale: The scaling factor 

1625 over: set the page2 content over page1 if True (default) else under 

1626 expand: Whether the page should be expanded to fit the 

1627 dimensions of the page to be merged. 

1628 

1629 """ 

1630 op = Transformation().scale(scale, scale) 

1631 self.merge_transformed_page(page2, op, over, expand) 

1632 

1633 def merge_rotated_page( 

1634 self, 

1635 page2: "PageObject", 

1636 rotation: float, 

1637 over: bool = True, 

1638 expand: bool = False, 

1639 ) -> None: 

1640 """ 

1641 Similar to :meth:`~pypdf._page.PageObject.merge_page`, but the stream to be merged 

1642 is rotated by applying a transformation matrix. 

1643 

1644 Args: 

1645 page2: The page to be merged into this one. 

1646 rotation: The angle of the rotation, in degrees 

1647 over: set the page2 content over page1 if True (default) else under 

1648 expand: Whether the page should be expanded to fit the 

1649 dimensions of the page to be merged. 

1650 

1651 """ 

1652 op = Transformation().rotate(rotation) 

1653 self.merge_transformed_page(page2, op, over, expand) 

1654 

1655 def merge_translated_page( 

1656 self, 

1657 page2: "PageObject", 

1658 tx: float, 

1659 ty: float, 

1660 over: bool = True, 

1661 expand: bool = False, 

1662 ) -> None: 

1663 """ 

1664 Similar to :meth:`~pypdf._page.PageObject.merge_page`, but the stream to be 

1665 merged is translated by applying a transformation matrix. 

1666 

1667 Args: 

1668 page2: the page to be merged into this one. 

1669 tx: The translation on X axis 

1670 ty: The translation on Y axis 

1671 over: set the page2 content over page1 if True (default) else under 

1672 expand: Whether the page should be expanded to fit the 

1673 dimensions of the page to be merged. 

1674 

1675 """ 

1676 op = Transformation().translate(tx, ty) 

1677 self.merge_transformed_page(page2, op, over, expand) 

1678 

1679 def add_transformation( 

1680 self, 

1681 ctm: Transformation | CompressedTransformationMatrix, 

1682 expand: bool = False, 

1683 ) -> None: 

1684 """ 

1685 Apply a transformation matrix to the page. 

1686 

1687 Args: 

1688 ctm: A 6-element tuple containing the operands of the 

1689 transformation matrix. Alternatively, a 

1690 :py:class:`Transformation<pypdf.Transformation>` 

1691 object can be passed. 

1692 

1693 See :doc:`/user/cropping-and-transforming`. 

1694 

1695 """ 

1696 if isinstance(ctm, Transformation): 

1697 ctm = ctm.ctm 

1698 content = self.get_contents() 

1699 if content is not None: 

1700 content = PageObject._add_transformation_matrix(content, self.pdf, ctm) 

1701 content.isolate_graphics_state() 

1702 self.replace_contents(content) 

1703 # if expanding the page to fit a new page, calculate the new media box size 

1704 if expand: 

1705 corners = [ 

1706 self.mediabox.left.as_numeric(), 

1707 self.mediabox.bottom.as_numeric(), 

1708 self.mediabox.left.as_numeric(), 

1709 self.mediabox.top.as_numeric(), 

1710 self.mediabox.right.as_numeric(), 

1711 self.mediabox.top.as_numeric(), 

1712 self.mediabox.right.as_numeric(), 

1713 self.mediabox.bottom.as_numeric(), 

1714 ] 

1715 

1716 ctm = tuple(float(x) for x in ctm) # type: ignore[assignment] 

1717 new_x = [ 

1718 ctm[0] * corners[i] + ctm[2] * corners[i + 1] + ctm[4] 

1719 for i in range(0, 8, 2) 

1720 ] 

1721 new_y = [ 

1722 ctm[1] * corners[i] + ctm[3] * corners[i + 1] + ctm[5] 

1723 for i in range(0, 8, 2) 

1724 ] 

1725 

1726 self.mediabox.lower_left = (min(new_x), min(new_y)) 

1727 self.mediabox.upper_right = (max(new_x), max(new_y)) 

1728 

1729 def scale(self, sx: float, sy: float) -> None: 

1730 """ 

1731 Scale a page by the given factors by applying a transformation matrix 

1732 to its content and updating the page size. 

1733 

1734 This updates the various page boundaries (bleedbox, trimbox, etc.) 

1735 and the contents of the page. 

1736 

1737 Args: 

1738 sx: The scaling factor on horizontal axis. 

1739 sy: The scaling factor on vertical axis. 

1740 

1741 """ 

1742 self.add_transformation((sx, 0, 0, sy, 0, 0)) 

1743 self.bleedbox = self.bleedbox.scale(sx, sy) 

1744 self.trimbox = self.trimbox.scale(sx, sy) 

1745 self.artbox = self.artbox.scale(sx, sy) 

1746 self.cropbox = self.cropbox.scale(sx, sy) 

1747 self.mediabox = self.mediabox.scale(sx, sy) 

1748 

1749 if PageAttributes.ANNOTS in self: 

1750 annotations = self[PageAttributes.ANNOTS] 

1751 if isinstance(annotations, ArrayObject): 

1752 for annotation in annotations: 

1753 annotation_obj = annotation.get_object() 

1754 if AnnotationDictionaryAttributes.Rect in annotation_obj: 

1755 rectangle = annotation_obj[AnnotationDictionaryAttributes.Rect] 

1756 if isinstance(rectangle, ArrayObject): 

1757 rectangle[0] = FloatObject(float(rectangle[0]) * sx) 

1758 rectangle[1] = FloatObject(float(rectangle[1]) * sy) 

1759 rectangle[2] = FloatObject(float(rectangle[2]) * sx) 

1760 rectangle[3] = FloatObject(float(rectangle[3]) * sy) 

1761 

1762 if PageAttributes.VP in self: 

1763 viewport = self[PageAttributes.VP] 

1764 if isinstance(viewport, ArrayObject): 

1765 bbox = viewport[0]["/BBox"] 

1766 else: 

1767 bbox = viewport["/BBox"] # type: ignore[index] 

1768 scaled_bbox = RectangleObject( 

1769 ( 

1770 float(bbox[0]) * sx, 

1771 float(bbox[1]) * sy, 

1772 float(bbox[2]) * sx, 

1773 float(bbox[3]) * sy, 

1774 ) 

1775 ) 

1776 if isinstance(viewport, ArrayObject): 

1777 self[NameObject(PageAttributes.VP)][NumberObject(0)][ # type: ignore[index] 

1778 NameObject("/BBox") 

1779 ] = scaled_bbox 

1780 else: 

1781 self[NameObject(PageAttributes.VP)][NameObject("/BBox")] = scaled_bbox # type: ignore[index] 

1782 

1783 def scale_by(self, factor: float) -> None: 

1784 """ 

1785 Scale a page by the given factor by applying a transformation matrix to 

1786 its content and updating the page size. 

1787 

1788 Args: 

1789 factor: The scaling factor (for both X and Y axis). 

1790 

1791 """ 

1792 self.scale(factor, factor) 

1793 

1794 def scale_to(self, width: float, height: float) -> None: 

1795 """ 

1796 Scale a page to the specified dimensions by applying a transformation 

1797 matrix to its content and updating the page size. 

1798 

1799 Args: 

1800 width: The new width. 

1801 height: The new height. 

1802 

1803 """ 

1804 sx = width / float(self.mediabox.width) 

1805 sy = height / float(self.mediabox.height) 

1806 self.scale(sx, sy) 

1807 

1808 def compress_content_streams(self, level: int = -1) -> None: 

1809 """ 

1810 Compress the size of this page by joining all content streams and 

1811 applying a FlateDecode filter. 

1812 

1813 However, it is possible that this function will perform no action if 

1814 content stream compression becomes "automatic". 

1815 """ 

1816 content = self.get_contents() 

1817 if content is not None: 

1818 content_obj = content.flate_encode(level) 

1819 try: 

1820 content.indirect_reference.pdf._objects[ # type: ignore[union-attr] 

1821 content.indirect_reference.idnum - 1 # type: ignore[union-attr] 

1822 ] = content_obj 

1823 except AttributeError as exception: 

1824 if self.indirect_reference is not None and hasattr( 

1825 self.indirect_reference.pdf, "_add_object" 

1826 ): 

1827 self.replace_contents(content_obj) 

1828 else: 

1829 raise ValueError("Page must be part of a PdfWriter") from exception 

1830 

1831 @property 

1832 def page_number(self) -> int | None: 

1833 """ 

1834 Read-only property which returns the page number within the PDF file. 

1835 

1836 Returns: 

1837 Page number; None if the page is not attached to a PDF. 

1838 

1839 """ 

1840 if self.indirect_reference is None: 

1841 return None 

1842 page_number: int | None = self.indirect_reference.pdf._get_page_number_by_indirect( 

1843 self.indirect_reference 

1844 ) 

1845 return page_number 

1846 

1847 def _debug_for_extract(self) -> str: # pragma: no cover 

1848 out = "" 

1849 for ope, op in ContentStream( 

1850 self["/Contents"].get_object(), self.pdf, "bytes" 

1851 ).operations: 

1852 if op == b"TJ": 

1853 s = [x for x in ope[0] if isinstance(x, str)] 

1854 else: 

1855 s = [] 

1856 out += op.decode("utf-8") + " " + "".join(s) + ope.__repr__() + "\n" 

1857 out += "\n=============================\n" 

1858 try: 

1859 for fo in self[PageAttributes.RESOURCES]["/Font"]: # type: ignore[index] 

1860 out += fo + "\n" 

1861 out += self[PageAttributes.RESOURCES]["/Font"][fo].__repr__() + "\n" # type: ignore[index] 

1862 try: 

1863 enc_repr = self[PageAttributes.RESOURCES]["/Font"][fo][ # type: ignore[index] 

1864 "/Encoding" 

1865 ].__repr__() 

1866 out += enc_repr + "\n" 

1867 except MemoryError: # pragma: no cover # TODO: BLE001 

1868 raise 

1869 except Exception: 

1870 pass 

1871 try: 

1872 out += ( 

1873 self[PageAttributes.RESOURCES]["/Font"][fo][ # type: ignore[index] 

1874 "/ToUnicode" 

1875 ] 

1876 .get_data() 

1877 .decode() 

1878 + "\n" 

1879 ) 

1880 except MemoryError: # pragma: no cover # TODO: BLE001 

1881 raise 

1882 except Exception: 

1883 pass 

1884 

1885 except KeyError: 

1886 out += "No Font\n" 

1887 return out 

1888 

1889 def _extract_text( 

1890 self, 

1891 obj: DictionaryObject, 

1892 pdf: Any, 

1893 orientations: tuple[int, ...] = (0, 90, 180, 270), 

1894 space_width: float = 200.0, 

1895 content_key: str | None = PageAttributes.CONTENTS, 

1896 visitor_operand_before: Callable[[Any, Any, Any, Any], None] | None = None, 

1897 visitor_operand_after: Callable[[Any, Any, Any, Any], None] | None = None, 

1898 visitor_text: Callable[[Any, Any, Any, Any, Any], None] | None = None, 

1899 *, 

1900 known_ids: set[int] | None = None, 

1901 traversal_state: _TraversalState | None = None 

1902 ) -> str: 

1903 """ 

1904 See extract_text for most arguments. 

1905 

1906 Args: 

1907 content_key: indicate the default key where to extract data 

1908 None = the object; this allows reusing the function on an XObject 

1909 default = "/Content" 

1910 

1911 """ 

1912 if known_ids is None: 

1913 known_ids = set() 

1914 if traversal_state is None: 

1915 traversal_state = _TraversalState() 

1916 

1917 resources_dict = _get_page_resources(obj) 

1918 if not resources_dict: 

1919 # No resources means no text is possible (no font); we consider the 

1920 # file as not damaged, no need to check for TJ or Tj 

1921 return "" 

1922 

1923 font_resources: dict[str, DictionaryObject] = {} 

1924 fonts: dict[str, Font] = {} 

1925 if font_resources_dict := _get_font_resources(resources_dict): 

1926 for font_resource in font_resources_dict: 

1927 try: 

1928 font_resource_object = cast(DictionaryObject, font_resources_dict[font_resource].get_object()) 

1929 font_resources[font_resource] = font_resource_object 

1930 fonts[font_resource] = Font.from_font_resource(font_resource_object) 

1931 # Override space width, if applicable 

1932 if fonts[font_resource].character_widths.get(fonts[font_resource].space_char, 0) == 0: 

1933 fonts[font_resource].space_width = space_width 

1934 except (AttributeError, TypeError): 

1935 pass 

1936 

1937 from ._text_extraction import _get_content_stream_for_text # noqa: PLC0415 

1938 

1939 content = _get_content_stream_for_text( 

1940 obj, 

1941 pdf, 

1942 content_key, 

1943 has_visitor=any( 

1944 visitor is not None for visitor in (visitor_operand_before, visitor_operand_after, visitor_text) 

1945 ), 

1946 ) 

1947 if content is None: 

1948 return "" 

1949 # We check all strings are TextStringObjects. ByteStringObjects 

1950 # are strings where the byte->string encoding was unknown, so adding 

1951 # them to the text here would be gibberish. 

1952 

1953 # Initialize the extractor with the necessary parameters 

1954 extractor = TextExtraction() 

1955 extractor.initialize_extraction(orientations, visitor_text, font_resources, fonts) 

1956 

1957 for operands, operator in content.operations: 

1958 if visitor_operand_before is not None: 

1959 visitor_operand_before(operator, operands, extractor.cm_matrix, extractor.tm_matrix) 

1960 # Multiple operators are handled here 

1961 if operator == b"'": 

1962 extractor.process_operation(b"T*", []) 

1963 extractor.process_operation(b"Tj", operands) 

1964 elif operator == b'"' and len(operands) >= 3: 

1965 extractor.process_operation(b"Tw", [operands[0]]) 

1966 extractor.process_operation(b"Tc", [operands[1]]) 

1967 extractor.process_operation(b"T*", []) 

1968 extractor.process_operation(b"Tj", operands[2:]) 

1969 elif operator == b"TJ": 

1970 # The space width may be smaller than the font width, so the width should be 95%. 

1971 _confirm_space_width = extractor._space_width * 0.95 

1972 if operands and isinstance(operands[0], ArrayObject): 

1973 for op in operands[0]: 

1974 # A name is a str too, but not text to show 

1975 if isinstance(op, (str, bytes)) and not isinstance(op, NameObject): 

1976 extractor.process_operation(b"Tj", [op]) 

1977 if isinstance(op, (int, float, NumberObject, FloatObject)): 

1978 extractor.process_tj_offset(float(op), _confirm_space_width) 

1979 elif operator == b"TD" and len(operands) >= 2: 

1980 # a non-numeric ty leaves the leading unchanged, like a non-numeric TL 

1981 if isinstance(operands[1], (int, float)): 

1982 extractor.process_operation(b"TL", [-operands[1]]) 

1983 extractor.process_operation(b"Td", operands) 

1984 elif operator == b"Do" and operands: 

1985 extractor.output += extractor.text 

1986 if visitor_text is not None: 

1987 visitor_text( 

1988 extractor.text, 

1989 extractor.memo_cm, 

1990 extractor.memo_tm, 

1991 extractor.font_resource, 

1992 extractor.font_size, 

1993 ) 

1994 try: 

1995 if extractor.output[-1] != "\n": 

1996 extractor.output += "\n" 

1997 if visitor_text is not None: 

1998 visitor_text( 

1999 "\n", 

2000 extractor.memo_cm, 

2001 extractor.memo_tm, 

2002 extractor.font_resource, 

2003 extractor.font_size, 

2004 ) 

2005 except IndexError: 

2006 pass 

2007 try: 

2008 xform_text = self._extract_text__xform( 

2009 resources_dict=resources_dict, 

2010 operands=operands, 

2011 orientations=orientations, 

2012 space_width=space_width, 

2013 visitor_operand_before=visitor_operand_before, 

2014 visitor_operand_after=visitor_operand_after, 

2015 visitor_text=visitor_text, 

2016 known_ids=known_ids, 

2017 traversal_state=traversal_state 

2018 ) 

2019 if xform_text is not None: 

2020 text = xform_text 

2021 extractor.output += text 

2022 # Nothing else to do: each text piece inside the form has 

2023 # already been reported via visitor_text while the form was 

2024 # being extracted recursively (issue #4079). 

2025 except MemoryError: # pragma: no cover # TODO: BLE001 

2026 raise 

2027 except Exception as exception: 

2028 logger_warning( 

2029 "Impossible to decode XFormObject %(operand)s: %(exception)s", 

2030 source=__name__, 

2031 operand=operands[0], 

2032 exception=exception, 

2033 ) 

2034 finally: 

2035 extractor.text = "" 

2036 extractor.memo_cm = extractor.cm_matrix.copy() 

2037 extractor.memo_tm = extractor.tm_matrix.copy() 

2038 else: 

2039 extractor.process_operation(operator, operands) 

2040 if visitor_operand_after is not None: 

2041 visitor_operand_after(operator, operands, extractor.cm_matrix, extractor.tm_matrix) 

2042 extractor.output += extractor.text # just in case 

2043 if extractor.text != "" and visitor_text is not None: 

2044 visitor_text( 

2045 extractor.text, 

2046 extractor.memo_cm, 

2047 extractor.memo_tm, 

2048 extractor.font_resource, 

2049 extractor.font_size, 

2050 ) 

2051 return extractor.output 

2052 

2053 def _extract_text__xform( 

2054 self, 

2055 *, 

2056 resources_dict: DictionaryObject, 

2057 operands: Any, 

2058 orientations: tuple[int, ...] = (0, 90, 180, 270), 

2059 space_width: float = 200.0, 

2060 visitor_operand_before: Callable[[Any, Any, Any, Any], None] | None = None, 

2061 visitor_operand_after: Callable[[Any, Any, Any, Any], None] | None = None, 

2062 visitor_text: Callable[[Any, Any, Any, Any, Any], None] | None = None, 

2063 known_ids: set[int], 

2064 traversal_state: _TraversalState 

2065 ) -> str | None: 

2066 xobj = cast(DictionaryObject, resources_dict["/XObject"]) 

2067 xform = cast(EncodedStreamObject, xobj[operands[0]]) 

2068 if xform["/Subtype"] == NameObject("/Image"): 

2069 return None 

2070 

2071 xform_id = id(xform) 

2072 if xform_id in known_ids: 

2073 logger_warning( 

2074 "Detected cyclic form XObject reference, skipping %(operand)s.", 

2075 source=__name__, 

2076 operand=operands[0] 

2077 ) 

2078 return "" 

2079 

2080 configuration = get_configuration() 

2081 if traversal_state.entry_count >= configuration.xform_maximum_invocations_per_extraction: 

2082 if not traversal_state.has_logged: 

2083 traversal_state.has_logged = True 

2084 logger_warning( 

2085 ( 

2086 "Exceeded %(limit)d form XObject invocations while extracting text; " 

2087 "further form content is skipped." 

2088 ), 

2089 source=__name__, 

2090 limit=configuration.xform_maximum_invocations_per_extraction 

2091 ) 

2092 return "" 

2093 

2094 traversal_state.entry_count += 1 

2095 known_ids.add(xform_id) 

2096 try: 

2097 text = self.extract_xform_text( 

2098 xform, 

2099 orientations, 

2100 space_width, 

2101 visitor_operand_before, 

2102 visitor_operand_after, 

2103 visitor_text, 

2104 known_ids=known_ids, 

2105 traversal_state=traversal_state, 

2106 ) 

2107 finally: 

2108 known_ids.discard(xform_id) 

2109 return text 

2110 

2111 def _layout_mode_fonts(self) -> dict[str, Font]: 

2112 """ 

2113 Get fonts formatted for "layout" mode text extraction. 

2114 

2115 Returns: 

2116 Dict[str, Font]: dictionary of Font instances keyed by font name 

2117 

2118 """ 

2119 # Font retrieval logic adapted from pypdf.PageObject._extract_text() 

2120 obj: Any = self 

2121 fonts: dict[str, Font] = {} 

2122 visited: set[int] = set() 

2123 while True: 

2124 obj_id = id(obj) 

2125 if obj_id in visited: 

2126 logger_warning("Detected cycle in /Parent hierarchy when retrieving fonts.", source=__name__) 

2127 break 

2128 visited.add(obj_id) 

2129 

2130 resources_dict: Any = obj.get(PageAttributes.RESOURCES, DictionaryObject()).get_object() 

2131 if not isinstance(resources_dict, DictionaryObject): 

2132 logger_warning( 

2133 "Page resources are not a dictionary: %(resources)s", 

2134 source=__name__, 

2135 resources=resources_dict, 

2136 ) 

2137 resources_dict = DictionaryObject() 

2138 if self.pdf is not None and (font_resources := _get_font_resources(resources_dict)): 

2139 for font_name in font_resources: 

2140 font_object = font_resources[font_name] 

2141 if isinstance(font_object, DictionaryObject): 

2142 fonts[font_name] = Font.from_font_resource(font_object) 

2143 

2144 parent = obj.get("/Parent", NullObject()).get_object() 

2145 if not isinstance(parent, DictionaryObject): 

2146 break 

2147 obj = parent 

2148 

2149 return fonts 

2150 

2151 def _layout_mode_text( 

2152 self, 

2153 space_vertically: bool = True, 

2154 scale_weight: float = 1.25, 

2155 strip_rotated: bool = True, 

2156 debug_path: Path | None = None, 

2157 font_height_weight: float = 1, 

2158 ) -> str: 

2159 """ 

2160 Get text preserving fidelity to source PDF text layout. 

2161 

2162 Args: 

2163 space_vertically: include blank lines inferred from y distance + font 

2164 height. Defaults to True. 

2165 scale_weight: multiplier for string length when calculating weighted 

2166 average character width. Defaults to 1.25. 

2167 strip_rotated: Removes text that is rotated w.r.t. to the page from 

2168 layout mode output. Defaults to True. 

2169 debug_path (Path | None): if supplied, must target a directory. 

2170 creates the following files with debug information for layout mode 

2171 functions if supplied: 

2172 - fonts.json: output of self._layout_mode_fonts 

2173 - tjs.json: individual text render ops with corresponding transform matrices 

2174 - bts.json: text render ops left justified and grouped by BT/ET operators 

2175 - bt_groups.json: BT/ET operations grouped by rendered y-coord (aka lines) 

2176 Defaults to None. 

2177 font_height_weight: multiplier for font height when calculating 

2178 blank lines. Defaults to 1. 

2179 

2180 Returns: 

2181 str: multiline string containing page text in a fixed width format that 

2182 closely adheres to the rendered layout in the source pdf. 

2183 

2184 """ 

2185 fonts = self._layout_mode_fonts() 

2186 if debug_path: # pragma: no cover 

2187 import json # noqa: PLC0415 

2188 

2189 debug_path.joinpath("fonts.json").write_text( 

2190 json.dumps(fonts, indent=2, default=asdict), 

2191 "utf-8" 

2192 ) 

2193 

2194 contents = self.get("/Contents") 

2195 if contents is not None: 

2196 contents = contents.get_object() 

2197 if not isinstance(contents, (ArrayObject, StreamObject)): 

2198 # No content can be extracted (certainly an empty page). 

2199 return "" 

2200 

2201 ops = iter(ContentStream(contents, self.pdf, "bytes").operations) 

2202 bt_groups = _layout_mode.text_show_operations( 

2203 ops, fonts, strip_rotated, debug_path 

2204 ) 

2205 

2206 if not bt_groups: 

2207 return "" 

2208 

2209 ty_groups = _layout_mode.y_coordinate_groups(bt_groups, debug_path) 

2210 

2211 char_width = _layout_mode.fixed_char_width(bt_groups, scale_weight) 

2212 

2213 return _layout_mode.fixed_width_page(ty_groups, char_width, space_vertically, font_height_weight) 

2214 

2215 def extract_text( 

2216 self, 

2217 *args: Any, 

2218 orientations: int | tuple[int, ...] = (0, 90, 180, 270), 

2219 space_width: float = 200.0, 

2220 visitor_operand_before: Callable[[Any, Any, Any, Any], None] | None = None, 

2221 visitor_operand_after: Callable[[Any, Any, Any, Any], None] | None = None, 

2222 visitor_text: Callable[[Any, Any, Any, Any, Any], None] | None = None, 

2223 extraction_mode: Literal["plain", "layout"] = "plain", 

2224 **kwargs: Any, 

2225 ) -> str: 

2226 """ 

2227 Locate all text drawing commands, in the order they are provided in the 

2228 content stream, and extract the text. 

2229 

2230 This works well for some PDF files, but poorly for others, depending on 

2231 the generator used. This will be refined in the future. 

2232 

2233 Do not rely on the order of text coming out of this function, as it 

2234 will change if this function is made more sophisticated. 

2235 

2236 Arabic and Hebrew are extracted in the correct order. 

2237 If required a custom RTL range of characters can be defined; 

2238 see function set_custom_rtl. 

2239 

2240 Additionally you can provide visitor methods to get informed on all 

2241 operations and all text objects. 

2242 For example in some PDF files this can be useful to parse tables. 

2243 

2244 Args: 

2245 orientations: list of orientations extract_text will look for 

2246 default = (0, 90, 180, 270) 

2247 note: currently only 0 (up),90 (turned left), 180 (upside down), 

2248 270 (turned right) 

2249 Silently ignored in "layout" mode. 

2250 space_width: force default space width 

2251 if not extracted from font (default: 200) 

2252 Silently ignored in "layout" mode. 

2253 visitor_operand_before: function to be called before processing an operation. 

2254 It has four arguments: operator, operand-arguments, 

2255 current transformation matrix and text matrix. 

2256 Ignored with a warning in "layout" mode. 

2257 visitor_operand_after: function to be called after processing an operation. 

2258 It has four arguments: operator, operand-arguments, 

2259 current transformation matrix and text matrix. 

2260 Ignored with a warning in "layout" mode. 

2261 visitor_text: function to be called when extracting some text at some position. 

2262 It has five arguments: text, current transformation matrix, 

2263 text matrix, font-dictionary and font-size. 

2264 The font-dictionary may be None in case of unknown fonts. 

2265 If not None it may e.g. contain key "/BaseFont" with value "/Arial,Bold". 

2266 Ignored with a warning in "layout" mode. 

2267 extraction_mode (Literal["plain", "layout"]): "plain" for legacy functionality, 

2268 "layout" for experimental layout mode functionality. 

2269 NOTE: orientations, space_width, and visitor_* parameters are NOT respected 

2270 in "layout" mode. 

2271 

2272 kwargs: 

2273 layout_mode_space_vertically (bool): include blank lines inferred from 

2274 y distance + font height. Defaults to True. 

2275 layout_mode_scale_weight (float): multiplier for string length when calculating 

2276 weighted average character width. Defaults to 1.25. 

2277 layout_mode_strip_rotated (bool): layout mode does not support rotated text. 

2278 Set to False to include rotated text anyway. If rotated text is discovered, 

2279 layout will be degraded and a warning will result. Defaults to True. 

2280 layout_mode_debug_path (Path | None): if supplied, must target a directory. 

2281 creates the following files with debug information for layout mode 

2282 functions if supplied: 

2283 

2284 - fonts.json: output of self._layout_mode_fonts 

2285 - tjs.json: individual text render ops with corresponding transform matrices 

2286 - bts.json: text render ops left justified and grouped by BT/ET operators 

2287 - bt_groups.json: BT/ET operations grouped by rendered y-coord (aka lines) 

2288 layout_mode_font_height_weight (float): multiplier for font height when calculating 

2289 blank lines. Defaults to 1. 

2290 

2291 Returns: 

2292 The extracted text 

2293 

2294 """ 

2295 if extraction_mode not in ["plain", "layout"]: 

2296 raise ValueError(f"Invalid text extraction mode '{extraction_mode}'") 

2297 if extraction_mode == "layout": 

2298 for visitor in ( 

2299 "visitor_operand_before", 

2300 "visitor_operand_after", 

2301 "visitor_text", 

2302 ): 

2303 if locals()[visitor]: 

2304 logger_warning( 

2305 "Argument %(visitor)s is ignored in layout mode", 

2306 source=__name__, 

2307 visitor=visitor, 

2308 ) 

2309 return self._layout_mode_text( 

2310 space_vertically=kwargs.get("layout_mode_space_vertically", True), 

2311 scale_weight=kwargs.get("layout_mode_scale_weight", 1.25), 

2312 strip_rotated=kwargs.get("layout_mode_strip_rotated", True), 

2313 debug_path=kwargs.get("layout_mode_debug_path"), 

2314 font_height_weight=kwargs.get("layout_mode_font_height_weight", 1) 

2315 ) 

2316 if len(args) >= 1: 

2317 if isinstance(args[0], str): 

2318 if len(args) >= 3: 

2319 if isinstance(args[2], (tuple, int)): 

2320 orientations = args[2] 

2321 else: 

2322 raise TypeError(f"Invalid positional parameter {args[2]}") 

2323 if len(args) >= 4: 

2324 if isinstance(args[3], (float, int)): 

2325 space_width = args[3] 

2326 else: 

2327 raise TypeError(f"Invalid positional parameter {args[3]}") 

2328 elif isinstance(args[0], (tuple, int)): 

2329 orientations = args[0] 

2330 if len(args) >= 2: 

2331 if isinstance(args[1], (float, int)): 

2332 space_width = args[1] 

2333 else: 

2334 raise TypeError(f"Invalid positional parameter {args[1]}") 

2335 else: 

2336 raise TypeError(f"Invalid positional parameter {args[0]}") 

2337 

2338 if isinstance(orientations, int): 

2339 orientations = (orientations,) 

2340 

2341 return self._extract_text( 

2342 self, 

2343 self.pdf, 

2344 orientations, 

2345 space_width, 

2346 PageAttributes.CONTENTS, 

2347 visitor_operand_before, 

2348 visitor_operand_after, 

2349 visitor_text, 

2350 ) 

2351 

2352 def extract_xform_text( 

2353 self, 

2354 xform: EncodedStreamObject, 

2355 orientations: tuple[int, ...] = (0, 90, 270, 360), 

2356 space_width: float = 200.0, 

2357 visitor_operand_before: Callable[[Any, Any, Any, Any], None] | None = None, 

2358 visitor_operand_after: Callable[[Any, Any, Any, Any], None] | None = None, 

2359 visitor_text: Callable[[Any, Any, Any, Any, Any], None] | None = None, 

2360 *, 

2361 known_ids: set[int] | None = None, 

2362 traversal_state: Any | None = None 

2363 ) -> str: 

2364 """ 

2365 Extract text from an XObject. 

2366 

2367 Args: 

2368 xform: 

2369 orientations: 

2370 space_width: force default space width (if not extracted from font (default 200) 

2371 visitor_operand_before: 

2372 visitor_operand_after: 

2373 visitor_text: 

2374 known_ids: 

2375 traversal_state: 

2376 

2377 Returns: 

2378 The extracted text 

2379 

2380 """ 

2381 # The type hint would have to use an internal type otherwise, which is not desired. 

2382 assert traversal_state is None or isinstance(traversal_state, _TraversalState) 

2383 return self._extract_text( 

2384 xform, 

2385 self.pdf, 

2386 orientations, 

2387 space_width, 

2388 None, 

2389 visitor_operand_before, 

2390 visitor_operand_after, 

2391 visitor_text, 

2392 known_ids=known_ids, 

2393 traversal_state=traversal_state, 

2394 ) 

2395 

2396 def _get_fonts(self) -> tuple[set[str], set[str]]: 

2397 """ 

2398 Get the names of embedded fonts and unembedded fonts. 

2399 

2400 Returns: 

2401 A tuple (set of embedded fonts, set of unembedded fonts) 

2402 

2403 """ 

2404 obj = self.get_object() 

2405 assert isinstance(obj, DictionaryObject) 

2406 fonts: set[str] = set() 

2407 embedded: set[str] = set() 

2408 fonts, embedded = _get_fonts_walk(obj, fonts, embedded) 

2409 unembedded = fonts - embedded 

2410 return embedded, unembedded 

2411 

2412 mediabox = _create_rectangle_accessor(PageAttributes.MEDIABOX, ()) 

2413 """A :class:`RectangleObject<pypdf.generic.RectangleObject>`, expressed in 

2414 default user space units, defining the boundaries of the physical medium on 

2415 which the page is intended to be displayed or printed.""" 

2416 

2417 cropbox = _create_rectangle_accessor("/CropBox", (PageAttributes.MEDIABOX,)) 

2418 """ 

2419 A :class:`RectangleObject<pypdf.generic.RectangleObject>`, expressed in 

2420 default user space units, defining the visible region of default user 

2421 space. 

2422 

2423 When the page is displayed or printed, its contents are to be clipped 

2424 (cropped) to this rectangle and then imposed on the output medium in some 

2425 implementation-defined manner. Default value: same as 

2426 :attr:`mediabox<mediabox>`. 

2427 """ 

2428 

2429 bleedbox = _create_rectangle_accessor("/BleedBox", ("/CropBox", PageAttributes.MEDIABOX)) 

2430 """A :class:`RectangleObject<pypdf.generic.RectangleObject>`, expressed in 

2431 default user space units, defining the region to which the contents of the 

2432 page should be clipped when output in a production environment.""" 

2433 

2434 trimbox = _create_rectangle_accessor("/TrimBox", ("/CropBox", PageAttributes.MEDIABOX)) 

2435 """A :class:`RectangleObject<pypdf.generic.RectangleObject>`, expressed in 

2436 default user space units, defining the intended dimensions of the finished 

2437 page after trimming.""" 

2438 

2439 artbox = _create_rectangle_accessor("/ArtBox", ("/CropBox", PageAttributes.MEDIABOX)) 

2440 """A :class:`RectangleObject<pypdf.generic.RectangleObject>`, expressed in 

2441 default user space units, defining the extent of the page's meaningful 

2442 content as intended by the page's creator.""" 

2443 

2444 @property 

2445 def annotations(self) -> ArrayObject | None: 

2446 if "/Annots" not in self: 

2447 return None 

2448 annotations = self["/Annots"].get_object() 

2449 if not isinstance(annotations, ArrayObject): 

2450 logger_warning( 

2451 "Annotations are not an array: %(annotations)s", 

2452 source=__name__, 

2453 annotations=annotations, 

2454 ) 

2455 return None 

2456 return annotations 

2457 

2458 @annotations.setter 

2459 def annotations(self, value: ArrayObject | None) -> None: 

2460 """ 

2461 Set the annotations array of the page. 

2462 

2463 Typically you do not want to set this value, but append to it. 

2464 If you append to it, remember to add the object first to the writer 

2465 and only add the indirect object. 

2466 """ 

2467 if value is None: 

2468 if "/Annots" not in self: 

2469 return 

2470 del self[NameObject("/Annots")] 

2471 else: 

2472 self[NameObject("/Annots")] = value 

2473 

2474 def add_action(self, trigger: PageTrigger, action: Action) -> None: 

2475 """ 

2476 Add an action which will launch on the given trigger event of this page. 

2477 

2478 Args: 

2479 trigger: The action trigger to use. 

2480 action: The action to be done. 

2481 

2482 Example: 

2483 >>> from pypdf import PdfWriter 

2484 >>> from pypdf.actions import JavaScript, PageTrigger 

2485 >>> writer = PdfWriter() 

2486 >>> page = writer.add_blank_page(595, 842) 

2487 >>> # Display the page number when the page is opened 

2488 >>> page.add_action(PageTrigger("open"), JavaScript("app.alert('This is page ' + this.pageNum);")) 

2489 >>> # Display the page number when the page is closed 

2490 >>> page.add_action(PageTrigger("close"), JavaScript("app.alert('This is page ' + this.pageNum);")) 

2491 """ 

2492 return Action._create_new(self, trigger, action) 

2493 

2494 def delete_action(self, trigger: PageTrigger) -> None: 

2495 """ 

2496 Delete all actions associated with an open or close trigger event of this page. 

2497 

2498 Args: 

2499 trigger: An open or close trigger. 

2500 

2501 Example: 

2502 >>> from pypdf import PdfWriter 

2503 >>> from pypdf.actions import JavaScript, PageTrigger 

2504 >>> writer = PdfWriter() 

2505 >>> page = writer.add_blank_page(595, 842) 

2506 >>> page.add_action(PageTrigger("open"), JavaScript("app.alert('This is page ' + this.pageNum);")) 

2507 >>> page.add_action(PageTrigger("close"), JavaScript("app.alert('This is page ' + this.pageNum);")) 

2508 >>> # Delete all actions triggered by a page open 

2509 >>> page.delete_action(PageTrigger("open")) 

2510 >>> # Delete all actions triggered by a page close 

2511 >>> page.delete_action(PageTrigger("close")) 

2512 """ 

2513 return Action._delete(self, trigger) 

2514 

2515 

2516class _VirtualList(Sequence[PageObject]): 

2517 def __init__( 

2518 self, 

2519 length_function: Callable[[], int], 

2520 get_function: Callable[[int], PageObject], 

2521 ) -> None: 

2522 self.length_function = length_function 

2523 self.get_function = get_function 

2524 self.current = -1 

2525 

2526 def __len__(self) -> int: 

2527 return self.length_function() 

2528 

2529 @overload 

2530 def __getitem__(self, index: int) -> PageObject: 

2531 ... 

2532 

2533 @overload 

2534 def __getitem__(self, index: slice) -> Sequence[PageObject]: 

2535 ... 

2536 

2537 def __getitem__( 

2538 self, index: int | slice 

2539 ) -> PageObject | Sequence[PageObject]: 

2540 if isinstance(index, slice): 

2541 indices = range(*index.indices(len(self))) 

2542 cls = type(self) 

2543 return cls(indices.__len__, lambda idx: self[indices[idx]]) 

2544 if not isinstance(index, int): 

2545 raise TypeError("Sequence indices must be integers") 

2546 len_self = len(self) 

2547 if index < 0: 

2548 # support negative indexes 

2549 index += len_self 

2550 if not (0 <= index < len_self): 

2551 raise IndexError("Sequence index out of range") 

2552 return self.get_function(index) 

2553 

2554 def __delitem__(self, index: int | slice) -> None: 

2555 if isinstance(index, slice): 

2556 r = list(range(*index.indices(len(self)))) 

2557 # pages have to be deleted from last to first 

2558 r.sort() 

2559 r.reverse() 

2560 for p in r: 

2561 del self[p] # recursive call 

2562 return 

2563 if not isinstance(index, int): 

2564 raise TypeError("Index must be integers") 

2565 len_self = len(self) 

2566 if index < 0: 

2567 # support negative indexes 

2568 index += len_self 

2569 if not (0 <= index < len_self): 

2570 raise IndexError("Index out of range") 

2571 ind = self[index].indirect_reference 

2572 assert ind is not None 

2573 parent: PdfObject | None = cast(DictionaryObject, ind.get_object()).get( 

2574 "/Parent", None 

2575 ) 

2576 first = True 

2577 while parent is not None: 

2578 parent = cast(DictionaryObject, parent.get_object()) 

2579 try: 

2580 i = cast(ArrayObject, parent["/Kids"]).index(ind) 

2581 del cast(ArrayObject, parent["/Kids"])[i] 

2582 first = False 

2583 try: 

2584 assert ind is not None 

2585 del ind.pdf.flattened_pages[index] # case of page in a Reader 

2586 except MemoryError: # pragma: no cover # TODO: BLE001 

2587 raise 

2588 except Exception: # pragma: no cover 

2589 pass 

2590 if "/Count" in parent: 

2591 parent[NameObject("/Count")] = NumberObject( 

2592 cast(int, parent["/Count"]) - 1 

2593 ) 

2594 if len(cast(ArrayObject, parent["/Kids"])) == 0: 

2595 # No more objects in this part of this subtree 

2596 ind = parent.indirect_reference 

2597 parent = parent.get("/Parent", None) 

2598 except ValueError as exception: # from index 

2599 if first: 

2600 raise PdfReadError(f"Page not found in page tree: {ind}") from exception 

2601 break 

2602 

2603 def __iter__(self) -> Iterator[PageObject]: 

2604 for i in range(len(self)): 

2605 yield self[i] 

2606 

2607 def __str__(self) -> str: 

2608 p = [f"PageObject({i})" for i in range(self.length_function())] 

2609 return f"[{', '.join(p)}]" 

2610 

2611 

2612def _get_fonts_walk( 

2613 obj: DictionaryObject, 

2614 fnt: set[str], 

2615 emb: set[str], 

2616) -> tuple[set[str], set[str]]: 

2617 """ 

2618 Get the set of all fonts and all embedded fonts. 

2619 

2620 Args: 

2621 obj: Page resources dictionary 

2622 fnt: font 

2623 emb: embedded fonts 

2624 

2625 Returns: 

2626 A tuple (fnt, emb) 

2627 

2628 If there is a key called 'BaseFont', that is a font that is used in the document. 

2629 If there is a key called 'FontName' and another key in the same dictionary object 

2630 that is called 'FontFilex' (where x is null, 2, or 3), then that fontname is 

2631 embedded. 

2632 

2633 We create and add to two sets, fnt = fonts used and emb = fonts embedded. 

2634 

2635 """ 

2636 fontkeys = ("/FontFile", "/FontFile2", "/FontFile3") 

2637 

2638 def process_font(f: PdfObject) -> None: 

2639 nonlocal fnt, emb 

2640 f = cast(DictionaryObject, f.get_object()) # to be sure 

2641 if "/BaseFont" in f: 

2642 fnt.add(cast(str, f["/BaseFont"])) 

2643 

2644 if ( 

2645 ("/CharProcs" in f) 

2646 or ( 

2647 "/FontDescriptor" in f 

2648 and any( 

2649 x in cast(DictionaryObject, f["/FontDescriptor"]) for x in fontkeys 

2650 ) 

2651 ) 

2652 or ( 

2653 "/DescendantFonts" in f 

2654 and "/FontDescriptor" 

2655 in cast( 

2656 DictionaryObject, 

2657 cast(ArrayObject, f["/DescendantFonts"])[0].get_object(), 

2658 ) 

2659 and any( 

2660 x 

2661 in cast( 

2662 DictionaryObject, 

2663 cast( 

2664 DictionaryObject, 

2665 cast(ArrayObject, f["/DescendantFonts"])[0].get_object(), 

2666 )["/FontDescriptor"], 

2667 ) 

2668 for x in fontkeys 

2669 ) 

2670 ) 

2671 ): 

2672 # the list comprehension ensures there is FontFile 

2673 try: 

2674 emb.add(cast(str, f["/BaseFont"])) 

2675 except KeyError: 

2676 emb.add("(" + cast(str, f["/Subtype"]) + ")") 

2677 

2678 if "/DR" in obj and "/Font" in cast(DictionaryObject, obj["/DR"]): 

2679 for f in cast( 

2680 DictionaryObject, cast(DictionaryObject, obj["/DR"])["/Font"] 

2681 ).values(): 

2682 process_font(f) 

2683 if "/Resources" in obj: 

2684 resources = cast(DictionaryObject, obj["/Resources"]).get_object() 

2685 if not isinstance(resources, DictionaryObject): 

2686 if not is_null_or_none(resources): 

2687 logger_warning( 

2688 "Resources are not a dictionary: %(resources)s", 

2689 source=__name__, 

2690 resources=resources, 

2691 ) 

2692 resources = DictionaryObject() 

2693 if "/Font" in resources: 

2694 for f in cast(DictionaryObject, resources["/Font"]).values(): 

2695 process_font(f) 

2696 if "/XObject" in resources: 

2697 for x in cast(DictionaryObject, resources["/XObject"]).values(): 

2698 _get_fonts_walk(cast(DictionaryObject, x.get_object()), fnt, emb) 

2699 if "/Annots" in obj: 

2700 for a in cast(ArrayObject, obj["/Annots"]): 

2701 _get_fonts_walk(cast(DictionaryObject, a.get_object()), fnt, emb) 

2702 if "/AP" in obj: 

2703 # /N is optional, and may refer to a missing object 

2704 normal = cast(DictionaryObject, obj["/AP"]).get("/N") 

2705 if normal is not None: 

2706 normal = normal.get_object() 

2707 if isinstance(normal, StreamObject): 

2708 # /Type is optional in an appearance stream 

2709 _get_fonts_walk(normal, fnt, emb) 

2710 elif isinstance(normal, DictionaryObject): 

2711 # One appearance stream per state, e.g. /Off and /Yes of a check box 

2712 for a in normal.values(): 

2713 _get_fonts_walk(cast(DictionaryObject, a.get_object()), fnt, emb) 

2714 elif not is_null_or_none(normal): 

2715 logger_warning( 

2716 "The normal appearance is not a stream or a dictionary: %(normal)s", 

2717 source=__name__, 

2718 normal=normal, 

2719 ) 

2720 return fnt, emb # return the sets for each page