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

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1533 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 decimal 

31import enum 

32import hashlib 

33import re 

34import struct 

35import sys 

36from collections.abc import Callable, Iterable, Mapping, Sequence 

37from io import BytesIO, FileIO, IOBase 

38from itertools import compress 

39from pathlib import Path 

40from re import Pattern 

41from types import TracebackType 

42from typing import ( 

43 IO, 

44 Any, 

45 Literal, 

46 NoReturn, 

47 cast, 

48) 

49 

50if sys.version_info >= (3, 11): 

51 from typing import Self 

52else: 

53 from typing_extensions import Self 

54 

55from ._doc_common import DocumentInformation, PdfDocCommon 

56from ._encryption import EncryptAlgorithm, Encryption 

57from ._page import PageObject, Transformation 

58from ._page_labels import nums_clear_range, nums_insert, nums_next 

59from ._reader import PdfReader 

60from ._utils import ( 

61 StrByteType, 

62 StreamType, 

63 _get_max_pdf_version_header, 

64 deprecation_with_replacement, 

65 logger_warning, 

66) 

67from .actions import Action 

68from .constants import AnnotationDictionaryAttributes as AA 

69from .constants import ( 

70 CatalogAttributes, 

71 Core, 

72 GoToActionArguments, 

73 ImageType, 

74 InteractiveFormDictEntries, 

75 OutlineFontFlag, 

76 PageLabelStyle, 

77 PagesAttributes, 

78 UserAccessPermissions, 

79) 

80from .constants import FieldDictionaryAttributes as FA 

81from .constants import PageAttributes as PG 

82from .constants import TrailerKeys as TK 

83from .errors import LimitReachedError, PdfReadError, PyPdfError 

84from .generic import ( 

85 PAGE_FIT, 

86 ArrayObject, 

87 BooleanObject, 

88 ByteStringObject, 

89 ContentStream, 

90 Destination, 

91 DictionaryObject, 

92 EmbeddedFile, 

93 Fit, 

94 FloatObject, 

95 IndirectObject, 

96 NamedReferenceLink, 

97 NameObject, 

98 NullObject, 

99 NumberObject, 

100 PdfObject, 

101 RectangleObject, 

102 ReferenceLink, 

103 StreamObject, 

104 TextStringObject, 

105 TreeObject, 

106 ViewerPreferences, 

107 create_string_object, 

108 extract_links, 

109 hex_to_rgb, 

110 is_null_or_none, 

111) 

112from .generic._appearance_stream import TextStreamAppearance 

113from .pagerange import PageRange, PageRangeSpec 

114from .types import ( 

115 AnnotationSubtype, 

116 BorderArrayType, 

117 LayoutType, 

118 OutlineItemType, 

119 OutlineType, 

120 PagemodeType, 

121) 

122from .xmp import XmpInformation 

123 

124ALL_DOCUMENT_PERMISSIONS = UserAccessPermissions.all() 

125 

126 

127class ObjectDeletionFlag(enum.IntFlag): 

128 NONE = 0 

129 TEXT = enum.auto() 

130 LINKS = enum.auto() 

131 ATTACHMENTS = enum.auto() 

132 OBJECTS_3D = enum.auto() 

133 ALL_ANNOTATIONS = enum.auto() 

134 XOBJECT_IMAGES = enum.auto() 

135 INLINE_IMAGES = enum.auto() 

136 DRAWING_IMAGES = enum.auto() 

137 IMAGES = XOBJECT_IMAGES | INLINE_IMAGES | DRAWING_IMAGES 

138 

139 

140def _rolling_checksum(stream: BytesIO, blocksize: int = 65536) -> str: 

141 hash_object = hashlib.md5(usedforsecurity=False) 

142 for block in iter(lambda: stream.read(blocksize), b""): 

143 hash_object.update(block) 

144 return hash_object.hexdigest() 

145 

146 

147class PdfWriter(PdfDocCommon): 

148 """ 

149 Write a PDF file out, given pages produced by another class or through 

150 cloning a PDF file during initialization. 

151 

152 Typically data is added from a :class:`PdfReader<pypdf.PdfReader>`. 

153 

154 Args: 

155 clone_from: identical to fileobj (for compatibility) 

156 

157 incremental: If true, loads the document and set the PdfWriter in incremental mode. 

158 

159 When writing incrementally, the original document is written first and new/modified 

160 content is appended. To be used for signed document/forms to keep signature valid. 

161 

162 full: If true, loads all the objects (always full if incremental = True). 

163 This parameter may allow loading large PDFs. 

164 

165 strict: If true, pypdf will raise an exception if a PDF does not follow the specification. 

166 If false, pypdf will try to be forgiving and do something reasonable, but it will log 

167 a warning message. It is a best-effort approach. 

168 

169 keep_initial_header: If true, the PDF header of the cloned document is kept 

170 when using ``clone_from`` in non-incremental mode. 

171 

172 """ 

173 

174 incremental: bool 

175 """ 

176 Returns if the PdfWriter object has been started in incremental mode. 

177 """ 

178 

179 _objects: list[PdfObject | None] 

180 """ 

181 The indirect objects in the PDF. 

182 For the incremental case, it will be filled with None 

183 in clone_reader_document_root. 

184 """ 

185 

186 _id_translated: dict[int, dict[int | Literal["PreventGC"], Any]] 

187 """ 

188 List of already translated IDs. 

189 dict[id(pdf)][(idnum, generation)] 

190 """ 

191 

192 _reader: PdfReader | None 

193 """ 

194 The document being appended to, in incremental mode only. 

195 """ 

196 

197 def __init__( 

198 self, 

199 fileobj: PdfReader | StrByteType | Path | None = "", 

200 clone_from: PdfReader | StrByteType | Path | None = None, 

201 incremental: bool = False, 

202 full: bool = False, 

203 strict: bool = False, 

204 *, 

205 keep_initial_header: bool = False, 

206 incremental_clone_object_count_limit: int | None = 500_000, 

207 incremental_clone_object_id_limit: int | None = 1_000_000, 

208 ) -> None: 

209 self.strict = strict 

210 """ 

211 If true, pypdf will raise an exception if a PDF does not follow the specification. 

212 If false, pypdf will try to be forgiving and do something reasonable, but it will log 

213 a warning message. It is a best-effort approach. 

214 """ 

215 

216 self.incremental = incremental or full 

217 

218 self._objects = [] 

219 

220 self._original_hash: list[int] = [] 

221 """ 

222 List of hashes after import; used to identify changes. 

223 """ 

224 

225 self._idnum_hash: dict[bytes, tuple[IndirectObject, list[IndirectObject]]] = {} 

226 """ 

227 Maps hash values of indirect objects to the list of IndirectObjects. 

228 This is used for compression. 

229 """ 

230 

231 self._id_translated = {} 

232 

233 self._info_obj: PdfObject | None 

234 """The PDF files's document information dictionary, 

235 defined by Info in the PDF file's trailer dictionary.""" 

236 

237 self._reader = None 

238 

239 self._ID: ArrayObject | None = None 

240 """The PDF file identifier, 

241 defined by the ID in the PDF file's trailer dictionary.""" 

242 

243 self._unresolved_links: list[tuple[ReferenceLink, ReferenceLink]] = [] 

244 "Tracks links in pages added to the writer for resolving later." 

245 self._merged_in_pages: dict[IndirectObject | None, IndirectObject | None] = {} 

246 "Tracks pages added to the writer and what page they turned into." 

247 

248 # Security parameters. 

249 self._incremental_clone_object_count_limit = ( 

250 incremental_clone_object_count_limit 

251 if isinstance(incremental_clone_object_count_limit, int) 

252 else sys.maxsize 

253 ) 

254 self._incremental_clone_object_id_limit = ( 

255 incremental_clone_object_id_limit if isinstance(incremental_clone_object_id_limit, int) else sys.maxsize 

256 ) 

257 

258 if self.incremental: 

259 if isinstance(fileobj, (str, Path)): 

260 with open(fileobj, "rb") as f: 

261 fileobj = BytesIO(f.read(-1)) 

262 if isinstance(fileobj, BytesIO): 

263 fileobj = PdfReader(fileobj) 

264 if not isinstance(fileobj, PdfReader): 

265 raise PyPdfError("Invalid type for incremental mode") 

266 self._reader = fileobj # prev content is in _reader.stream 

267 self._header = fileobj.pdf_header.encode() 

268 self._readonly = True # TODO: to be analysed 

269 else: 

270 self._header = b"%PDF-1.3" 

271 self._info_obj = self._add_object( 

272 DictionaryObject( 

273 {NameObject("/Producer"): create_string_object("pypdf")} 

274 ) 

275 ) 

276 

277 def _get_clone_from( 

278 fileobj: PdfReader | str | Path | IO[Any] | BytesIO | None, 

279 clone_from: PdfReader | str | Path | IO[Any] | BytesIO | None, 

280 ) -> PdfReader | str | Path | IO[Any] | BytesIO | None: 

281 if isinstance(fileobj, (str, Path, IO, BytesIO)) and ( 

282 fileobj == "" or clone_from is not None 

283 ): 

284 return clone_from 

285 cloning = True 

286 if isinstance(fileobj, (str, Path)): 

287 fileobj_path = Path(fileobj) 

288 if not fileobj_path.exists() or fileobj_path.stat().st_size == 0: 

289 cloning = False 

290 elif isinstance(fileobj, (IOBase, BytesIO)): 

291 t = fileobj.tell() 

292 if fileobj.seek(0, 2) == 0: 

293 cloning = False 

294 fileobj.seek(t, 0) 

295 if cloning: 

296 clone_from = fileobj 

297 return clone_from 

298 

299 clone_from = _get_clone_from(fileobj, clone_from) 

300 # To prevent overwriting 

301 self.temp_fileobj = fileobj 

302 self.fileobj = "" 

303 self._with_as_usage = False 

304 self._cloned = False 

305 # The root of our page tree node 

306 pages = DictionaryObject( 

307 { 

308 NameObject(PagesAttributes.TYPE): NameObject("/Pages"), 

309 NameObject(PagesAttributes.COUNT): NumberObject(0), 

310 NameObject(PagesAttributes.KIDS): ArrayObject(), 

311 } 

312 ) 

313 self.flattened_pages = [] 

314 self._encryption: Encryption | None = None 

315 self._encrypt_entry: DictionaryObject | None = None 

316 

317 if clone_from is not None: 

318 if not isinstance(clone_from, PdfReader): 

319 clone_from = PdfReader(clone_from) 

320 self.clone_document_from_reader(clone_from) 

321 self._cloned = True 

322 if keep_initial_header and not self.incremental: 

323 self._header = clone_from.pdf_header.encode() 

324 else: 

325 self._pages = self._add_object(pages) 

326 self._root_object = DictionaryObject( 

327 { 

328 NameObject(PagesAttributes.TYPE): NameObject(Core.CATALOG), 

329 NameObject(Core.PAGES): self._pages, 

330 } 

331 ) 

332 self._add_object(self._root_object) 

333 if full and not incremental: 

334 self.incremental = False 

335 if isinstance(self._ID, list): 

336 if isinstance(self._ID[0], TextStringObject): 

337 self._ID[0] = ByteStringObject(self._ID[0].get_original_bytes()) 

338 if isinstance(self._ID[1], TextStringObject): 

339 self._ID[1] = ByteStringObject(self._ID[1].get_original_bytes()) 

340 

341 # for commonality 

342 @property 

343 def is_encrypted(self) -> bool: 

344 """ 

345 Read-only boolean property showing whether this PDF file is encrypted. 

346 

347 Note that this property, if true, will remain true even after the 

348 :meth:`decrypt()<pypdf.PdfReader.decrypt>` method is called. 

349 """ 

350 return False 

351 

352 @property 

353 def root_object(self) -> DictionaryObject: 

354 """ 

355 Provide direct access to PDF Structure. 

356 

357 Note: 

358 Recommended only for read access. 

359 

360 """ 

361 return self._root_object 

362 

363 @property 

364 def _info(self) -> DictionaryObject | None: 

365 """ 

366 Provide access to "/Info". Standardized with PdfReader. 

367 

368 Returns: 

369 /Info Dictionary; None if the entry does not exist 

370 

371 """ 

372 return ( 

373 None 

374 if self._info_obj is None 

375 else cast(DictionaryObject, self._info_obj.get_object()) 

376 ) 

377 

378 @_info.setter 

379 def _info(self, value: IndirectObject | DictionaryObject | None) -> None: 

380 if value is None: 

381 try: 

382 self._objects[self._info_obj.indirect_reference.idnum - 1] = None # type: ignore[union-attr] 

383 except (KeyError, AttributeError): 

384 pass 

385 self._info_obj = None 

386 else: 

387 if self._info_obj is None: 

388 self._info_obj = self._add_object(DictionaryObject()) 

389 obj = cast(DictionaryObject, self._info_obj.get_object()) 

390 obj.clear() 

391 obj.update(cast(DictionaryObject, value.get_object())) 

392 

393 @property 

394 def xmp_metadata(self) -> XmpInformation | None: 

395 """XMP (Extensible Metadata Platform) data.""" 

396 return cast(XmpInformation, self.root_object.xmp_metadata) 

397 

398 @xmp_metadata.setter 

399 def xmp_metadata(self, value: XmpInformation | bytes | None) -> None: 

400 """XMP (Extensible Metadata Platform) data.""" 

401 if value is None: 

402 if "/Metadata" in self.root_object: 

403 del self.root_object["/Metadata"] 

404 return 

405 

406 metadata = self.root_object.get("/Metadata", None) 

407 if not isinstance(metadata, IndirectObject): 

408 if metadata is not None: 

409 del self.root_object["/Metadata"] 

410 metadata_stream = StreamObject() 

411 stream_reference = self._add_object(metadata_stream) 

412 self.root_object[NameObject("/Metadata")] = stream_reference 

413 else: 

414 metadata_stream = cast(StreamObject, metadata.get_object()) 

415 

416 if isinstance(value, XmpInformation): 

417 bytes_data = value.stream.get_data() 

418 else: 

419 bytes_data = value 

420 metadata_stream.set_data(bytes_data) 

421 

422 def __enter__(self) -> Self: 

423 """Store how writer is initialized by 'with'.""" 

424 c: bool = self._cloned 

425 t = self.temp_fileobj 

426 self.__init__() # type: ignore[misc] 

427 self._cloned = c 

428 self._with_as_usage = True 

429 self.fileobj = t # type: ignore[assignment] 

430 return self 

431 

432 def __exit__( 

433 self, 

434 exc_type: type[BaseException] | None, 

435 exc: BaseException | None, 

436 traceback: TracebackType | None, 

437 ) -> None: 

438 """Write data to the fileobj.""" 

439 if self.fileobj and not self._cloned: 

440 self.write(self.fileobj) 

441 

442 @property 

443 def pdf_header(self) -> str: 

444 """ 

445 Read/Write property of the PDF header that is written. 

446 

447 This should be something like ``'%PDF-1.5'``. It is recommended to set 

448 the lowest version that supports all features which are used within the 

449 PDF file. 

450 

451 Note: `pdf_header` returns a string but accepts bytes or str for writing 

452 """ 

453 return self._header.decode() 

454 

455 @pdf_header.setter 

456 def pdf_header(self, new_header: str | bytes) -> None: 

457 if isinstance(new_header, str): 

458 new_header = new_header.encode() 

459 self._header = new_header 

460 

461 def _add_object(self, obj: PdfObject) -> IndirectObject: 

462 if ( 

463 getattr(obj, "indirect_reference", None) is not None 

464 and obj.indirect_reference.pdf == self # type: ignore[union-attr] 

465 ): 

466 return obj.indirect_reference # type: ignore[return-value] 

467 # check for /Contents in Pages (/Contents in annotations are strings) 

468 if isinstance(obj, DictionaryObject) and isinstance( 

469 obj.get(PG.CONTENTS, None), (ArrayObject, DictionaryObject) 

470 ): 

471 obj[NameObject(PG.CONTENTS)] = self._add_object(obj[PG.CONTENTS]) 

472 self._objects.append(obj) 

473 obj.indirect_reference = IndirectObject(len(self._objects), 0, self) 

474 return obj.indirect_reference 

475 

476 def get_object( 

477 self, 

478 indirect_reference: int | IndirectObject, 

479 ) -> PdfObject: 

480 if isinstance(indirect_reference, int): 

481 obj = self._objects[indirect_reference - 1] 

482 elif indirect_reference.pdf != self: 

483 raise ValueError("PDF must be self") 

484 else: 

485 obj = self._objects[indirect_reference.idnum - 1] 

486 if obj is None: 

487 raise PdfReadError(f"Object {indirect_reference!r} not found!") 

488 return obj 

489 

490 def _replace_object( 

491 self, 

492 indirect_reference: int | IndirectObject, 

493 obj: PdfObject, 

494 ) -> PdfObject: 

495 if isinstance(indirect_reference, IndirectObject): 

496 if indirect_reference.pdf != self: 

497 raise ValueError("PDF must be self") 

498 indirect_reference = indirect_reference.idnum 

499 gen = self._objects[indirect_reference - 1].indirect_reference.generation # type: ignore[union-attr] 

500 if ( 

501 getattr(obj, "indirect_reference", None) is not None 

502 and obj.indirect_reference.pdf != self # type: ignore[union-attr] 

503 ): 

504 obj = obj.clone(self) 

505 self._objects[indirect_reference - 1] = obj 

506 obj.indirect_reference = IndirectObject(indirect_reference, gen, self) 

507 

508 assert isinstance(obj, PdfObject), "mypy" 

509 return obj 

510 

511 def _add_page( 

512 self, 

513 page: PageObject, 

514 index: int, 

515 excluded_keys: Iterable[str] = (), 

516 ) -> PageObject: 

517 if not isinstance(page, PageObject) or page.get(PagesAttributes.TYPE, None) != Core.PAGE: 

518 raise ValueError("Invalid page object") 

519 assert self.flattened_pages is not None, "mypy" 

520 page_org = page 

521 excluded_keys = list(excluded_keys) 

522 excluded_keys += [PagesAttributes.PARENT, "/StructParents"] 

523 # Acrobat does not accept two indirect references pointing on the same 

524 # page; therefore in order to add multiple copies of the same 

525 # page, we need to create a new dictionary for the page, however the 

526 # objects below (including content) are not duplicated: 

527 try: # delete an already existing page 

528 del self._id_translated[id(page_org.indirect_reference.pdf)][ # type: ignore[union-attr] 

529 page_org.indirect_reference.idnum # type: ignore[union-attr] 

530 ] 

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

532 raise 

533 except Exception: 

534 pass 

535 

536 page = cast( 

537 "PageObject", page_org.clone(self, False, excluded_keys).get_object() 

538 ) 

539 if page_org.pdf is not None: 

540 other = page_org.pdf.pdf_header 

541 self.pdf_header = _get_max_pdf_version_header(self.pdf_header, other) 

542 

543 node, idx = self._get_page_in_node(index) 

544 page[NameObject(PagesAttributes.PARENT)] = node.indirect_reference 

545 

546 if idx >= 0: 

547 cast(ArrayObject, node[PagesAttributes.KIDS]).insert(idx, page.indirect_reference) 

548 self.flattened_pages.insert(index, page) 

549 else: 

550 cast(ArrayObject, node[PagesAttributes.KIDS]).append(page.indirect_reference) 

551 self.flattened_pages.append(page) 

552 current: PdfObject | None = node 

553 recurse = 0 

554 while not is_null_or_none(current): 

555 assert current is not None, "mypy" # guarded by is_null_or_none 

556 node_dict = cast(DictionaryObject, current.get_object()) 

557 node_dict[NameObject(PagesAttributes.COUNT)] = NumberObject(cast(int, node_dict[PagesAttributes.COUNT]) + 1) 

558 current = node_dict.get(PagesAttributes.PARENT, None) 

559 recurse += 1 

560 if recurse > 1000: 

561 raise PyPdfError("Too many recursive calls!") 

562 

563 if page_org.pdf is not None: 

564 # the page may contain links to other pages, and those other 

565 # pages may or may not already be added. we store the 

566 # information we need, so that we can resolve the references 

567 # later. 

568 if "/Annots" not in excluded_keys: 

569 self._unresolved_links.extend(extract_links(page, page_org)) 

570 self._merged_in_pages[page_org.indirect_reference] = page.indirect_reference 

571 

572 return page 

573 

574 def set_need_appearances_writer(self, state: bool = True) -> None: 

575 """ 

576 Sets the "NeedAppearances" flag in the PDF writer. 

577 

578 The "NeedAppearances" flag indicates whether the appearance dictionary 

579 for form fields should be automatically generated by the PDF viewer or 

580 if the embedded appearance should be used. 

581 

582 Args: 

583 state: The actual value of the NeedAppearances flag. 

584 

585 Returns: 

586 None 

587 

588 """ 

589 # See §12.7.2 and §7.7.2 for more information: 

590 # https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf 

591 try: 

592 # get the AcroForm tree 

593 if CatalogAttributes.ACRO_FORM not in self._root_object: 

594 self._root_object[ 

595 NameObject(CatalogAttributes.ACRO_FORM) 

596 ] = self._add_object(DictionaryObject()) 

597 

598 need_appearances = NameObject(InteractiveFormDictEntries.NeedAppearances) 

599 cast(DictionaryObject, self._root_object[CatalogAttributes.ACRO_FORM])[ 

600 need_appearances 

601 ] = BooleanObject(state) 

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

603 raise 

604 except Exception as exc: # pragma: no cover 

605 logger_warning( 

606 "set_need_appearances_writer(%(state)s) catch : %(exc)s", 

607 source=__name__, 

608 state=state, 

609 exc=exc, 

610 ) 

611 

612 def create_viewer_preferences(self) -> ViewerPreferences: 

613 o = ViewerPreferences() 

614 self._root_object[ 

615 NameObject(CatalogAttributes.VIEWER_PREFERENCES) 

616 ] = self._add_object(o) 

617 return o 

618 

619 def add_page( 

620 self, 

621 page: PageObject, 

622 excluded_keys: Iterable[str] = (), 

623 ) -> PageObject: 

624 """ 

625 Add a page to this PDF file. 

626 

627 Recommended for advanced usage including the adequate excluded_keys. 

628 

629 The page is usually acquired from a :class:`PdfReader<pypdf.PdfReader>` 

630 instance. 

631 

632 Args: 

633 page: The page to add to the document. Should be 

634 an instance of :class:`PageObject<pypdf._page.PageObject>` 

635 excluded_keys: 

636 

637 Returns: 

638 The added PageObject. 

639 

640 """ 

641 assert self.flattened_pages is not None, "mypy" 

642 return self._add_page(page, len(self.flattened_pages), excluded_keys) 

643 

644 def insert_page( 

645 self, 

646 page: PageObject, 

647 index: int = 0, 

648 excluded_keys: Iterable[str] = (), 

649 ) -> PageObject: 

650 """ 

651 Insert a page in this PDF file. The page is usually acquired from a 

652 :class:`PdfReader<pypdf.PdfReader>` instance. 

653 

654 Args: 

655 page: The page to add to the document. 

656 index: Position at which the page will be inserted. 

657 excluded_keys: 

658 

659 Returns: 

660 The added PageObject. 

661 

662 """ 

663 assert self.flattened_pages is not None, "mypy" 

664 if index < 0: 

665 index += len(self.flattened_pages) 

666 if index < 0: 

667 raise ValueError("Invalid index value") 

668 if index >= len(self.flattened_pages): 

669 return self.add_page(page, excluded_keys) 

670 return self._add_page(page, index, excluded_keys) 

671 

672 def _get_page_number_by_indirect( 

673 self, indirect_reference: int | NullObject | IndirectObject | None 

674 ) -> int | None: 

675 """ 

676 Generate _page_id2num. 

677 

678 Args: 

679 indirect_reference: 

680 

681 Returns: 

682 The page number or None 

683 

684 """ 

685 # To provide same function as in PdfReader 

686 if is_null_or_none(indirect_reference): 

687 return None 

688 assert indirect_reference is not None, "mypy" 

689 if isinstance(indirect_reference, int): 

690 indirect_reference = IndirectObject(indirect_reference, 0, self) 

691 obj = indirect_reference.get_object() 

692 if isinstance(obj, PageObject): 

693 return obj.page_number 

694 return None 

695 

696 def add_blank_page( 

697 self, width: float | None = None, height: float | None = None 

698 ) -> PageObject: 

699 """ 

700 Append a blank page to this PDF file and return it. 

701 

702 If no page size is specified, use the size of the last page. 

703 

704 Args: 

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

706 space units. 

707 height: The height of the new page expressed in default 

708 user space units. 

709 

710 Returns: 

711 The newly appended page. 

712 

713 Raises: 

714 PageSizeNotDefinedError: if width and height are not defined 

715 and previous page does not exist. 

716 

717 """ 

718 page = PageObject.create_blank_page(self, width, height) 

719 return self.add_page(page) 

720 

721 def insert_blank_page( 

722 self, 

723 width: float | decimal.Decimal | None = None, 

724 height: float | decimal.Decimal | None = None, 

725 index: int = 0, 

726 ) -> PageObject: 

727 """ 

728 Insert a blank page to this PDF file and return it. 

729 

730 If no page size is specified for a dimension, use the size of the last page. 

731 

732 Args: 

733 width: The width of the new page in default user space units. 

734 height: The height of the new page in default user space units. 

735 index: Position to add the page. 

736 

737 Returns: 

738 The newly inserted page. 

739 

740 Raises: 

741 PageSizeNotDefinedError: if width and height are not defined 

742 and previous page does not exist. 

743 IndexError: Index is outside of [-self.get_num_pages(), self.get_num_pages()] 

744 """ 

745 num_pages = self.get_num_pages() 

746 if abs(index) > num_pages: 

747 raise IndexError(f"Index should be in range [-{num_pages}, {num_pages}]") 

748 

749 if num_pages: 

750 # Use the chosen index, but do not exceed the available pages 

751 fixed_index = min(index, num_pages - 1) 

752 mediabox = self.pages[fixed_index].mediabox 

753 if width is None or width <= 0: 

754 width = mediabox.width 

755 if height is None or height <= 0: 

756 height = mediabox.height 

757 

758 page = PageObject.create_blank_page(self, width, height) 

759 self.insert_page(page, index) 

760 return page 

761 

762 @property 

763 def open_destination( 

764 self, 

765 ) -> Destination | TextStringObject | ByteStringObject | None: 

766 return super().open_destination 

767 

768 @open_destination.setter 

769 def open_destination(self, dest: str | Destination | PageObject | None) -> None: 

770 if dest is None: 

771 try: 

772 del self._root_object["/OpenAction"] 

773 except KeyError: 

774 pass 

775 elif isinstance(dest, str): 

776 self._root_object[NameObject("/OpenAction")] = TextStringObject(dest) 

777 elif isinstance(dest, Destination): 

778 self._root_object[NameObject("/OpenAction")] = dest.dest_array 

779 elif isinstance(dest, PageObject): 

780 self._root_object[NameObject("/OpenAction")] = Destination( 

781 "Opening", 

782 dest.indirect_reference 

783 if dest.indirect_reference is not None 

784 else NullObject(), 

785 PAGE_FIT, 

786 ).dest_array 

787 

788 def add_js(self, javascript: str) -> NoReturn: 

789 """ 

790 Add JavaScript which will launch upon opening this PDF. 

791 

792 Args: 

793 javascript: Your JavaScript. 

794 """ 

795 deprecation_with_replacement("add_js", "add_open_action", "7.0.0") 

796 

797 def add_open_action(self, action: Action) -> None: 

798 """ 

799 Add an action to the document-level JavaScript name tree. 

800 

801 Args: 

802 action: The action to add. 

803 

804 Example: 

805 This will launch the print window when the PDF is opened. 

806 

807 >>> from pypdf import PdfWriter 

808 >>> from pypdf.actions import JavaScript 

809 >>> output = PdfWriter() 

810 >>> output.add_open_action(JavaScript("this.print({bUI:true,bSilent:false,bShrinkToFit:true});")) 

811 """ 

812 return Action._create_open_action(self, action) 

813 

814 def add_attachment(self, filename: str, data: str | bytes) -> "EmbeddedFile": 

815 """ 

816 Embed a file inside the PDF. 

817 

818 Reference: 

819 https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf 

820 Section 7.11.3 

821 

822 Args: 

823 filename: The filename to display. 

824 data: The data in the file. 

825 

826 Returns: 

827 EmbeddedFile instance for the newly created embedded file. 

828 

829 """ 

830 return EmbeddedFile._create_new(self, filename, data) 

831 

832 def append_pages_from_reader( 

833 self, 

834 reader: PdfReader, 

835 after_page_append: Callable[[PageObject], None] | None = None, 

836 ) -> None: 

837 """ 

838 Copy pages from reader to writer. Includes an optional callback 

839 parameter which is invoked after pages are appended to the writer. 

840 

841 ``append`` should be preferred. 

842 

843 Args: 

844 reader: a PdfReader object from which to copy page 

845 annotations to this writer object. The writer's annots 

846 will then be updated. 

847 after_page_append: 

848 Callback function that is invoked after each page is appended to 

849 the writer. Signature includes a reference to the appended page 

850 (delegates to append_pages_from_reader). The single parameter of 

851 the callback is a reference to the page just appended to the 

852 document. 

853 

854 """ 

855 reader_num_pages = len(reader.pages) 

856 # Copy pages from reader to writer 

857 for reader_page_number in range(reader_num_pages): 

858 reader_page = reader.pages[reader_page_number] 

859 writer_page = self.add_page(reader_page) 

860 # Trigger callback, pass writer page as parameter 

861 if callable(after_page_append): 

862 after_page_append(writer_page) 

863 

864 def _merge_content_stream_to_page( 

865 self, 

866 page: PageObject, 

867 new_content_data: bytes, 

868 ) -> None: 

869 """ 

870 Combines existing content stream(s) with new content (as bytes). 

871 

872 Args: 

873 page: The page to which the new content data will be added. 

874 new_content_data: A binary-encoded new content stream, for 

875 instance the commands to draw an XObject. 

876 """ 

877 # First resolve the existing page content. This always is an IndirectObject: 

878 # PDF Explained by John Whitington 

879 # https://www.oreilly.com/library/view/pdf-explained/9781449321581/ch04.html 

880 if NameObject("/Contents") in page: 

881 existing_content_ref = page[NameObject("/Contents")] 

882 existing_content = existing_content_ref.get_object() 

883 

884 if isinstance(existing_content, ArrayObject): 

885 # Create a new StreamObject for the new_content_data 

886 new_stream_obj = StreamObject() 

887 new_stream_obj.set_data(new_content_data) 

888 existing_content.append(self._add_object(new_stream_obj)) 

889 page[NameObject("/Contents")] = self._add_object(existing_content) 

890 if isinstance(existing_content, StreamObject): 

891 # Merge new content to existing StreamObject 

892 merged_data = existing_content.get_data() + b"\n" + new_content_data 

893 new_stream = StreamObject() 

894 new_stream.set_data(merged_data) 

895 page[NameObject("/Contents")] = self._add_object(new_stream) 

896 else: 

897 # If no existing content, then we have an empty page. 

898 # Create a new StreamObject in a new /Contents entry. 

899 new_stream = StreamObject() 

900 new_stream.set_data(new_content_data) 

901 page[NameObject("/Contents")] = self._add_object(new_stream) 

902 

903 def _add_apstream_object( 

904 self, 

905 page: PageObject, 

906 appearance_stream_obj: StreamObject, 

907 object_name: str, 

908 x_offset: float, 

909 y_offset: float, 

910 ) -> None: 

911 """ 

912 Adds an appearance stream to the page content in the form of 

913 an XObject. 

914 

915 Args: 

916 page: The page to which to add the appearance stream. 

917 appearance_stream_obj: The appearance stream. 

918 object_name: The name of the appearance stream. 

919 x_offset: The horizontal offset for the appearance stream. 

920 y_offset: The vertical offset for the appearance stream. 

921 """ 

922 pg_res = cast(DictionaryObject, page[PG.RESOURCES]) 

923 # Always add the resolved stream object to the writer to get a new IndirectObject. 

924 # This ensures we have a valid IndirectObject managed by *this* writer. 

925 xobject_ref = self._add_object(appearance_stream_obj) 

926 xobject_name = NameObject(f"/Fm_{object_name}")._sanitize() 

927 if "/XObject" not in pg_res: 

928 pg_res[NameObject("/XObject")] = DictionaryObject() 

929 pg_xo_res = cast(DictionaryObject, pg_res["/XObject"]) 

930 if xobject_name not in pg_xo_res: 

931 pg_xo_res[xobject_name] = xobject_ref 

932 else: 

933 logger_warning( 

934 "XObject %(xobject_name)r already added to page resources. This might be an issue.", 

935 source=__name__, 

936 xobject_name=xobject_name, 

937 ) 

938 xobject_cm = Transformation().translate(x_offset, y_offset) 

939 xobject_drawing_commands = f"q\n{xobject_cm._to_cm()}\n{xobject_name} Do\nQ".encode() 

940 self._merge_content_stream_to_page(page, xobject_drawing_commands) 

941 

942 FFBITS_NUL = FA.FfBits(0) 

943 

944 def update_page_form_field_values( 

945 self, 

946 page: PageObject | list[PageObject] | None, 

947 fields: Mapping[str, str | list[str] | tuple[str, str, float]], 

948 flags: FA.FfBits = FFBITS_NUL, 

949 auto_regenerate: bool | None = True, 

950 flatten: bool = False, 

951 ) -> None: 

952 """ 

953 Update the form field values for a given page from a fields dictionary. 

954 

955 Copy field texts and values from fields to page. 

956 If the field links to a parent object, add the information to the parent. 

957 

958 Args: 

959 page: `PageObject` - references **PDF writer's page** where the 

960 annotations and field data will be updated. 

961 `List[Pageobject]` - provides list of pages to be processed. 

962 `None` - all pages. 

963 fields: a Python dictionary of: 

964 

965 * field names (/T) as keys and text values (/V) as value 

966 * field names (/T) as keys and list of text values (/V) for multiple choice list 

967 * field names (/T) as keys and tuple of: 

968 * text values (/V) 

969 * font id (e.g. /F1, the font id must exist) 

970 * font size (0 for autosize) 

971 

972 flags: A set of flags from :class:`~pypdf.constants.FieldDictionaryAttributes.FfBits`. 

973 

974 auto_regenerate: Set/unset the need_appearances flag; 

975 the flag is unchanged if auto_regenerate is None. 

976 

977 flatten: Whether or not to flatten the annotation. If True, this adds the annotation's 

978 appearance stream to the page contents. Note that this option does not remove the 

979 annotation itself. 

980 

981 """ 

982 if CatalogAttributes.ACRO_FORM not in self._root_object: 

983 raise PyPdfError("No /AcroForm dictionary in PDF of PdfWriter Object") 

984 acro_form = cast(DictionaryObject, self._root_object[CatalogAttributes.ACRO_FORM]) 

985 if InteractiveFormDictEntries.Fields not in acro_form: 

986 raise PyPdfError("No /Fields dictionary in PDF of PdfWriter Object") 

987 if isinstance(auto_regenerate, bool): 

988 self.set_need_appearances_writer(auto_regenerate) 

989 # Iterate through pages, update field values 

990 if page is None: 

991 page = list(self.pages) 

992 if isinstance(page, list): 

993 for p in page: 

994 if PG.ANNOTS in p: # just to prevent warnings 

995 self.update_page_form_field_values(p, fields, flags, None, flatten=flatten) 

996 return 

997 if PG.ANNOTS not in page: 

998 logger_warning("No fields to update on this page", source=__name__) 

999 return 

1000 appearance_stream_obj: StreamObject | None = None 

1001 

1002 for annotation in page[PG.ANNOTS]: # type: ignore[attr-defined] 

1003 annotation = cast(DictionaryObject, annotation.get_object()) 

1004 if annotation.get("/Subtype", "") != "/Widget": 

1005 continue 

1006 if "/FT" in annotation and "/T" in annotation: 

1007 parent_annotation = annotation 

1008 else: 

1009 parent_annotation = annotation.get( 

1010 PG.PARENT, DictionaryObject() 

1011 ).get_object() 

1012 

1013 for field, value in fields.items(): 

1014 rectangle = cast(RectangleObject, annotation[AA.Rect]) 

1015 if not ( 

1016 self._get_qualified_field_name(parent=parent_annotation) == field 

1017 or parent_annotation.get("/T", None) == field 

1018 ): 

1019 continue 

1020 if ( 

1021 parent_annotation.get("/FT", None) == "/Ch" 

1022 and "/I" in parent_annotation 

1023 ): 

1024 del parent_annotation["/I"] 

1025 if flags: 

1026 annotation[NameObject(FA.Ff)] = NumberObject(flags) 

1027 # Set the field value 

1028 if not (value is None and flatten): # Only change values if given by user and not flattening. 

1029 if isinstance(value, list): 

1030 lst = ArrayObject(TextStringObject(v) for v in value) 

1031 parent_annotation[NameObject(FA.V)] = lst 

1032 elif isinstance(value, tuple): 

1033 annotation[NameObject(FA.V)] = TextStringObject( 

1034 value[0], 

1035 ) 

1036 else: 

1037 parent_annotation[NameObject(FA.V)] = TextStringObject(value) 

1038 # Get or create the field's appearance stream object 

1039 if parent_annotation.get(FA.FT) == "/Btn": 

1040 # Checkbox button (no /FT found in Radio widgets); 

1041 # We can find the associated appearance stream object 

1042 # within the annotation. 

1043 v = NameObject(value) 

1044 ap = cast(DictionaryObject, annotation[NameObject(AA.AP)]) 

1045 normal_ap = cast(DictionaryObject, ap["/N"]) 

1046 if v not in normal_ap: 

1047 v = NameObject("/Off") 

1048 appearance_stream_obj = normal_ap.get(v) 

1049 # Other cases will be updated through the for loop 

1050 annotation[NameObject(AA.AS)] = v 

1051 annotation[NameObject(FA.V)] = v 

1052 elif ( 

1053 parent_annotation.get(FA.FT) == "/Tx" 

1054 or parent_annotation.get(FA.FT) == "/Ch" 

1055 ): 

1056 # Textbox; we need to generate the appearance stream object 

1057 if isinstance(value, tuple): 

1058 appearance_stream_obj = TextStreamAppearance.from_text_annotation( 

1059 self, page, flatten, acro_form, parent_annotation, annotation, value[1], value[2] 

1060 ) 

1061 else: 

1062 appearance_stream_obj = TextStreamAppearance.from_text_annotation( 

1063 self, page, flatten, acro_form, parent_annotation, annotation 

1064 ) 

1065 # Add the appearance stream object 

1066 if AA.AP not in annotation: 

1067 annotation[NameObject(AA.AP)] = DictionaryObject( 

1068 {NameObject("/N"): self._add_object(appearance_stream_obj)} 

1069 ) 

1070 elif "/N" not in (ap:= cast(DictionaryObject, annotation[AA.AP])): 

1071 cast(DictionaryObject, annotation[NameObject(AA.AP)])[ 

1072 NameObject("/N") 

1073 ] = self._add_object(appearance_stream_obj) 

1074 else: # [/AP][/N] exists 

1075 n = annotation[AA.AP]["/N"].indirect_reference.idnum # type: ignore[index] 

1076 self._objects[n - 1] = appearance_stream_obj 

1077 appearance_stream_obj.indirect_reference = IndirectObject(n, 0, self) 

1078 elif ( 

1079 annotation.get(FA.FT) == "/Sig" 

1080 ): # deprecated # not implemented yet 

1081 logger_warning("Signature forms not implemented yet", source=__name__) 

1082 

1083 if appearance_stream_obj and flatten: 

1084 self._add_apstream_object(page, appearance_stream_obj, field, rectangle[0], rectangle[1]) 

1085 

1086 def reattach_fields( 

1087 self, page: PageObject | None = None 

1088 ) -> list[DictionaryObject]: 

1089 """ 

1090 Parse annotations within the page looking for orphan fields and 

1091 reattach then into the Fields Structure. 

1092 

1093 Args: 

1094 page: page to analyze. 

1095 If none is provided, all pages will be analyzed. 

1096 

1097 Returns: 

1098 list of reattached fields. 

1099 

1100 """ 

1101 lst = [] 

1102 if page is None: 

1103 for p in self.pages: 

1104 lst += self.reattach_fields(p) 

1105 return lst 

1106 

1107 try: 

1108 af = cast(DictionaryObject, self._root_object[CatalogAttributes.ACRO_FORM]) 

1109 except KeyError: 

1110 af = DictionaryObject() 

1111 self._root_object[NameObject(CatalogAttributes.ACRO_FORM)] = af 

1112 try: 

1113 fields = cast(ArrayObject, af[InteractiveFormDictEntries.Fields]) 

1114 except KeyError: 

1115 fields = ArrayObject() 

1116 af[NameObject(InteractiveFormDictEntries.Fields)] = fields 

1117 

1118 if "/Annots" not in page: 

1119 return lst 

1120 annotations = cast(ArrayObject, page["/Annots"]) 

1121 for idx, annotation in enumerate(annotations): 

1122 is_indirect = isinstance(annotation, IndirectObject) 

1123 annotation = cast(DictionaryObject, annotation.get_object()) 

1124 if annotation.get("/Subtype", "") == "/Widget" and "/FT" in annotation: 

1125 if ( 

1126 "indirect_reference" in annotation.__dict__ 

1127 and annotation.indirect_reference in fields 

1128 ): 

1129 continue 

1130 if not is_indirect: 

1131 annotations[idx] = self._add_object(annotation) 

1132 fields.append(annotation.indirect_reference) 

1133 lst.append(annotation) 

1134 return lst 

1135 

1136 def _collect_incremental_clone_object_ids(self, reader: PdfReader) -> list[int]: 

1137 object_ids: set[int] = set() 

1138 for xref_entry in reader.xref.values(): 

1139 object_ids.update(filter(None, xref_entry)) 

1140 object_ids.update(filter(None, reader.xref_objStm)) 

1141 

1142 object_count = len(object_ids) 

1143 if object_count > self._incremental_clone_object_count_limit: 

1144 raise LimitReachedError( 

1145 f"Incremental clone object count {object_count} exceeds " 

1146 f"maximum allowed count {self._incremental_clone_object_count_limit}." 

1147 ) 

1148 

1149 max_object_id = max(object_ids, default=0) 

1150 if max_object_id > self._incremental_clone_object_id_limit: 

1151 raise LimitReachedError( 

1152 f"Incremental clone object ID {max_object_id} exceeds " 

1153 f"maximum allowed ID {self._incremental_clone_object_id_limit}." 

1154 ) 

1155 

1156 return sorted(object_ids) 

1157 

1158 def clone_reader_document_root(self, reader: PdfReader) -> None: 

1159 """ 

1160 Copy the reader document root to the writer and all sub-elements, 

1161 including pages, threads, outlines,... For partial insertion, ``append`` 

1162 should be considered. 

1163 

1164 Args: 

1165 reader: PdfReader from which the document root should be copied. 

1166 

1167 """ 

1168 self._info_obj = None 

1169 if self.incremental: 

1170 object_ids = self._collect_incremental_clone_object_ids(reader) 

1171 self._objects = [None] * (object_ids[-1] if object_ids else 0) 

1172 for object_id in object_ids: 

1173 reader_object = reader.get_object(object_id) 

1174 if reader_object is not None: 

1175 self._objects[object_id - 1] = reader_object.replicate(self) 

1176 else: 

1177 self._objects.clear() 

1178 self._root_object = reader.root_object.clone(self) 

1179 self._pages = self._root_object.raw_get("/Pages") 

1180 

1181 trailer_size = cast(int, reader.trailer["/Size"]) 

1182 if len(self._objects) > trailer_size: 

1183 if self.strict: 

1184 raise PdfReadError( 

1185 f"Object count {len(self._objects)} exceeds defined trailer size {trailer_size}" 

1186 ) 

1187 logger_warning( 

1188 "Object count %(object_count)d exceeds defined trailer size %(trailer_size)d", 

1189 source=__name__, 

1190 object_count=len(self._objects), 

1191 trailer_size=trailer_size, 

1192 ) 

1193 

1194 # must be done here before rewriting 

1195 if self.incremental: 

1196 self._original_hash = [ 

1197 (obj.hash_bin() if obj is not None else 0) for obj in self._objects 

1198 ] 

1199 

1200 try: 

1201 self._flatten() 

1202 except IndexError as exception: # pragma: no cover 

1203 raise PdfReadError("Got index error while flattening.") from exception # pragma: no cover 

1204 

1205 assert self.flattened_pages is not None 

1206 for p in self.flattened_pages: 

1207 self._replace_object(cast(IndirectObject, p.indirect_reference).idnum, p) 

1208 if not self.incremental: 

1209 p[NameObject("/Parent")] = self._pages 

1210 if not self.incremental: 

1211 cast(DictionaryObject, self._pages.get_object())[ 

1212 NameObject("/Kids") 

1213 ] = ArrayObject([p.indirect_reference for p in self.flattened_pages]) 

1214 

1215 def clone_document_from_reader( 

1216 self, 

1217 reader: PdfReader, 

1218 after_page_append: Callable[[PageObject], None] | None = None, 

1219 ) -> None: 

1220 """ 

1221 Create a copy (clone) of a document from a PDF file reader cloning 

1222 section '/Root' and '/Info' and '/ID' of the pdf. 

1223 

1224 Args: 

1225 reader: PDF file reader instance from which the clone 

1226 should be created. 

1227 after_page_append: 

1228 Callback function that is invoked after each page is appended to 

1229 the writer. Signature includes a reference to the appended page 

1230 (delegates to append_pages_from_reader). The single parameter of 

1231 the callback is a reference to the page just appended to the 

1232 document. 

1233 

1234 """ 

1235 self.clone_reader_document_root(reader) 

1236 inf = reader._info 

1237 if self.incremental: 

1238 if inf is not None: 

1239 self._info_obj = cast( 

1240 IndirectObject, inf.clone(self).indirect_reference 

1241 ) 

1242 assert isinstance(self._info, DictionaryObject), "mypy" 

1243 self._original_hash[ 

1244 self._info_obj.indirect_reference.idnum - 1 

1245 ] = self._info.hash_bin() 

1246 elif inf is not None: 

1247 self._info_obj = self._add_object(inf.clone(self)) 

1248 # else: _info_obj = None done in clone_reader_document_root() 

1249 

1250 try: 

1251 self._ID = cast(ArrayObject, reader._ID).clone(self) 

1252 except AttributeError: 

1253 pass 

1254 

1255 if callable(after_page_append): 

1256 for page in cast( 

1257 ArrayObject, cast(DictionaryObject, self._pages.get_object())["/Kids"] 

1258 ): 

1259 after_page_append(page.get_object()) 

1260 

1261 def _compute_document_identifier(self) -> ByteStringObject: 

1262 stream = BytesIO() 

1263 self._write_pdf_structure(stream) 

1264 stream.seek(0) 

1265 return ByteStringObject(_rolling_checksum(stream).encode("utf8")) 

1266 

1267 def generate_file_identifiers(self) -> None: 

1268 """ 

1269 Generate an identifier for the PDF that will be written. 

1270 

1271 The only point of this is ensuring uniqueness. Reproducibility is not 

1272 required. 

1273 When a file is first written, both identifiers shall be set to the same value. 

1274 If both identifiers match when a file reference is resolved, it is very 

1275 likely that the correct and unchanged file has been found. If only the first 

1276 identifier matches, a different version of the correct file has been found. 

1277 see §14.4 "File Identifiers". 

1278 """ 

1279 if self._ID: 

1280 id1 = self._ID[0] 

1281 id2 = self._compute_document_identifier() 

1282 else: 

1283 id1 = self._compute_document_identifier() 

1284 id2 = id1 

1285 self._ID = ArrayObject((id1, id2)) 

1286 

1287 def encrypt( 

1288 self, 

1289 user_password: str, 

1290 owner_password: str | None = None, 

1291 use_128bit: bool = True, 

1292 permissions_flag: UserAccessPermissions = ALL_DOCUMENT_PERMISSIONS, 

1293 *, 

1294 algorithm: str | None = None, 

1295 ) -> None: 

1296 """ 

1297 Encrypt this PDF file with the PDF Standard encryption handler. 

1298 

1299 Args: 

1300 user_password: The password which allows for opening 

1301 and reading the PDF file with the restrictions provided. 

1302 owner_password: The password which allows for 

1303 opening the PDF files without any restrictions. By default, 

1304 the owner password is the same as the user password. 

1305 use_128bit: flag as to whether to use 128bit 

1306 encryption. When false, 40bit encryption will be used. 

1307 By default, this flag is on. 

1308 permissions_flag: permissions as described in 

1309 Table 3.20 of the PDF 1.7 specification. A bit value of 1 means 

1310 the permission is granted. 

1311 Hence an integer value of -1 will set all flags. 

1312 Bit position 3 is for printing, 4 is for modifying content, 

1313 5 and 6 control annotations, 9 for form fields, 

1314 10 for extraction of text and graphics. 

1315 algorithm: encrypt algorithm. Values may be one of "RC4-40", "RC4-128", 

1316 "AES-128", "AES-256-R5", "AES-256". If it is valid, 

1317 `use_128bit` will be ignored. 

1318 

1319 """ 

1320 if self.incremental: 

1321 raise NotImplementedError("Encrypting incremental PDF files is currently not supported.") 

1322 

1323 if owner_password is None: 

1324 owner_password = user_password 

1325 

1326 if algorithm is not None: 

1327 try: 

1328 alg = getattr(EncryptAlgorithm, algorithm.replace("-", "_")) 

1329 except AttributeError as exception: # pragma: no cover 

1330 raise ValueError(f"Algorithm '{algorithm}' NOT supported") from exception # pragma: no cover 

1331 else: 

1332 alg = EncryptAlgorithm.RC4_128 

1333 if not use_128bit: 

1334 alg = EncryptAlgorithm.RC4_40 

1335 self.generate_file_identifiers() 

1336 assert self._ID 

1337 self._encryption = Encryption.make(alg, permissions_flag, self._ID[0]) 

1338 # in case call `encrypt` again 

1339 entry = self._encryption.write_entry(user_password, owner_password, strict=self.strict) 

1340 if self._encrypt_entry: 

1341 # replace old encrypt_entry 

1342 assert self._encrypt_entry.indirect_reference is not None 

1343 entry.indirect_reference = self._encrypt_entry.indirect_reference 

1344 self._objects[entry.indirect_reference.idnum - 1] = entry 

1345 else: 

1346 self._add_object(entry) 

1347 self._encrypt_entry = entry 

1348 

1349 def _resolve_links(self) -> None: 

1350 """Patch up links that were added to the document earlier, to 

1351 make sure they still point to the same pages. 

1352 """ 

1353 known_names: set[str] | None = None 

1354 for (new_link, old_link) in self._unresolved_links: 

1355 old_page = old_link.find_referenced_page() 

1356 if not old_page: 

1357 continue 

1358 new_page = self._merged_in_pages.get(old_page) 

1359 if new_page is None: 

1360 continue 

1361 if isinstance(new_link, NamedReferenceLink): 

1362 if known_names is None: 

1363 known_names = set(self.named_destinations) 

1364 new_link.patch_reference(self, new_page, known_names=known_names) 

1365 else: 

1366 new_link.patch_reference(self, new_page) 

1367 

1368 def write_stream(self, stream: StreamType) -> None: 

1369 if hasattr(stream, "mode") and "b" not in stream.mode: 

1370 logger_warning( 

1371 "File <%(stream_name)s> to write to is not in binary mode. " 

1372 "It may not be written to correctly.", 

1373 source=__name__, 

1374 stream_name=stream.name, 

1375 ) 

1376 self._resolve_links() 

1377 

1378 if self.incremental: 

1379 assert self._reader is not None, "mypy" 

1380 has_increment = len(self.list_objects_in_increment()) > 0 

1381 if has_increment and self._reader.is_encrypted: 

1382 raise NotImplementedError( 

1383 "Writing incremental updates of encrypted PDF files is currently not supported." 

1384 ) 

1385 self._reader.stream.seek(0) 

1386 stream.write(self._reader.stream.read(-1)) 

1387 if has_increment: 

1388 self._write_increment(stream) # writes objs, xref stream and startxref 

1389 else: 

1390 object_positions, free_objects = self._write_pdf_structure(stream) 

1391 xref_location = self._write_xref_table( 

1392 stream, object_positions, free_objects 

1393 ) 

1394 self._write_trailer(stream, xref_location) 

1395 

1396 def write(self, stream: Path | StrByteType) -> tuple[bool, IO[Any]]: 

1397 """ 

1398 Write the collection of pages added to this object out as a PDF file. 

1399 

1400 Args: 

1401 stream: An object to write the file to. The object can support 

1402 the write method and the tell method, similar to a file object, or 

1403 be a file path, just like the fileobj, just named it stream to keep 

1404 existing workflow. 

1405 

1406 Returns: 

1407 A tuple (bool, IO). 

1408 

1409 """ 

1410 my_file = False 

1411 

1412 if stream == "": 

1413 raise ValueError(f"Output({stream=}) is empty.") 

1414 

1415 if isinstance(stream, (str, Path)): 

1416 stream = FileIO(stream, "wb") 

1417 my_file = True 

1418 

1419 self.write_stream(stream) 

1420 

1421 if my_file: 

1422 stream.close() 

1423 else: 

1424 stream.flush() 

1425 

1426 return my_file, stream 

1427 

1428 def list_objects_in_increment(self) -> list[IndirectObject]: 

1429 """ 

1430 For analysis or debugging. 

1431 Provides the list of new or modified objects that will be written 

1432 in the increment. 

1433 Deleted objects will not be freed but will become orphans. 

1434 

1435 Returns: 

1436 List of new or modified IndirectObjects 

1437 

1438 """ 

1439 original_hash_count = len(self._original_hash) 

1440 return [ 

1441 cast(IndirectObject, obj).indirect_reference 

1442 for i, obj in enumerate(self._objects) 

1443 if ( 

1444 obj is not None 

1445 and ( 

1446 i >= original_hash_count 

1447 or obj.hash_bin() != self._original_hash[i] 

1448 ) 

1449 ) 

1450 ] 

1451 

1452 def _write_increment(self, stream: StreamType) -> None: 

1453 # Only reached from `write()` inside `if self.incremental`. 

1454 assert self._reader is not None, "mypy" 

1455 object_positions = {} 

1456 object_blocks = [] 

1457 current_start = -1 

1458 current_stop = -2 

1459 original_hash_count = len(self._original_hash) 

1460 for i, obj in enumerate(self._objects): 

1461 if obj is not None and ( 

1462 i >= original_hash_count 

1463 or obj.hash_bin() != self._original_hash[i] 

1464 ): 

1465 idnum = i + 1 

1466 assert isinstance(obj, PdfObject), "mypy" 

1467 # first write new/modified object 

1468 object_positions[idnum] = stream.tell() 

1469 stream.write(f"{idnum} 0 obj\n".encode()) 

1470 """ encryption is not operational 

1471 if self._encryption and obj != self._encrypt_entry: 

1472 obj = self._encryption.encrypt_object(obj, idnum, 0) 

1473 """ 

1474 obj.write_to_stream(stream) 

1475 stream.write(b"\nendobj\n") 

1476 

1477 # prepare xref 

1478 if idnum != current_stop: 

1479 if current_start > 0: 

1480 object_blocks.append( 

1481 [current_start, current_stop - current_start] 

1482 ) 

1483 current_start = idnum 

1484 current_stop = idnum + 1 

1485 assert current_start > 0, "for pytest only" 

1486 object_blocks.append([current_start, current_stop - current_start]) 

1487 # write incremented xref 

1488 xref_location = stream.tell() 

1489 xr_id = len(self._objects) + 1 

1490 stream.write(f"{xr_id} 0 obj".encode()) 

1491 init_data = { 

1492 NameObject("/Type"): NameObject("/XRef"), 

1493 NameObject("/Size"): NumberObject(xr_id + 1), 

1494 NameObject("/Root"): self.root_object.indirect_reference, 

1495 NameObject("/Filter"): NameObject("/FlateDecode"), 

1496 NameObject("/Index"): ArrayObject( 

1497 [NumberObject(_it) for _su in object_blocks for _it in _su] 

1498 ), 

1499 NameObject("/W"): ArrayObject( 

1500 [NumberObject(1), NumberObject(4), NumberObject(1)] 

1501 ), 

1502 "__streamdata__": b"", 

1503 } 

1504 if self._info is not None and ( 

1505 self._info.indirect_reference.idnum - 1 # type: ignore[union-attr] 

1506 >= len(self._original_hash) 

1507 or cast(IndirectObject, self._info).hash_bin() # kept for future 

1508 != self._original_hash[ 

1509 self._info.indirect_reference.idnum - 1 # type: ignore[union-attr] 

1510 ] 

1511 ): 

1512 init_data[NameObject(TK.INFO)] = self._info.indirect_reference 

1513 init_data[NameObject(TK.PREV)] = NumberObject(self._reader._startxref) 

1514 if self._ID: 

1515 init_data[NameObject(TK.ID)] = self._ID 

1516 xr = StreamObject.initialize_from_dictionary(init_data) 

1517 xr.set_data( 

1518 b"".join( 

1519 [struct.pack(b">BIB", 1, _pos, 0) for _pos in object_positions.values()] 

1520 ) 

1521 ) 

1522 xr.write_to_stream(stream) 

1523 stream.write(f"\nendobj\nstartxref\n{xref_location}\n%%EOF\n".encode()) # eof 

1524 

1525 def _write_pdf_structure(self, stream: StreamType) -> tuple[list[int], list[int]]: 

1526 object_positions = [] 

1527 free_objects = [] 

1528 stream.write(self.pdf_header.encode() + b"\n") 

1529 stream.write(b"%\xE2\xE3\xCF\xD3\n") 

1530 

1531 for idnum, obj in enumerate(self._objects, start=1): 

1532 if obj is not None: 

1533 object_positions.append(stream.tell()) 

1534 stream.write(f"{idnum} 0 obj\n".encode()) 

1535 if self._encryption and obj != self._encrypt_entry: 

1536 obj = self._encryption.encrypt_object(obj, idnum, 0) 

1537 obj.write_to_stream(stream) 

1538 stream.write(b"\nendobj\n") 

1539 else: 

1540 object_positions.append(-1) 

1541 free_objects.append(idnum) 

1542 free_objects.append(0) # add 0 to loop in accordance with specification 

1543 return object_positions, free_objects 

1544 

1545 def _write_xref_table( 

1546 self, stream: StreamType, object_positions: list[int], free_objects: list[int] 

1547 ) -> int: 

1548 xref_location = stream.tell() 

1549 stream.write(b"xref\n") 

1550 stream.write(f"0 {len(self._objects) + 1}\n".encode()) 

1551 stream.write(f"{free_objects[0]:0>10} {65535:0>5} f \n".encode()) 

1552 free_idx = 1 

1553 for offset in object_positions: 

1554 if offset > 0: 

1555 stream.write(f"{offset:0>10} {0:0>5} n \n".encode()) 

1556 else: 

1557 stream.write(f"{free_objects[free_idx]:0>10} {1:0>5} f \n".encode()) 

1558 free_idx += 1 

1559 return xref_location 

1560 

1561 def _write_trailer(self, stream: StreamType, xref_location: int) -> None: 

1562 """ 

1563 Write the PDF trailer to the stream. 

1564 

1565 To quote the PDF specification: 

1566 [The] trailer [gives] the location of the cross-reference table and 

1567 of certain special objects within the body of the file. 

1568 """ 

1569 stream.write(b"trailer\n") 

1570 trailer = DictionaryObject( 

1571 { 

1572 NameObject(TK.SIZE): NumberObject(len(self._objects) + 1), 

1573 NameObject(TK.ROOT): self.root_object.indirect_reference, 

1574 } 

1575 ) 

1576 if self._info is not None: 

1577 trailer[NameObject(TK.INFO)] = self._info.indirect_reference 

1578 if self._ID is not None: 

1579 trailer[NameObject(TK.ID)] = self._ID 

1580 if self._encrypt_entry: 

1581 trailer[NameObject(TK.ENCRYPT)] = self._encrypt_entry.indirect_reference 

1582 trailer.write_to_stream(stream) 

1583 stream.write(f"\nstartxref\n{xref_location}\n%%EOF\n".encode()) # eof 

1584 

1585 @property 

1586 def metadata(self) -> DocumentInformation | None: 

1587 """ 

1588 Retrieve/set the PDF file's document information dictionary, if it exists. 

1589 

1590 Args: 

1591 value: dict with the entries to be set. if None : remove the /Info entry from the pdf. 

1592 

1593 Note that some PDF files use (XMP) metadata streams instead of document 

1594 information dictionaries, and these metadata streams will not be 

1595 accessed by this function, but by :meth:`~xmp_metadata`. 

1596 

1597 """ 

1598 return super().metadata 

1599 

1600 @metadata.setter 

1601 def metadata( 

1602 self, 

1603 value: DocumentInformation | DictionaryObject | dict[Any, Any] | None, 

1604 ) -> None: 

1605 if value is None: 

1606 self._info = None 

1607 else: 

1608 if self._info is not None: 

1609 self._info.clear() 

1610 

1611 self.add_metadata(value) 

1612 

1613 def add_metadata(self, infos: dict[str, Any]) -> None: 

1614 """ 

1615 Add custom metadata to the output. 

1616 

1617 Args: 

1618 infos: a Python dictionary where each key is a field 

1619 and each value is your new metadata. 

1620 

1621 """ 

1622 args = {} 

1623 if isinstance(infos, PdfObject): 

1624 infos = cast(DictionaryObject, infos.get_object()) 

1625 for key, value in list(infos.items()): 

1626 if isinstance(value, PdfObject): 

1627 value = value.get_object() 

1628 args[NameObject(key)] = create_string_object(str(value)) 

1629 if self._info is None: 

1630 self._info = DictionaryObject() 

1631 self._info.update(args) 

1632 

1633 _UNSET = object() 

1634 

1635 def compress_identical_objects( 

1636 self, 

1637 remove_identicals: Any = _UNSET, 

1638 remove_orphans: Any = _UNSET, 

1639 *, 

1640 remove_duplicates: bool = True, 

1641 remove_unreferenced: bool = True, 

1642 ) -> None: 

1643 """ 

1644 Parse the PDF file and merge objects that have the same hash. 

1645 This will make objects common to multiple pages. 

1646 Recommended to be used just before writing output. 

1647 

1648 Args: 

1649 remove_identicals: Deprecated. 

1650 remove_orphans: Deprecated. 

1651 remove_duplicates: Remove duplicate objects. 

1652 remove_unreferenced: Remove unreferenced objects. 

1653 

1654 """ 

1655 if remove_identicals != self._UNSET: 

1656 deprecation_with_replacement("remove_identicals", "remove_duplicates", "7.0.0") 

1657 if remove_orphans != self._UNSET: 

1658 deprecation_with_replacement("remove_orphans", "remove_unreferenced", "7.0.0") 

1659 

1660 def replace_in_obj( 

1661 obj: PdfObject, crossref: dict[IndirectObject, IndirectObject] 

1662 ) -> None: 

1663 if isinstance(obj, DictionaryObject): 

1664 key_val = obj.items() 

1665 elif isinstance(obj, ArrayObject): 

1666 key_val = enumerate(obj) # type: ignore[assignment] 

1667 else: 

1668 return 

1669 assert isinstance(obj, (DictionaryObject, ArrayObject)) 

1670 for k, v in key_val: 

1671 if isinstance(v, IndirectObject): 

1672 unreferenced[v.idnum - 1] = False 

1673 if v in crossref: 

1674 obj[k] = crossref[v] 

1675 else: 

1676 """The filtering on DictionaryObject and ArrayObject only 

1677 will be performed within replace_in_obj""" 

1678 replace_in_obj(v, crossref) 

1679 

1680 # _idnum_hash: dict[hash] = (1st_ind_obj, [2nd_ind_obj,...]) 

1681 self._idnum_hash = {} 

1682 unreferenced = [True] * len(self._objects) 

1683 # look for similar objects 

1684 for idx, obj in enumerate(self._objects): 

1685 if is_null_or_none(obj): 

1686 continue 

1687 assert obj is not None, "mypy" # mypy: TypeGuard of `is_null_or_none` does not help here. 

1688 assert isinstance(obj.indirect_reference, IndirectObject) 

1689 h = obj.hash_value() 

1690 if remove_duplicates and h in self._idnum_hash: 

1691 self._idnum_hash[h][1].append(obj.indirect_reference) 

1692 self._objects[idx] = None 

1693 else: 

1694 self._idnum_hash[h] = (obj.indirect_reference, []) 

1695 

1696 # generate the dict converting others to 1st 

1697 cnv = {v[0]: v[1] for v in self._idnum_hash.values() if len(v[1]) > 0} 

1698 cnv_rev: dict[IndirectObject, IndirectObject] = {} 

1699 for k, v in cnv.items(): 

1700 cnv_rev.update(zip(v, (k,) * len(v))) 

1701 

1702 # replace reference to merged objects 

1703 for obj in self._objects: 

1704 if isinstance(obj, (DictionaryObject, ArrayObject)): 

1705 replace_in_obj(obj, cnv_rev) 

1706 

1707 if remove_unreferenced: 

1708 unreferenced[self.root_object.indirect_reference.idnum - 1] = False # type: ignore[union-attr] 

1709 

1710 if not is_null_or_none(self._info): 

1711 unreferenced[self._info.indirect_reference.idnum - 1] = False # type: ignore[union-attr] 

1712 

1713 try: 

1714 unreferenced[self._ID.indirect_reference.idnum - 1] = False # type: ignore[union-attr] 

1715 except AttributeError: 

1716 pass 

1717 

1718 for i in compress(range(len(self._objects)), unreferenced): 

1719 self._objects[i] = None 

1720 

1721 def get_reference(self, obj: PdfObject) -> IndirectObject: 

1722 idnum = self._objects.index(obj) + 1 

1723 ref = IndirectObject(idnum, 0, self) 

1724 assert ref.get_object() == obj 

1725 return ref 

1726 

1727 def get_outline_root(self) -> TreeObject: 

1728 if Core.OUTLINES in self._root_object: 

1729 # Entries in the catalog dictionary 

1730 outline = cast(TreeObject, self._root_object[Core.OUTLINES]) 

1731 if not isinstance(outline, TreeObject): 

1732 t = TreeObject(outline) 

1733 self._replace_object(outline.indirect_reference.idnum, t) 

1734 outline = t 

1735 else: 

1736 outline = TreeObject() 

1737 outline.update({}) 

1738 outline_ref = self._add_object(outline) 

1739 self._root_object[NameObject(Core.OUTLINES)] = outline_ref 

1740 

1741 return outline 

1742 

1743 def get_threads_root(self) -> ArrayObject: 

1744 """ 

1745 The list of threads. 

1746 

1747 See §12.4.3 of the PDF 1.7 or PDF 2.0 specification. 

1748 

1749 Returns: 

1750 An array (possibly empty) of Dictionaries with an ``/F`` key, 

1751 and optionally information about the thread in ``/I`` or ``/Metadata`` keys. 

1752 

1753 """ 

1754 if Core.THREADS in self._root_object: 

1755 # Entries in the catalog dictionary 

1756 threads = cast(ArrayObject, self._root_object[Core.THREADS]) 

1757 else: 

1758 threads = ArrayObject() 

1759 self._root_object[NameObject(Core.THREADS)] = threads 

1760 return threads 

1761 

1762 @property 

1763 def threads(self) -> ArrayObject: 

1764 """ 

1765 Read-only property for the list of threads. 

1766 

1767 See §12.4.3 of the PDF 1.7 or PDF 2.0 specification. 

1768 

1769 Each element is a dictionary with an ``/F`` key, and optionally 

1770 information about the thread in ``/I`` or ``/Metadata`` keys. 

1771 """ 

1772 return self.get_threads_root() 

1773 

1774 def add_outline_item_destination( 

1775 self, 

1776 page_destination: IndirectObject | PageObject | TreeObject, 

1777 parent: TreeObject | IndirectObject | None = None, 

1778 before: TreeObject | IndirectObject | None = None, 

1779 is_open: bool = True, 

1780 ) -> IndirectObject: 

1781 page_destination = cast(PageObject, page_destination.get_object()) 

1782 if isinstance(page_destination, PageObject): 

1783 return self.add_outline_item_destination( 

1784 Destination( 

1785 f"page #{page_destination.page_number}", 

1786 cast(IndirectObject, page_destination.indirect_reference), 

1787 Fit.fit(), 

1788 ) 

1789 ) 

1790 

1791 if parent is None: 

1792 parent = self.get_outline_root() 

1793 

1794 page_destination[NameObject("/%is_open%")] = BooleanObject(is_open) 

1795 parent = cast(TreeObject, parent.get_object()) 

1796 page_destination_ref = self._add_object(page_destination) 

1797 if before is not None: 

1798 before = before.indirect_reference 

1799 parent.insert_child( 

1800 page_destination_ref, 

1801 before, 

1802 self, 

1803 page_destination.inc_parent_counter_outline, 

1804 ) 

1805 if "/Count" not in page_destination: 

1806 page_destination[NameObject("/Count")] = NumberObject(0) 

1807 

1808 return page_destination_ref 

1809 

1810 def add_outline_item_dict( 

1811 self, 

1812 outline_item: OutlineItemType, 

1813 parent: TreeObject | IndirectObject | None = None, 

1814 before: TreeObject | IndirectObject | None = None, 

1815 is_open: bool = True, 

1816 ) -> IndirectObject: 

1817 outline_item_object = TreeObject() 

1818 outline_item_object.update(outline_item) 

1819 

1820 """code currently unreachable 

1821 if "/A" in outline_item: 

1822 action = DictionaryObject() 

1823 a_dict = cast(DictionaryObject, outline_item["/A"]) 

1824 for k, v in list(a_dict.items()): 

1825 action[NameObject(str(k))] = v 

1826 action_ref = self._add_object(action) 

1827 outline_item_object[NameObject("/A")] = action_ref 

1828 """ 

1829 return self.add_outline_item_destination( 

1830 outline_item_object, parent, before, is_open 

1831 ) 

1832 

1833 def add_outline_item( 

1834 self, 

1835 title: str, 

1836 page_number: PageObject | IndirectObject | int | None, 

1837 parent: TreeObject | IndirectObject | None = None, 

1838 before: TreeObject | IndirectObject | None = None, 

1839 color: tuple[float, float, float] | str | None = None, 

1840 bold: bool = False, 

1841 italic: bool = False, 

1842 fit: Fit = PAGE_FIT, 

1843 is_open: bool = True, 

1844 ) -> IndirectObject: 

1845 """ 

1846 Add an outline item (commonly referred to as a "Bookmark") to the PDF file. 

1847 

1848 Args: 

1849 title: Title to use for this outline item. 

1850 page_number: Page number this outline item will point to. 

1851 parent: A reference to a parent outline item to create nested 

1852 outline items. 

1853 before: 

1854 color: Color of the outline item's font as a red, green, blue tuple 

1855 from 0.0 to 1.0 or as a Hex String (#RRGGBB) 

1856 bold: Outline item font is bold 

1857 italic: Outline item font is italic 

1858 fit: The fit of the destination page. 

1859 

1860 Returns: 

1861 The added outline item as an indirect object. 

1862 

1863 """ 

1864 page_ref: NullObject | IndirectObject | NumberObject | None 

1865 if isinstance(italic, Fit): # it means that we are on the old params 

1866 if fit is not None and page_number is None: 

1867 page_number = fit 

1868 return self.add_outline_item( 

1869 title, page_number, parent, None, before, color, bold, italic, is_open=is_open 

1870 ) 

1871 if page_number is None: 

1872 action_ref = None 

1873 else: 

1874 if isinstance(page_number, IndirectObject): 

1875 page_ref = page_number 

1876 elif isinstance(page_number, PageObject): 

1877 page_ref = page_number.indirect_reference 

1878 elif isinstance(page_number, int): 

1879 try: 

1880 page_ref = self.pages[page_number].indirect_reference 

1881 except IndexError: 

1882 page_ref = NumberObject(page_number) 

1883 else: 

1884 raise TypeError(f"page_number: invalid type {type(page_number)}") 

1885 if page_ref is None: 

1886 logger_warning( 

1887 "can not find reference of page %(page_number)s", 

1888 source=__name__, 

1889 page_number=page_number, 

1890 ) 

1891 page_ref = NullObject() 

1892 dest = Destination( 

1893 NameObject("/" + title + " outline item"), 

1894 page_ref, 

1895 fit, 

1896 ) 

1897 

1898 action_ref = self._add_object( 

1899 DictionaryObject( 

1900 { 

1901 NameObject(GoToActionArguments.D): dest.dest_array, 

1902 NameObject(GoToActionArguments.S): NameObject("/GoTo"), 

1903 } 

1904 ) 

1905 ) 

1906 outline_item = self._add_object( 

1907 _create_outline_item(action_ref, title, color, italic, bold) 

1908 ) 

1909 

1910 if parent is None: 

1911 parent = self.get_outline_root() 

1912 return self.add_outline_item_destination(outline_item, parent, before, is_open) 

1913 

1914 def add_outline(self) -> None: 

1915 raise NotImplementedError( 

1916 "This method is not yet implemented. Use :meth:`add_outline_item` instead." 

1917 ) 

1918 

1919 def add_named_destination_array( 

1920 self, title: TextStringObject, destination: IndirectObject | ArrayObject 

1921 ) -> None: 

1922 named_dest = self.get_named_dest_root() 

1923 i = 0 

1924 while i < len(named_dest): 

1925 if title < named_dest[i]: 

1926 named_dest.insert(i, destination) 

1927 named_dest.insert(i, TextStringObject(title)) 

1928 return 

1929 i += 2 

1930 named_dest.extend([TextStringObject(title), destination]) 

1931 return 

1932 

1933 def add_named_destination_object( 

1934 self, 

1935 page_destination: PdfObject, 

1936 ) -> IndirectObject: 

1937 page_destination_ref = self._add_object(page_destination.dest_array) # type: ignore[attr-defined] 

1938 self.add_named_destination_array( 

1939 cast("TextStringObject", page_destination["/Title"]), page_destination_ref # type: ignore[index] 

1940 ) 

1941 

1942 return page_destination_ref 

1943 

1944 def _get_page_reference(self, page_number: int) -> Any: 

1945 """Look up a page by number, reporting a bad index rather than an IndexError from the kids array.""" 

1946 pages = cast(DictionaryObject, self.get_object(self._pages)) 

1947 kids = cast(ArrayObject, pages[PagesAttributes.KIDS]) 

1948 count = len(kids) 

1949 if not (-count <= page_number < count): 

1950 raise IndexError(f"Page number {page_number} is out of range") 

1951 return kids[page_number] 

1952 

1953 def add_named_destination( 

1954 self, 

1955 title: str, 

1956 page_number: int, 

1957 fit: Fit | None = None, 

1958 ) -> IndirectObject: 

1959 """ 

1960 Add a named destination to a page in this PDF. 

1961 

1962 Args: 

1963 title: Name of the destination. 

1964 page_number: Index of the destination page, starting at zero. 

1965 fit: How the destination is displayed. 

1966 Defaults to fitting the page horizontally with its 

1967 top edge at the top of the window. 

1968 

1969 Returns: 

1970 A reference to the destination's GoTo action. 

1971 

1972 """ 

1973 page_ref = self._get_page_reference(page_number) 

1974 if fit is None: 

1975 top = cast(DictionaryObject, page_ref.get_object()).get(PG.MEDIABOX) 

1976 top = RectangleObject(top).top if top is not None else 0 

1977 fit = Fit.fit_horizontally(top=top) 

1978 if not isinstance(title, TextStringObject): 

1979 title = TextStringObject(str(title)) 

1980 dest = DictionaryObject() 

1981 dest.update( 

1982 { 

1983 NameObject(GoToActionArguments.D): Destination(title, page_ref, fit).dest_array, 

1984 NameObject(GoToActionArguments.S): NameObject("/GoTo"), 

1985 } 

1986 ) 

1987 

1988 dest_ref = self._add_object(dest) 

1989 self.add_named_destination_array(title, dest_ref) 

1990 return dest_ref 

1991 

1992 def remove_links(self) -> None: 

1993 """Remove links and annotations from this output.""" 

1994 for page in self.pages: 

1995 self.remove_objects_from_page(page, ObjectDeletionFlag.ALL_ANNOTATIONS) 

1996 

1997 def remove_annotations( 

1998 self, subtypes: AnnotationSubtype | Iterable[AnnotationSubtype] | None 

1999 ) -> None: 

2000 """ 

2001 Remove annotations by annotation subtype. 

2002 

2003 Args: 

2004 subtypes: subtype or list of subtypes to be removed. 

2005 Examples are: "/Link", "/FileAttachment", "/Sound", 

2006 "/Movie", "/Screen", ... 

2007 If you want to remove all annotations, use subtypes=None. 

2008 

2009 """ 

2010 for page in self.pages: 

2011 self._remove_annots_from_page(page, subtypes) 

2012 

2013 def _remove_annots_from_page( 

2014 self, 

2015 page: IndirectObject | PageObject | DictionaryObject, 

2016 subtypes: Iterable[str] | None, 

2017 ) -> None: 

2018 page = cast(DictionaryObject, page.get_object()) 

2019 if PG.ANNOTS in page: 

2020 i = 0 

2021 while i < len(cast(ArrayObject, page[PG.ANNOTS])): 

2022 an = cast(ArrayObject, page[PG.ANNOTS])[i] 

2023 obj = cast(DictionaryObject, an.get_object()) 

2024 if subtypes is None or cast(str, obj["/Subtype"]) in subtypes: 

2025 if isinstance(an, IndirectObject): 

2026 self._objects[an.idnum - 1] = NullObject() # to reduce PDF size 

2027 del page[PG.ANNOTS][i] # type: ignore[attr-defined] 

2028 else: 

2029 i += 1 

2030 

2031 def remove_objects_from_page( 

2032 self, 

2033 page: PageObject | DictionaryObject, 

2034 to_delete: ObjectDeletionFlag | Iterable[ObjectDeletionFlag], 

2035 text_filters: dict[str, Any] | None = None 

2036 ) -> None: 

2037 """ 

2038 Remove objects specified by ``to_delete`` from the given page. 

2039 

2040 Args: 

2041 page: Page object to clean up. 

2042 to_delete: Objects to be deleted; can be a ``ObjectDeletionFlag`` 

2043 or a list of ObjectDeletionFlag 

2044 text_filters: Properties of text to be deleted, if applicable. Optional. 

2045 This is a Python dictionary with the following properties: 

2046 

2047 * font_ids: List of font resource IDs (such as /F1 or /T1_0) to be deleted. 

2048 

2049 """ 

2050 if isinstance(to_delete, (list, tuple)): 

2051 for to_d in to_delete: 

2052 self.remove_objects_from_page(page, to_d) 

2053 return None 

2054 assert isinstance(to_delete, ObjectDeletionFlag) 

2055 

2056 if to_delete & ObjectDeletionFlag.LINKS: 

2057 return self._remove_annots_from_page(page, ("/Link",)) 

2058 if to_delete & ObjectDeletionFlag.ATTACHMENTS: 

2059 return self._remove_annots_from_page( 

2060 page, ("/FileAttachment", "/Sound", "/Movie", "/Screen") 

2061 ) 

2062 if to_delete & ObjectDeletionFlag.OBJECTS_3D: 

2063 return self._remove_annots_from_page(page, ("/3D",)) 

2064 if to_delete & ObjectDeletionFlag.ALL_ANNOTATIONS: 

2065 return self._remove_annots_from_page(page, None) 

2066 

2067 jump_operators = [] 

2068 if to_delete & ObjectDeletionFlag.DRAWING_IMAGES: 

2069 jump_operators = [ 

2070 b"w", b"J", b"j", b"M", b"d", b"i", 

2071 b"W", b"W*", 

2072 b"b", b"b*", b"B", b"B*", b"S", b"s", b"f", b"f*", b"F", b"n", 

2073 b"m", b"l", b"c", b"v", b"y", b"h", b"re", 

2074 b"sh" 

2075 ] 

2076 if to_delete & ObjectDeletionFlag.TEXT: 

2077 jump_operators = [b"Tj", b"TJ", b"'", b'"'] 

2078 

2079 if not isinstance(page, PageObject): 

2080 page = PageObject(self, page.indirect_reference) # pragma: no cover 

2081 if "/Contents" in page: 

2082 content = cast(ContentStream, page.get_contents()) 

2083 

2084 images, forms = self._remove_objects_from_page__clean_forms( 

2085 elt=page, stack=[], jump_operators=jump_operators, to_delete=to_delete, text_filters=text_filters, 

2086 ) 

2087 

2088 self._remove_objects_from_page__clean( 

2089 content=content, images=images, forms=forms, 

2090 jump_operators=jump_operators, to_delete=to_delete, 

2091 text_filters=text_filters 

2092 ) 

2093 page.replace_contents(content) 

2094 return None 

2095 

2096 def _remove_objects_from_page__clean( 

2097 self, 

2098 content: ContentStream, 

2099 images: list[str], 

2100 forms: list[str], 

2101 jump_operators: list[bytes], 

2102 to_delete: ObjectDeletionFlag, 

2103 text_filters: dict[str, Any] | None = None, 

2104 ) -> None: 

2105 font_id = None 

2106 font_ids_to_delete = [] 

2107 if text_filters and to_delete & ObjectDeletionFlag.TEXT: 

2108 font_ids_to_delete = text_filters.get("font_ids", []) 

2109 

2110 i = 0 

2111 while i < len(content.operations): 

2112 operands, operator = content.operations[i] 

2113 if operator == b"Tf": 

2114 font_id = operands[0] 

2115 if ( 

2116 ( 

2117 operator == b"INLINE IMAGE" 

2118 and (to_delete & ObjectDeletionFlag.INLINE_IMAGES) 

2119 ) 

2120 or (operator in jump_operators) 

2121 or ( 

2122 operator == b"Do" 

2123 and (to_delete & ObjectDeletionFlag.XOBJECT_IMAGES) 

2124 and (operands[0] in images) 

2125 ) 

2126 ): 

2127 if ( 

2128 not to_delete & ObjectDeletionFlag.TEXT 

2129 or (to_delete & ObjectDeletionFlag.TEXT and not text_filters) 

2130 or (to_delete & ObjectDeletionFlag.TEXT and font_id in font_ids_to_delete) 

2131 ): 

2132 del content.operations[i] 

2133 else: 

2134 i += 1 

2135 else: 

2136 i += 1 

2137 content.get_data() # this ensures ._data is rebuilt from the .operations 

2138 

2139 def _remove_objects_from_page__clean_forms( 

2140 self, 

2141 elt: DictionaryObject, 

2142 stack: list[DictionaryObject], 

2143 jump_operators: list[bytes], 

2144 to_delete: ObjectDeletionFlag, 

2145 text_filters: dict[str, Any] | None = None, 

2146 ) -> tuple[list[str], list[str]]: 

2147 # elt in recursive call is a new ContentStream object, so we have to check the indirect_reference 

2148 if (elt in stack) or ( 

2149 hasattr(elt, "indirect_reference") and any( 

2150 elt.indirect_reference == getattr(x, "indirect_reference", -1) 

2151 for x in stack 

2152 ) 

2153 ): 

2154 # to prevent infinite looping 

2155 return [], [] # pragma: no cover 

2156 try: 

2157 d = cast( 

2158 dict[Any, Any], 

2159 cast(DictionaryObject, elt["/Resources"])["/XObject"], 

2160 ) 

2161 except KeyError: 

2162 d = {} 

2163 images = [] 

2164 forms = [] 

2165 for k, v in d.items(): 

2166 o = v.get_object() 

2167 try: 

2168 content: Any = None 

2169 if ( 

2170 to_delete & ObjectDeletionFlag.XOBJECT_IMAGES 

2171 and o["/Subtype"] == "/Image" 

2172 ): 

2173 content = NullObject() # to delete the image keeping the entry 

2174 images.append(k) 

2175 if o["/Subtype"] == "/Form": 

2176 forms.append(k) 

2177 if isinstance(o, ContentStream): 

2178 content = o 

2179 else: 

2180 content = ContentStream(o, self) 

2181 content.update( 

2182 { 

2183 k1: v1 

2184 for k1, v1 in o.items() 

2185 if k1 not in ["/Length", "/Filter", "/DecodeParms"] 

2186 } 

2187 ) 

2188 try: 

2189 content.indirect_reference = o.indirect_reference 

2190 except AttributeError: # pragma: no cover 

2191 pass 

2192 stack.append(elt) 

2193 

2194 # clean subforms 

2195 self._remove_objects_from_page__clean_forms( 

2196 elt=content, stack=stack, jump_operators=jump_operators, to_delete=to_delete, 

2197 text_filters=text_filters, 

2198 ) 

2199 if content is not None: 

2200 if isinstance(v, IndirectObject): 

2201 self._objects[v.idnum - 1] = content 

2202 else: 

2203 # should only occur in a PDF not respecting PDF spec 

2204 # where streams must be indirected. 

2205 d[k] = self._add_object(content) # pragma: no cover 

2206 except (TypeError, KeyError): 

2207 pass 

2208 for im in images: 

2209 del d[im] # for clean-up 

2210 if isinstance(elt, StreamObject): # for /Form 

2211 if not isinstance(elt, ContentStream): # pragma: no cover 

2212 e = ContentStream(elt, self) 

2213 e.update(elt.items()) 

2214 elt = e 

2215 # clean the content 

2216 self._remove_objects_from_page__clean( 

2217 content=elt, images=images, forms=forms, jump_operators=jump_operators, 

2218 to_delete=to_delete, text_filters=text_filters 

2219 ) 

2220 return images, forms 

2221 

2222 def remove_images( 

2223 self, 

2224 to_delete: ImageType = ImageType.ALL, 

2225 ) -> None: 

2226 """ 

2227 Remove images from this output. 

2228 

2229 Args: 

2230 to_delete: The type of images to be deleted 

2231 (default = all images types) 

2232 

2233 """ 

2234 if isinstance(to_delete, bool): 

2235 to_delete = ImageType.ALL 

2236 

2237 i = ObjectDeletionFlag.NONE 

2238 

2239 for image in ("XOBJECT_IMAGES", "INLINE_IMAGES", "DRAWING_IMAGES"): 

2240 if to_delete & ImageType[image]: 

2241 i |= ObjectDeletionFlag[image] 

2242 

2243 for page in self.pages: 

2244 self.remove_objects_from_page(page, i) 

2245 

2246 def remove_text(self, font_names: list[str] | None = None) -> None: 

2247 """ 

2248 Remove text from the PDF. 

2249 

2250 Args: 

2251 font_names: List of font names to remove, such as "Helvetica-Bold". 

2252 Optional. If not specified, all text will be removed. 

2253 """ 

2254 if not font_names: 

2255 font_names = [] 

2256 

2257 for page in self.pages: 

2258 resource_ids_to_remove = [] 

2259 

2260 # Content streams reference fonts and other resources with names like "/F1" or "/T1_0" 

2261 # Font names need to be converted to resource names/IDs for easier removal 

2262 if font_names: 

2263 # Recursively loop through page objects to gather font info 

2264 def get_font_info( 

2265 obj: Any, 

2266 font_info: dict[str, Any] | None = None, 

2267 key: str | None = None 

2268 ) -> dict[str, Any]: 

2269 if font_info is None: 

2270 font_info = {} 

2271 if isinstance(obj, IndirectObject): 

2272 obj = obj.get_object() 

2273 if isinstance(obj, dict): 

2274 if obj.get("/Type") == "/Font": 

2275 font_name = obj.get("/BaseFont", "") 

2276 # Normalize font names like "/RRXFFV+Palatino-Bold" to "Palatino-Bold" 

2277 normalized_font_name = font_name.lstrip("/").split("+")[-1] 

2278 if normalized_font_name not in font_info: 

2279 font_info[normalized_font_name] = { 

2280 "normalized_font_name": normalized_font_name, 

2281 "resource_ids": [], 

2282 } 

2283 if key not in font_info[normalized_font_name]["resource_ids"]: 

2284 font_info[normalized_font_name]["resource_ids"].append(key) 

2285 for k in obj: 

2286 font_info = get_font_info(obj[k], font_info, k) 

2287 elif isinstance(obj, (list, ArrayObject)): 

2288 for child_obj in obj: 

2289 font_info = get_font_info(child_obj, font_info) 

2290 return font_info 

2291 

2292 # Add relevant resource names for removal 

2293 font_info = get_font_info(page.get("/Resources")) 

2294 for font_name in font_names: 

2295 if font_name in font_info: 

2296 resource_ids_to_remove.extend(font_info[font_name]["resource_ids"]) 

2297 

2298 text_filters = {} 

2299 if font_names: 

2300 text_filters["font_ids"] = resource_ids_to_remove 

2301 self.remove_objects_from_page(page, ObjectDeletionFlag.TEXT, text_filters=text_filters) 

2302 

2303 def add_uri( 

2304 self, 

2305 page_number: int, 

2306 uri: str, 

2307 rect: RectangleObject, 

2308 border: Sequence[Any] | None = None, 

2309 ) -> None: 

2310 """ 

2311 Add an URI from a rectangular area to the specified page. 

2312 

2313 Args: 

2314 page_number: index of the page on which to place the URI action. 

2315 uri: URI of resource to link to. 

2316 rect: :class:`RectangleObject<pypdf.generic.RectangleObject>` or 

2317 array of four integers specifying the clickable rectangular area 

2318 ``[xLL, yLL, xUR, yUR]``, or string in the form 

2319 ``"[ xLL yLL xUR yUR ]"``. 

2320 border: if provided, an array describing border-drawing 

2321 properties. See the PDF spec for details. No border will be 

2322 drawn if this argument is omitted. 

2323 

2324 """ 

2325 page_link = self._get_page_reference(page_number) 

2326 page_ref = cast(dict[str, Any], self.get_object(page_link)) 

2327 

2328 border_arr: BorderArrayType 

2329 if border is not None: 

2330 border_arr = [NumberObject(n) for n in border[:3]] 

2331 if len(border) == 4: 

2332 dash_pattern = ArrayObject([NumberObject(n) for n in border[3]]) 

2333 border_arr.append(dash_pattern) 

2334 else: 

2335 border_arr = [NumberObject(2), NumberObject(2), NumberObject(2)] 

2336 

2337 if isinstance(rect, str): 

2338 coords = [float(n) for n in rect.strip().strip("[]").split()] 

2339 rect = RectangleObject(coords) 

2340 elif isinstance(rect, RectangleObject): 

2341 pass 

2342 else: 

2343 rect = RectangleObject(rect) 

2344 

2345 lnk2 = DictionaryObject() 

2346 lnk2.update( 

2347 { 

2348 NameObject("/S"): NameObject("/URI"), 

2349 NameObject("/URI"): TextStringObject(uri), 

2350 } 

2351 ) 

2352 lnk = DictionaryObject() 

2353 lnk.update( 

2354 { 

2355 NameObject(AA.Type): NameObject("/Annot"), 

2356 NameObject(AA.Subtype): NameObject("/Link"), 

2357 NameObject(AA.P): page_link, 

2358 NameObject(AA.Rect): rect, 

2359 NameObject("/H"): NameObject("/I"), 

2360 NameObject(AA.Border): ArrayObject(border_arr), 

2361 NameObject("/A"): lnk2, 

2362 } 

2363 ) 

2364 lnk_ref = self._add_object(lnk) 

2365 

2366 if PG.ANNOTS in page_ref: 

2367 page_ref[PG.ANNOTS].append(lnk_ref) 

2368 else: 

2369 page_ref[NameObject(PG.ANNOTS)] = ArrayObject([lnk_ref]) 

2370 

2371 _valid_layouts = ( 

2372 "/NoLayout", 

2373 "/SinglePage", 

2374 "/OneColumn", 

2375 "/TwoColumnLeft", 

2376 "/TwoColumnRight", 

2377 "/TwoPageLeft", 

2378 "/TwoPageRight", 

2379 ) 

2380 

2381 def _get_page_layout(self) -> LayoutType | None: 

2382 try: 

2383 return cast(LayoutType, self._root_object["/PageLayout"]) 

2384 except KeyError: 

2385 return None 

2386 

2387 def _set_page_layout(self, layout: NameObject | LayoutType) -> None: 

2388 """ 

2389 Set the page layout. 

2390 

2391 Args: 

2392 layout: The page layout to be used. 

2393 

2394 .. list-table:: Valid ``layout`` arguments 

2395 :widths: 50 200 

2396 

2397 * - /NoLayout 

2398 - Layout explicitly not specified 

2399 * - /SinglePage 

2400 - Show one page at a time 

2401 * - /OneColumn 

2402 - Show one column at a time 

2403 * - /TwoColumnLeft 

2404 - Show pages in two columns, odd-numbered pages on the left 

2405 * - /TwoColumnRight 

2406 - Show pages in two columns, odd-numbered pages on the right 

2407 * - /TwoPageLeft 

2408 - Show two pages at a time, odd-numbered pages on the left 

2409 * - /TwoPageRight 

2410 - Show two pages at a time, odd-numbered pages on the right 

2411 

2412 """ 

2413 if not isinstance(layout, NameObject): 

2414 if layout not in self._valid_layouts: 

2415 logger_warning( 

2416 "Layout should be one of: %(layouts)s", 

2417 source=__name__, 

2418 layouts=", ".join(self._valid_layouts), 

2419 ) 

2420 layout = NameObject(layout) 

2421 self._root_object.update({NameObject("/PageLayout"): layout}) 

2422 

2423 def set_page_layout(self, layout: LayoutType) -> None: 

2424 """ 

2425 Set the page layout. 

2426 

2427 Args: 

2428 layout: The page layout to be used 

2429 

2430 .. list-table:: Valid ``layout`` arguments 

2431 :widths: 50 200 

2432 

2433 * - /NoLayout 

2434 - Layout explicitly not specified 

2435 * - /SinglePage 

2436 - Show one page at a time 

2437 * - /OneColumn 

2438 - Show one column at a time 

2439 * - /TwoColumnLeft 

2440 - Show pages in two columns, odd-numbered pages on the left 

2441 * - /TwoColumnRight 

2442 - Show pages in two columns, odd-numbered pages on the right 

2443 * - /TwoPageLeft 

2444 - Show two pages at a time, odd-numbered pages on the left 

2445 * - /TwoPageRight 

2446 - Show two pages at a time, odd-numbered pages on the right 

2447 

2448 """ 

2449 self._set_page_layout(layout) 

2450 

2451 @property 

2452 def page_layout(self) -> LayoutType | None: 

2453 """ 

2454 Page layout property. 

2455 

2456 .. list-table:: Valid ``layout`` values 

2457 :widths: 50 200 

2458 

2459 * - /NoLayout 

2460 - Layout explicitly not specified 

2461 * - /SinglePage 

2462 - Show one page at a time 

2463 * - /OneColumn 

2464 - Show one column at a time 

2465 * - /TwoColumnLeft 

2466 - Show pages in two columns, odd-numbered pages on the left 

2467 * - /TwoColumnRight 

2468 - Show pages in two columns, odd-numbered pages on the right 

2469 * - /TwoPageLeft 

2470 - Show two pages at a time, odd-numbered pages on the left 

2471 * - /TwoPageRight 

2472 - Show two pages at a time, odd-numbered pages on the right 

2473 """ 

2474 return self._get_page_layout() 

2475 

2476 @page_layout.setter 

2477 def page_layout(self, layout: LayoutType) -> None: 

2478 self._set_page_layout(layout) 

2479 

2480 _valid_modes = ( 

2481 "/UseNone", 

2482 "/UseOutlines", 

2483 "/UseThumbs", 

2484 "/FullScreen", 

2485 "/UseOC", 

2486 "/UseAttachments", 

2487 ) 

2488 

2489 def _get_page_mode(self) -> PagemodeType | None: 

2490 try: 

2491 return cast(PagemodeType, self._root_object["/PageMode"]) 

2492 except KeyError: 

2493 return None 

2494 

2495 @property 

2496 def page_mode(self) -> PagemodeType | None: 

2497 """ 

2498 Page mode property. 

2499 

2500 .. list-table:: Valid ``mode`` values 

2501 :widths: 50 200 

2502 

2503 * - /UseNone 

2504 - Do not show outline or thumbnails panels 

2505 * - /UseOutlines 

2506 - Show outline (aka bookmarks) panel 

2507 * - /UseThumbs 

2508 - Show page thumbnails panel 

2509 * - /FullScreen 

2510 - Fullscreen view 

2511 * - /UseOC 

2512 - Show Optional Content Group (OCG) panel 

2513 * - /UseAttachments 

2514 - Show attachments panel 

2515 """ 

2516 return self._get_page_mode() 

2517 

2518 @page_mode.setter 

2519 def page_mode(self, mode: PagemodeType) -> None: 

2520 if isinstance(mode, NameObject): 

2521 mode_name: NameObject = mode 

2522 else: 

2523 if mode not in self._valid_modes: 

2524 logger_warning( 

2525 "Mode should be one of: %(modes)s", 

2526 source=__name__, 

2527 modes=", ".join(self._valid_modes), 

2528 ) 

2529 mode_name = NameObject(mode) 

2530 self._root_object.update({NameObject("/PageMode"): mode_name}) 

2531 

2532 def add_annotation( 

2533 self, 

2534 page_number: int | PageObject, 

2535 annotation: dict[str, Any], 

2536 ) -> DictionaryObject: 

2537 """ 

2538 Add a single annotation to the page. 

2539 The added annotation must be a new annotation. 

2540 It cannot be recycled. 

2541 

2542 Args: 

2543 page_number: PageObject or page index. 

2544 annotation: Annotation to be added (created with annotation). 

2545 

2546 Returns: 

2547 The inserted object. 

2548 This can be used for popup creation, for example. 

2549 

2550 """ 

2551 page = page_number 

2552 if isinstance(page, int): 

2553 page = self.pages[page] 

2554 elif not isinstance(page, PageObject): 

2555 raise TypeError("page: invalid type") 

2556 

2557 to_add = cast(DictionaryObject, _pdf_objectify(annotation)) 

2558 to_add[NameObject("/P")] = page.indirect_reference 

2559 

2560 if page.annotations is None: 

2561 page[NameObject("/Annots")] = ArrayObject() 

2562 assert page.annotations is not None 

2563 

2564 # Resolve pypdf's intermediate internal-link destination. 

2565 destination = to_add.get("/Dest") 

2566 if ( 

2567 to_add.get("/Subtype") == "/Link" 

2568 and isinstance(destination, DictionaryObject) 

2569 and "target_page_index" in destination 

2570 ): 

2571 target_page_reference: IndirectObject | NumberObject 

2572 target_page_index = cast(int, destination["target_page_index"]) 

2573 fit_type = cast(str, destination["fit"]) 

2574 # Work around the intermediate destination containing native Python 

2575 # objects instead of PdfObject instances. 

2576 fit_args = cast(Sequence[Any], dict(destination)["fit_args"]) 

2577 

2578 if 0 <= target_page_index < len(self.pages): 

2579 target_page_reference = cast( 

2580 IndirectObject, 

2581 self.pages[target_page_index].indirect_reference, 

2582 ) 

2583 else: 

2584 # Preserve support for referencing a page that may be added 

2585 # later. See #2450. 

2586 target_page_reference = NumberObject(target_page_index) 

2587 

2588 to_add[NameObject("/Dest")] = Destination( 

2589 NameObject("/LinkName"), 

2590 target_page_reference, 

2591 Fit(fit_type=fit_type, fit_args=fit_args), 

2592 ).dest_array 

2593 

2594 page.annotations.append(self._add_object(to_add)) 

2595 

2596 if to_add.get("/Subtype") == "/Popup" and NameObject("/Parent") in to_add: 

2597 cast(DictionaryObject, to_add["/Parent"].get_object())[ 

2598 NameObject("/Popup") 

2599 ] = to_add.indirect_reference 

2600 

2601 return to_add 

2602 

2603 def clean_page(self, page: PageObject | IndirectObject) -> PageObject: 

2604 """ 

2605 Perform some clean up in the page. 

2606 Currently: convert NameObject named destination to TextStringObject 

2607 (required for names/dests list) 

2608 

2609 Args: 

2610 page: 

2611 

2612 Returns: 

2613 The cleaned PageObject 

2614 

2615 """ 

2616 page = cast("PageObject", page.get_object()) 

2617 for a in page.get("/Annots", []): 

2618 a_obj = a.get_object() 

2619 d = a_obj.get("/Dest", None) 

2620 act = a_obj.get("/A", None) 

2621 if isinstance(d, NameObject): 

2622 a_obj[NameObject("/Dest")] = TextStringObject(d) 

2623 elif act is not None: 

2624 act = act.get_object() 

2625 d = act.get("/D", None) 

2626 if isinstance(d, NameObject): 

2627 act[NameObject("/D")] = TextStringObject(d) 

2628 return page 

2629 

2630 def _create_stream( 

2631 self, fileobj: Path | StrByteType | PdfReader 

2632 ) -> tuple[IOBase, Encryption | None]: 

2633 # If the fileobj parameter is a string, assume it is a path 

2634 # and create a file object at that location. If it is a file, 

2635 # copy the file's contents into a BytesIO stream object; if 

2636 # it is a PdfReader, copy that reader's stream into a 

2637 # BytesIO stream. 

2638 # If fileobj is none of the above types, it is not modified 

2639 encryption_obj = None 

2640 stream: IOBase 

2641 if isinstance(fileobj, (str, Path)): 

2642 with FileIO(fileobj, "rb") as f: 

2643 stream = BytesIO(f.read()) 

2644 elif isinstance(fileobj, PdfReader): 

2645 if fileobj._encryption: 

2646 encryption_obj = fileobj._encryption 

2647 orig_tell = fileobj.stream.tell() 

2648 fileobj.stream.seek(0) 

2649 stream = BytesIO(fileobj.stream.read()) 

2650 

2651 # reset the stream to its original location 

2652 fileobj.stream.seek(orig_tell) 

2653 elif hasattr(fileobj, "seek") and hasattr(fileobj, "read"): 

2654 fileobj.seek(0) 

2655 filecontent = fileobj.read() 

2656 stream = BytesIO(filecontent) 

2657 else: 

2658 raise NotImplementedError( 

2659 "Merging requires an object that PdfReader can parse. " 

2660 "Typically, that is a Path or a string representing a Path, " 

2661 "a file object, or an object implementing .seek and .read. " 

2662 "Passing a PdfReader directly works as well." 

2663 ) 

2664 return stream, encryption_obj 

2665 

2666 def append( 

2667 self, 

2668 fileobj: StrByteType | PdfReader | Path, 

2669 outline_item: str | PageRange | tuple[int, int] | tuple[int, int, int] | list[int] | None = None, 

2670 pages: PageRange | tuple[int, int] | tuple[int, int, int] | list[int] | list[PageObject] | None = None, 

2671 import_outline: bool = True, 

2672 excluded_fields: list[str] | tuple[str, ...] | None = None, 

2673 ) -> None: 

2674 """ 

2675 Identical to the :meth:`merge()<merge>` method, but assumes you want to 

2676 concatenate all pages onto the end of the file instead of specifying a 

2677 position. 

2678 

2679 Args: 

2680 fileobj: A File Object or an object that supports the standard 

2681 read and seek methods similar to a File Object. Could also be a 

2682 string representing a path to a PDF file. 

2683 outline_item: Optionally, you may specify a string to build an 

2684 outline (aka 'bookmark') to identify the beginning of the 

2685 included file. 

2686 pages: Can be a :class:`PageRange<pypdf.pagerange.PageRange>` 

2687 or a ``(start, stop[, step])`` tuple 

2688 or a list of pages to be processed 

2689 to merge only the specified range of pages from the source 

2690 document into the output document. 

2691 import_outline: You may prevent the source document's 

2692 outline (collection of outline items, previously referred to as 

2693 'bookmarks') from being imported by specifying this as ``False``. 

2694 excluded_fields: Provide the list of fields/keys to be ignored 

2695 if ``/Annots`` is part of the list, the annotation will be ignored 

2696 if ``/B`` is part of the list, the articles will be ignored 

2697 

2698 """ 

2699 if excluded_fields is None: 

2700 excluded_fields = () 

2701 if isinstance(outline_item, (tuple, list, PageRange)): 

2702 if isinstance(pages, bool): 

2703 if not isinstance(import_outline, bool): 

2704 excluded_fields = import_outline 

2705 import_outline = pages 

2706 pages = outline_item 

2707 self.merge( 

2708 None, 

2709 fileobj, 

2710 None, 

2711 pages, 

2712 import_outline, 

2713 excluded_fields, 

2714 ) 

2715 else: # if isinstance(outline_item, str): 

2716 self.merge( 

2717 None, 

2718 fileobj, 

2719 outline_item, 

2720 pages, 

2721 import_outline, 

2722 excluded_fields, 

2723 ) 

2724 

2725 def merge( 

2726 self, 

2727 position: int | None, 

2728 fileobj: Path | StrByteType | PdfReader, 

2729 outline_item: str | None = None, 

2730 pages: PageRangeSpec | list[PageObject] | None = None, 

2731 import_outline: bool = True, 

2732 excluded_fields: list[str] | tuple[str, ...] | None = (), 

2733 ) -> None: 

2734 """ 

2735 Merge the pages from the given file into the output file at the 

2736 specified page number. 

2737 

2738 Args: 

2739 position: The *page number* to insert this file. File will 

2740 be inserted after the given number. 

2741 fileobj: A File Object or an object that supports the standard 

2742 read and seek methods similar to a File Object. Could also be a 

2743 string representing a path to a PDF file. 

2744 outline_item: Optionally, you may specify a string to build an outline 

2745 (aka 'bookmark') to identify the 

2746 beginning of the included file. 

2747 pages: can be a :class:`PageRange<pypdf.pagerange.PageRange>` 

2748 or a ``(start, stop[, step])`` tuple 

2749 or a list of pages to be processed 

2750 to merge only the specified range of pages from the source 

2751 document into the output document. 

2752 import_outline: You may prevent the source document's 

2753 outline (collection of outline items, previously referred to as 

2754 'bookmarks') from being imported by specifying this as ``False``. 

2755 excluded_fields: provide the list of fields/keys to be ignored 

2756 if ``/Annots`` is part of the list, the annotation will be ignored 

2757 if ``/B`` is part of the list, the articles will be ignored 

2758 

2759 Raises: 

2760 TypeError: The pages attribute is not configured properly 

2761 

2762 """ 

2763 if isinstance(fileobj, PdfDocCommon): 

2764 reader = fileobj 

2765 else: 

2766 stream, _encryption_obj = self._create_stream(fileobj) 

2767 # Create a new PdfReader instance using the stream 

2768 # (either file or BytesIO or StringIO) created above 

2769 reader = PdfReader(stream, strict=False) # type: ignore[arg-type] 

2770 

2771 if excluded_fields is None: 

2772 excluded_fields = () 

2773 # Find the range of pages to merge. 

2774 if pages is None: 

2775 pages = list(range(len(reader.pages))) 

2776 elif isinstance(pages, PageRange): 

2777 pages = list(range(*pages.indices(len(reader.pages)))) 

2778 elif isinstance(pages, list): 

2779 pass # keep unchanged 

2780 elif isinstance(pages, tuple) and len(pages) <= 3: 

2781 pages = list(range(*pages)) 

2782 elif not isinstance(pages, tuple): 

2783 raise TypeError( 

2784 '"pages" must be a tuple of (start, stop[, step]) or a list' 

2785 ) 

2786 

2787 srcpages = {} 

2788 for page in pages: 

2789 if isinstance(page, PageObject): 

2790 pg = page 

2791 else: 

2792 pg = reader.pages[page] 

2793 assert pg.indirect_reference is not None 

2794 if position is None: 

2795 # numbers in the exclude list identifies that the exclusion is 

2796 # only applicable to 1st level of cloning 

2797 srcpages[pg.indirect_reference.idnum] = self.add_page( 

2798 pg, [*list(excluded_fields), 1, "/B", 1, "/Annots"] # type: ignore[list-item] 

2799 ) 

2800 else: 

2801 srcpages[pg.indirect_reference.idnum] = self.insert_page( 

2802 pg, position, [*list(excluded_fields), 1, "/B", 1, "/Annots"] # type: ignore[list-item] 

2803 ) 

2804 position += 1 

2805 srcpages[pg.indirect_reference.idnum].original_page = pg 

2806 

2807 reader._named_destinations = ( 

2808 reader.named_destinations 

2809 ) # need for the outline processing below 

2810 

2811 arr: Any 

2812 

2813 for dest in reader._named_destinations.values(): 

2814 self._merge__process_named_dests(dest=dest, reader=reader, srcpages=srcpages) 

2815 

2816 outline_item_typ: TreeObject 

2817 if outline_item is not None: 

2818 outline_item_typ = cast( 

2819 "TreeObject", 

2820 self.add_outline_item( 

2821 TextStringObject(outline_item), 

2822 next(iter(srcpages.values())).indirect_reference, 

2823 fit=PAGE_FIT, 

2824 ).get_object(), 

2825 ) 

2826 else: 

2827 outline_item_typ = self.get_outline_root() 

2828 

2829 _ro = reader.root_object 

2830 if import_outline and Core.OUTLINES in _ro: 

2831 outline = self._get_filtered_outline( 

2832 node=_ro.get(Core.OUTLINES, None), pages=srcpages, reader=reader 

2833 ) 

2834 self._insert_filtered_outline( 

2835 outline, outline_item_typ, None 

2836 ) # TODO: use before parameter 

2837 

2838 if "/Annots" not in excluded_fields: 

2839 parent_fields: dict[int, DictionaryObject] = {} 

2840 for pag in srcpages.values(): 

2841 lst = self._insert_filtered_annotations( 

2842 annots=pag.original_page.get("/Annots", []), 

2843 page=pag, 

2844 pages=srcpages, 

2845 reader=reader, 

2846 parent_fields=parent_fields, 

2847 ) 

2848 if len(lst) > 0: 

2849 pag[NameObject("/Annots")] = lst 

2850 self.clean_page(pag) 

2851 self._set_cloned_kids(parent_fields, reader) 

2852 

2853 acro_form = _ro.get("/AcroForm") 

2854 if acro_form is not None: 

2855 acro_form = acro_form.get_object() 

2856 if not is_null_or_none(acro_form) and not isinstance(acro_form, DictionaryObject): 

2857 logger_warning( 

2858 "AcroForm is not a dictionary: %(acro_form)s", 

2859 source=__name__, 

2860 acro_form=acro_form, 

2861 ) 

2862 if isinstance(acro_form, DictionaryObject): 

2863 writer_acro_form = self._root_object.get("/AcroForm") 

2864 if writer_acro_form is None or not isinstance(writer_acro_form.get_object(), DictionaryObject): 

2865 self._root_object[NameObject("/AcroForm")] = self._add_object( 

2866 acro_form.clone(self, False, ("/Fields",)) 

2867 ) 

2868 arr = ArrayObject() 

2869 else: 

2870 arr = cast(DictionaryObject, writer_acro_form.get_object()).get("/Fields", ArrayObject()).get_object() 

2871 if not isinstance(arr, ArrayObject): 

2872 arr = ArrayObject() 

2873 fields = acro_form.get("/Fields", ArrayObject()).get_object() 

2874 if not isinstance(fields, ArrayObject): 

2875 logger_warning( 

2876 "AcroForm /Fields is not an array: %(fields)s", 

2877 source=__name__, 

2878 fields=fields, 

2879 ) 

2880 fields = ArrayObject() 

2881 trslat = self._id_translated[id(reader)] 

2882 for f in fields: 

2883 # trslat only knows the fields which have been copied through the pages 

2884 if isinstance(f, IndirectObject) and f.idnum in trslat: 

2885 ind = IndirectObject(trslat[f.idnum], 0, self) 

2886 if ind not in arr: 

2887 arr.append(ind) 

2888 cast(DictionaryObject, self._root_object["/AcroForm"])[ 

2889 NameObject("/Fields") 

2890 ] = arr 

2891 

2892 if "/B" not in excluded_fields: 

2893 self.add_filtered_articles("", srcpages, reader) 

2894 

2895 def _merge__process_named_dests(self, dest: Any, reader: PdfDocCommon, srcpages: dict[int, PageObject]) -> None: 

2896 arr: Any = dest.dest_array 

2897 if "/Names" in self._root_object and dest["/Title"] in cast( 

2898 list[Any], 

2899 cast( 

2900 DictionaryObject, 

2901 cast(DictionaryObject, self._root_object["/Names"]).get("/Dests", DictionaryObject()), 

2902 ).get("/Names", DictionaryObject()), 

2903 ): 

2904 # already exists: should not duplicate it 

2905 pass 

2906 elif dest["/Page"] is None or isinstance(dest["/Page"], NullObject): 

2907 pass 

2908 elif isinstance(dest["/Page"], int): 

2909 # the page reference is a page number normally not a PDF Reference 

2910 # page numbers as int are normally accepted only in external goto 

2911 try: 

2912 p = reader.pages[dest["/Page"]] 

2913 except IndexError: 

2914 return 

2915 assert p.indirect_reference is not None 

2916 try: 

2917 arr[NumberObject(0)] = NumberObject( 

2918 srcpages[p.indirect_reference.idnum].page_number 

2919 ) 

2920 self.add_named_destination_array(dest["/Title"], arr) 

2921 except KeyError: 

2922 pass 

2923 elif dest["/Page"].indirect_reference.idnum in srcpages: 

2924 arr[NumberObject(0)] = srcpages[ 

2925 dest["/Page"].indirect_reference.idnum 

2926 ].indirect_reference 

2927 self.add_named_destination_array(dest["/Title"], arr) 

2928 

2929 def _add_articles_thread( 

2930 self, 

2931 thread: DictionaryObject, 

2932 pages: dict[int, PageObject], 

2933 reader: PdfReader, 

2934 ) -> IndirectObject: 

2935 """ 

2936 Clone the thread with only the applicable articles. 

2937 

2938 Args: 

2939 thread: Thread entry from the reader's array of threads 

2940 pages: Mapping of object numbers to page objects. 

2941 reader: The corresponding reader. 

2942 

2943 Returns: 

2944 The added thread as an indirect reference 

2945 

2946 """ 

2947 new_thread = thread.clone( 

2948 self, force_duplicate=True, ignore_fields=("/F",) 

2949 ) # use of clone to keep link between reader and writer 

2950 self.threads.append(new_thread.indirect_reference) 

2951 first_article = cast("DictionaryObject", thread["/F"]) 

2952 current_article: DictionaryObject | None = first_article 

2953 new_article: DictionaryObject | None = None 

2954 

2955 visited: set[int] = set() 

2956 while current_article is not None: 

2957 article_id = id(current_article) 

2958 if article_id in visited: 

2959 raise LimitReachedError("Detected cyclic article structure.") 

2960 visited.add(article_id) 

2961 

2962 page = self._get_cloned_page( 

2963 cast("PageObject", current_article["/P"]), pages, reader 

2964 ) 

2965 if page is not None: 

2966 if new_article is None: 

2967 new_article = cast( 

2968 "DictionaryObject", 

2969 self._add_object(DictionaryObject()).get_object(), 

2970 ) 

2971 new_first = new_article 

2972 new_thread[NameObject("/F")] = new_article.indirect_reference 

2973 else: 

2974 new_article2 = cast( 

2975 "DictionaryObject", 

2976 self._add_object( 

2977 DictionaryObject( 

2978 {NameObject("/V"): new_article.indirect_reference} 

2979 ) 

2980 ).get_object(), 

2981 ) 

2982 new_article[NameObject("/N")] = new_article2.indirect_reference 

2983 new_article = new_article2 

2984 new_article[NameObject("/P")] = page 

2985 new_article[NameObject("/T")] = new_thread.indirect_reference 

2986 new_article[NameObject("/R")] = current_article["/R"] 

2987 page_object = cast("PageObject", page.get_object()) 

2988 if "/B" not in page_object: 

2989 page_object[NameObject("/B")] = ArrayObject() 

2990 cast("ArrayObject", page_object["/B"]).append( 

2991 new_article.indirect_reference 

2992 ) 

2993 

2994 current_article = cast("DictionaryObject", current_article["/N"]) 

2995 if current_article == first_article: 

2996 new_article[NameObject("/N")] = new_first.indirect_reference # type: ignore[index] 

2997 new_first[NameObject("/V")] = new_article.indirect_reference # type: ignore[union-attr] 

2998 current_article = None 

2999 

3000 assert new_thread.indirect_reference is not None 

3001 return new_thread.indirect_reference 

3002 

3003 def add_filtered_articles( 

3004 self, 

3005 fltr: ( 

3006 Pattern[Any] | str 

3007 ), # thread entry from the reader's array of threads 

3008 pages: dict[int, PageObject], 

3009 reader: PdfReader, 

3010 ) -> None: 

3011 """ 

3012 Add articles matching the defined criteria. 

3013 

3014 Args: 

3015 fltr: 

3016 pages: 

3017 reader: 

3018 

3019 """ 

3020 if isinstance(fltr, str): 

3021 fltr = re.compile(fltr) 

3022 elif not isinstance(fltr, Pattern): 

3023 fltr = re.compile("") 

3024 for p in pages.values(): 

3025 pp = p.original_page 

3026 for a in pp.get("/B", ()): 

3027 a_obj = a.get_object() 

3028 if is_null_or_none(a_obj): 

3029 continue 

3030 thr = a_obj.get("/T") 

3031 if thr is None: 

3032 continue 

3033 thr = thr.get_object() 

3034 if thr.indirect_reference.idnum not in self._id_translated[ 

3035 id(reader) 

3036 ] and fltr.search((thr.get("/I", {})).get("/Title", "")): 

3037 self._add_articles_thread(thr, pages, reader) 

3038 

3039 def _get_cloned_page( 

3040 self, 

3041 page: IndirectObject | PageObject | NullObject | int | None, 

3042 pages: dict[int, PageObject], 

3043 reader: PdfReader, 

3044 ) -> IndirectObject | None: 

3045 if isinstance(page, NullObject): 

3046 return None 

3047 if isinstance(page, int): 

3048 # An explicit destination may reference the target page by its 

3049 # (zero-based) index in the source document rather than by an 

3050 # indirect reference; this is what `Link(target_page_index=...)` 

3051 # produces. Resolve the index through the reader's page list so it 

3052 # can be remapped like a regular page reference. A destination that 

3053 # points past the end of the source document is dropped. 

3054 try: 

3055 page = reader.pages[page].indirect_reference 

3056 except IndexError: 

3057 return None 

3058 if isinstance(page, DictionaryObject) and page.get("/Type", "") == "/Page": 

3059 _i = page.indirect_reference 

3060 elif isinstance(page, IndirectObject): 

3061 _i = page 

3062 try: 

3063 return pages[_i.idnum].indirect_reference # type: ignore[union-attr] 

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

3065 raise 

3066 except Exception: 

3067 return None 

3068 

3069 def _insert_filtered_annotations( 

3070 self, 

3071 *, 

3072 annots: IndirectObject | list[PdfObject] | None, 

3073 page: PageObject, 

3074 pages: dict[int, PageObject], 

3075 reader: PdfReader, 

3076 parent_fields: dict[int, DictionaryObject] | None = None, 

3077 ) -> list[Destination]: 

3078 outlist = ArrayObject() 

3079 if isinstance(annots, IndirectObject): 

3080 annots = cast("list[Any]", annots.get_object()) 

3081 if annots is None: 

3082 return outlist 

3083 if not isinstance(annots, list): 

3084 logger_warning( 

3085 "Expected list of annotations, got %(annots)s of type %(annots_type)s.", 

3086 source=__name__, 

3087 annots=annots, 

3088 annots_type=annots.__class__.__name__, 

3089 ) 

3090 return outlist 

3091 for an in annots: 

3092 ano = cast("DictionaryObject", an.get_object()) 

3093 if ( 

3094 ano.get("/Subtype") != "/Link" 

3095 or "/A" not in ano 

3096 or cast("DictionaryObject", ano["/A"])["/S"] != "/GoTo" # type: ignore[comparison-overlap] 

3097 or "/Dest" in ano 

3098 ): 

3099 if ( 

3100 parent_fields is not None 

3101 and ano.get("/Subtype") == "/Widget" 

3102 and isinstance(ano.get("/Parent"), IndirectObject) 

3103 ): 

3104 outlist.append(self._clone_widget_annotation(ano, parent_fields)) 

3105 elif "/Dest" not in ano: 

3106 outlist.append(self._add_object(ano.clone(self))) 

3107 else: 

3108 d = ano["/Dest"] 

3109 if isinstance(d, str): 

3110 # it is a named dest 

3111 if str(d) in self.get_named_dest_root(): 

3112 outlist.append(ano.clone(self).indirect_reference) 

3113 else: 

3114 if not isinstance(d, ArrayObject) or not d: 

3115 continue 

3116 p = self._get_cloned_page(d[0], pages, reader) 

3117 if p is not None: 

3118 anc = ano.clone(self, ignore_fields=("/Dest",)) 

3119 anc[NameObject("/Dest")] = ArrayObject([p, *d[1:]]) 

3120 outlist.append(self._add_object(anc)) 

3121 else: 

3122 d = cast("DictionaryObject", ano["/A"]).get("/D", NullObject()) 

3123 if is_null_or_none(d): 

3124 continue 

3125 if isinstance(d, str): 

3126 # it is a named dest 

3127 if str(d) in self.get_named_dest_root(): 

3128 outlist.append(ano.clone(self).indirect_reference) 

3129 else: 

3130 if not isinstance(d, ArrayObject) or not d: 

3131 continue 

3132 p = self._get_cloned_page(d[0], pages, reader) 

3133 if p is not None: 

3134 anc = ano.clone(self, ignore_fields=("/D",)) 

3135 cast("DictionaryObject", anc["/A"])[ 

3136 NameObject("/D") 

3137 ] = ArrayObject([p, *d[1:]]) 

3138 outlist.append(self._add_object(anc)) 

3139 return outlist 

3140 

3141 def _clone_widget_annotation( 

3142 self, annotation: DictionaryObject, parent_fields: dict[int, DictionaryObject] 

3143 ) -> IndirectObject: 

3144 """ 

3145 Clone a widget annotation and link it to its parent fields. 

3146 

3147 Cloning ``/Parent`` directly would also clone the ``/Kids`` of the 

3148 parent fields, and with them the widgets and pages of sibling fields 

3149 which are not part of the merge. Instead, the parent fields are cloned 

3150 without ``/Kids`` and collected in ``parent_fields``, so that their kids 

3151 can be set by :meth:`_set_cloned_kids` once all annotations are cloned. 

3152 """ 

3153 clone = annotation.clone(self, ignore_fields=(1, "/Parent")) 

3154 source, target = annotation, clone 

3155 while isinstance(source.get("/Parent"), IndirectObject): 

3156 parent_reference = cast(IndirectObject, source.get("/Parent")) 

3157 source_parent = parent_reference.get_object() 

3158 if not isinstance(source_parent, DictionaryObject): 

3159 break 

3160 parent = source_parent.clone(self, ignore_fields=(1, "/Kids", 1, "/Parent")) 

3161 target[NameObject("/Parent")] = parent.indirect_reference 

3162 if parent_reference.idnum in parent_fields: 

3163 # The ancestors have already been linked. 

3164 break 

3165 parent_fields[parent_reference.idnum] = source_parent 

3166 source, target = source_parent, parent 

3167 assert clone.indirect_reference is not None 

3168 return clone.indirect_reference 

3169 

3170 def _set_cloned_kids(self, parent_fields: dict[int, DictionaryObject], reader: PdfReader) -> None: 

3171 """Set the ``/Kids`` of the cloned parent fields to the cloned kids, in their original order.""" 

3172 translated = self._id_translated.get(id(reader), {}) 

3173 for idnum, source_parent in parent_fields.items(): 

3174 kids = source_parent.get("/Kids", ArrayObject()) 

3175 parent = cast(DictionaryObject, self.get_object(translated[idnum])) 

3176 parent[NameObject("/Kids")] = ArrayObject( 

3177 IndirectObject(translated[kid.idnum], 0, self) 

3178 for kid in cast(ArrayObject, kids) 

3179 if isinstance(kid, IndirectObject) and kid.idnum in translated 

3180 ) 

3181 

3182 def _get_filtered_outline( 

3183 self, 

3184 *, 

3185 node: Any, 

3186 pages: dict[int, PageObject], 

3187 reader: PdfReader, 

3188 visited: set[int] | None = None, 

3189 ) -> list[Destination]: 

3190 """ 

3191 Extract outline item entries that are part of the specified page set. 

3192 

3193 Returns: 

3194 A list of destination objects. 

3195 

3196 """ 

3197 if visited is None: 

3198 visited = set() 

3199 new_outline: list[Destination] = [] 

3200 if node is None: 

3201 return new_outline 

3202 node = node.get_object() 

3203 if is_null_or_none(node): 

3204 node = DictionaryObject() 

3205 if not isinstance(node, DictionaryObject): 

3206 logger_warning("Outline node is not a dictionary: %(node)s", source=__name__, node=node) 

3207 return new_outline 

3208 

3209 if node.get("/Type", "") == "/Outlines" or "/Title" not in node: 

3210 node_id = id(node) 

3211 if node_id in visited: 

3212 logger_warning("Detected cycle in outlines.", source=__name__) 

3213 return [] 

3214 visited.add(node_id) 

3215 

3216 node = node.get("/First", None) 

3217 if node is not None: 

3218 node = node.get_object() 

3219 new_outline += self._get_filtered_outline(node=node, pages=pages, reader=reader, visited=visited) 

3220 else: 

3221 cloned_page: IndirectObject | NullObject | None 

3222 while True: 

3223 node = node.get_object() 

3224 if not isinstance(node, DictionaryObject): 

3225 logger_warning("Outline node is not a dictionary: %(node)s", source=__name__, node=node) 

3226 break 

3227 node_id = id(node) 

3228 if node_id in visited: 

3229 logger_warning("Detected cycle in outlines.", source=__name__) 

3230 break 

3231 visited.add(node_id) 

3232 

3233 destination = cast("Destination", reader._build_outline_item(node)) 

3234 cloned_page = self._get_cloned_page(cast("PageObject", destination["/Page"]), pages, reader) 

3235 if cloned_page is None: 

3236 cloned_page = NullObject() 

3237 destination[NameObject("/Page")] = cloned_page 

3238 if "/First" in node: 

3239 destination._filtered_children = self._get_filtered_outline( 

3240 node=node["/First"], pages=pages, reader=reader, visited=visited 

3241 ) 

3242 else: 

3243 destination._filtered_children = [] 

3244 if ( 

3245 not isinstance(cloned_page, NullObject) 

3246 or len(destination._filtered_children) > 0 

3247 ): 

3248 new_outline.append(destination) 

3249 

3250 if "/Next" not in node: 

3251 break 

3252 node = node["/Next"] 

3253 return new_outline 

3254 

3255 def _clone_outline(self, dest: Destination) -> TreeObject: 

3256 n_ol = TreeObject() 

3257 self._add_object(n_ol) 

3258 n_ol[NameObject("/Title")] = TextStringObject(dest["/Title"]) 

3259 if not isinstance(dest["/Page"], NullObject): 

3260 if dest.node is not None and "/A" in dest.node: 

3261 n_ol[NameObject("/A")] = dest.node["/A"].clone(self) 

3262 else: 

3263 n_ol[NameObject("/Dest")] = dest.dest_array 

3264 # TODO: /SE 

3265 if dest.node is not None: 

3266 n_ol[NameObject("/F")] = NumberObject(dest.node.get("/F", 0)) 

3267 color = dest.node.get("/C", NullObject()).get_object() 

3268 if not isinstance(color, list): 

3269 color = [FloatObject(0.0), FloatObject(0.0), FloatObject(0.0)] 

3270 n_ol[NameObject("/C")] = ArrayObject(color) 

3271 return n_ol 

3272 

3273 def _insert_filtered_outline( 

3274 self, 

3275 outlines: list[Destination], 

3276 parent: TreeObject | IndirectObject, 

3277 before: TreeObject | IndirectObject | None = None, 

3278 ) -> None: 

3279 for dest in outlines: 

3280 # TODO: can be improved to keep A and SE entries (ignored for the moment) 

3281 # with np=self.add_outline_item_destination(dest,parent,before) 

3282 if dest.get("/Type", "") == "/Outlines" or "/Title" not in dest: 

3283 np = parent 

3284 else: 

3285 np = self._clone_outline(dest) 

3286 cast(TreeObject, parent.get_object()).insert_child(np, before, self) 

3287 self._insert_filtered_outline(dest._filtered_children, np, None) 

3288 

3289 def close(self) -> None: 

3290 """Implemented for API harmonization.""" 

3291 return 

3292 

3293 def find_outline_item( 

3294 self, 

3295 outline_item: IndirectObject | str, 

3296 root: OutlineType | None = None, 

3297 *, 

3298 visited: set[int] | None = None, 

3299 ) -> list[int] | None: 

3300 if root is None: 

3301 outline = self.get_outline_root() 

3302 else: 

3303 outline = cast("TreeObject", root) 

3304 if visited is None: 

3305 visited = set() 

3306 

3307 index = 0 

3308 while outline is not None: 

3309 if ( 

3310 outline.indirect_reference == outline_item 

3311 or outline.get("/Title", None) == outline_item 

3312 ): 

3313 return [index] 

3314 

3315 outline_id = id(outline) 

3316 if outline_id in visited: 

3317 raise LimitReachedError("Detected cyclic outline hierarchy.") 

3318 visited.add(outline_id) 

3319 

3320 if "/First" in outline: 

3321 result = self.find_outline_item( 

3322 outline_item=outline_item, 

3323 root=cast(OutlineType, outline["/First"]), 

3324 visited=visited, 

3325 ) 

3326 if result: 

3327 return ([index] if "/Title" in outline else []) + result 

3328 if "/Next" in outline: 

3329 index += 1 

3330 outline = cast(TreeObject, outline["/Next"]) 

3331 else: 

3332 return None 

3333 raise PyPdfError("This line is theoretically unreachable.") # pragma: no cover 

3334 

3335 def reset_translation( 

3336 self, reader: PdfReader | IndirectObject | None = None 

3337 ) -> None: 

3338 """ 

3339 Reset the translation table between reader and the writer object. 

3340 

3341 Late cloning will create new independent objects. 

3342 

3343 Args: 

3344 reader: PdfReader or IndirectObject referencing a PdfReader object. 

3345 if set to None or omitted, all tables will be reset. 

3346 

3347 """ 

3348 if reader is None: 

3349 self._id_translated = {} 

3350 elif isinstance(reader, PdfReader): 

3351 try: 

3352 del self._id_translated[id(reader)] 

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

3354 raise 

3355 except Exception: 

3356 pass 

3357 elif isinstance(reader, IndirectObject): 

3358 try: 

3359 del self._id_translated[id(reader.pdf)] 

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

3361 raise 

3362 except Exception: 

3363 pass 

3364 else: 

3365 raise TypeError(f"Invalid parameter {reader}") 

3366 

3367 def set_page_label( 

3368 self, 

3369 page_index_from: int, 

3370 page_index_to: int, 

3371 style: PageLabelStyle | None = None, 

3372 prefix: str | None = None, 

3373 start: int | None = 0, 

3374 ) -> None: 

3375 """ 

3376 Set a page label to a range of pages. 

3377 

3378 Page indexes must be given starting from 0. 

3379 Labels must have a style, a prefix or both. 

3380 If a range is not assigned any page label, a decimal label starting from 1 is applied. 

3381 

3382 Args: 

3383 page_index_from: page index of the beginning of the range starting from 0 

3384 page_index_to: page index of the beginning of the range starting from 0 

3385 style: The numbering style to be used for the numeric portion of each page label: 

3386 

3387 * ``/D`` Decimal Arabic numerals 

3388 * ``/R`` Uppercase Roman numerals 

3389 * ``/r`` Lowercase Roman numerals 

3390 * ``/A`` Uppercase letters (A to Z for the first 26 pages, 

3391 AA to ZZ for the next 26, and so on) 

3392 * ``/a`` Lowercase letters (a to z for the first 26 pages, 

3393 aa to zz for the next 26, and so on) 

3394 

3395 prefix: The label prefix for page labels in this range. 

3396 start: The value of the numeric portion for the first page label 

3397 in the range. 

3398 Subsequent pages are numbered sequentially from this value, 

3399 which must be greater than or equal to 1. 

3400 Default value: 1. 

3401 

3402 """ 

3403 if style is None and prefix is None: 

3404 raise ValueError("At least one of style and prefix must be given") 

3405 if style is not None and style not in tuple(PageLabelStyle): 

3406 raise ValueError( 

3407 f"style must be one of: {', '.join(PageLabelStyle)}, got {style!r}" 

3408 ) 

3409 if page_index_from < 0: 

3410 raise ValueError("page_index_from must be greater or equal than 0") 

3411 if page_index_to < page_index_from: 

3412 raise ValueError( 

3413 "page_index_to must be greater or equal than page_index_from" 

3414 ) 

3415 if page_index_to >= len(self.pages): 

3416 raise ValueError("page_index_to exceeds number of pages") 

3417 if start is not None and start != 0 and start < 1: 

3418 raise ValueError("If given, start must be greater or equal than one") 

3419 

3420 self._set_page_label(page_index_from, page_index_to, style, prefix, start) 

3421 

3422 def _set_page_label( 

3423 self, 

3424 page_index_from: int, 

3425 page_index_to: int, 

3426 style: PageLabelStyle | None = None, 

3427 prefix: str | None = None, 

3428 start: int | None = 0, 

3429 ) -> None: 

3430 """ 

3431 Set a page label to a range of pages. 

3432 

3433 Page indexes must be given starting from 0. 

3434 Labels must have a style, a prefix or both. 

3435 If a range is not assigned any page label a decimal label starting from 1 is applied. 

3436 

3437 Args: 

3438 page_index_from: page index of the beginning of the range starting from 0 

3439 page_index_to: page index of the beginning of the range starting from 0 

3440 style: The numbering style to be used for the numeric portion of each page label: 

3441 /D Decimal Arabic numerals 

3442 /R Uppercase Roman numerals 

3443 /r Lowercase Roman numerals 

3444 /A Uppercase letters (A to Z for the first 26 pages, 

3445 AA to ZZ for the next 26, and so on) 

3446 /a Lowercase letters (a to z for the first 26 pages, 

3447 aa to zz for the next 26, and so on) 

3448 prefix: The label prefix for page labels in this range. 

3449 start: The value of the numeric portion for the first page label 

3450 in the range. 

3451 Subsequent pages are numbered sequentially from this value, 

3452 which must be greater than or equal to 1. Default value: 1. 

3453 

3454 """ 

3455 default_page_label = DictionaryObject() 

3456 default_page_label[NameObject("/S")] = NameObject("/D") 

3457 

3458 new_page_label = DictionaryObject() 

3459 if style is not None: 

3460 new_page_label[NameObject("/S")] = NameObject(style) 

3461 if prefix is not None: 

3462 new_page_label[NameObject("/P")] = TextStringObject(prefix) 

3463 if start != 0: 

3464 new_page_label[NameObject("/St")] = NumberObject(start) 

3465 

3466 if NameObject(CatalogAttributes.PAGE_LABELS) not in self._root_object: 

3467 nums = ArrayObject() 

3468 nums_insert(NumberObject(0), default_page_label, nums) 

3469 page_labels = TreeObject() 

3470 page_labels[NameObject("/Nums")] = nums 

3471 self._root_object[NameObject(CatalogAttributes.PAGE_LABELS)] = page_labels 

3472 

3473 page_labels = cast( 

3474 TreeObject, self._root_object[NameObject(CatalogAttributes.PAGE_LABELS)] 

3475 ) 

3476 nums = cast(ArrayObject, page_labels[NameObject("/Nums")]) 

3477 

3478 nums_insert(NumberObject(page_index_from), new_page_label, nums) 

3479 nums_clear_range(NumberObject(page_index_from), page_index_to, nums) 

3480 next_label_pos, *_ = nums_next(NumberObject(page_index_from), nums) 

3481 if next_label_pos != page_index_to + 1 and page_index_to + 1 < len(self.pages): 

3482 nums_insert(NumberObject(page_index_to + 1), default_page_label, nums) 

3483 

3484 page_labels[NameObject("/Nums")] = nums 

3485 self._root_object[NameObject(CatalogAttributes.PAGE_LABELS)] = page_labels 

3486 

3487 def _repr_mimebundle_( 

3488 self, 

3489 include: Iterable[str] | None = None, 

3490 exclude: Iterable[str] | None = None, 

3491 ) -> dict[str, Any]: 

3492 """ 

3493 Integration into Jupyter Notebooks. 

3494 

3495 This method returns a dictionary that maps a mime-type to its 

3496 representation. 

3497 

3498 .. seealso:: 

3499 

3500 https://ipython.readthedocs.io/en/stable/config/integrating.html 

3501 """ 

3502 pdf_data = BytesIO() 

3503 self.write(pdf_data) 

3504 data = { 

3505 "application/pdf": pdf_data, 

3506 } 

3507 

3508 if include is not None: 

3509 # Filter representations based on include list 

3510 data = {k: v for k, v in data.items() if k in include} 

3511 

3512 if exclude is not None: 

3513 # Remove representations based on exclude list 

3514 data = {k: v for k, v in data.items() if k not in exclude} 

3515 

3516 return data 

3517 

3518 

3519def _pdf_objectify(obj: dict[str, Any] | str | float | list[Any]) -> PdfObject: 

3520 if isinstance(obj, PdfObject): 

3521 return obj 

3522 if isinstance(obj, dict): 

3523 to_add = DictionaryObject() 

3524 for key, value in obj.items(): 

3525 to_add[NameObject(key)] = _pdf_objectify(value) 

3526 return to_add 

3527 if isinstance(obj, str): 

3528 if obj.startswith("/"): 

3529 return NameObject(obj) 

3530 return TextStringObject(obj) 

3531 if isinstance(obj, (float, int)): 

3532 return FloatObject(obj) 

3533 if isinstance(obj, list): 

3534 return ArrayObject(_pdf_objectify(i) for i in obj) 

3535 raise NotImplementedError( 

3536 f"{type(obj)=} could not be cast to a PdfObject" 

3537 ) 

3538 

3539 

3540def _create_outline_item( 

3541 action_ref: IndirectObject | None, 

3542 title: str, 

3543 color: tuple[float, float, float] | str | None, 

3544 italic: bool, 

3545 bold: bool, 

3546) -> TreeObject: 

3547 outline_item = TreeObject() 

3548 if action_ref is not None: 

3549 outline_item[NameObject("/A")] = action_ref 

3550 outline_item.update( 

3551 { 

3552 NameObject("/Title"): create_string_object(title), 

3553 } 

3554 ) 

3555 if color: 

3556 if isinstance(color, str): 

3557 color = hex_to_rgb(color) 

3558 outline_item.update( 

3559 {NameObject("/C"): ArrayObject([FloatObject(c) for c in color])} 

3560 ) 

3561 if italic or bold: 

3562 format_flag = 0 

3563 if italic: 

3564 format_flag += OutlineFontFlag.italic 

3565 if bold: 

3566 format_flag += OutlineFontFlag.bold 

3567 outline_item.update({NameObject("/F"): NumberObject(format_flag)}) 

3568 return outline_item