Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/pypdf/_doc_common.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

773 statements  

1# Copyright (c) 2006, Mathieu Fenniak 

2# Copyright (c) 2007, Ashish Kulkarni <kulkarni.ashish@gmail.com> 

3# Copyright (c) 2024, Pubpub-ZZ 

4# 

5# All rights reserved. 

6# 

7# Redistribution and use in source and binary forms, with or without 

8# modification, are permitted provided that the following conditions are 

9# met: 

10# 

11# * Redistributions of source code must retain the above copyright notice, 

12# this list of conditions and the following disclaimer. 

13# * Redistributions in binary form must reproduce the above copyright notice, 

14# this list of conditions and the following disclaimer in the documentation 

15# and/or other materials provided with the distribution. 

16# * The name of the author may not be used to endorse or promote products 

17# derived from this software without specific prior written permission. 

18# 

19# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 

20# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 

21# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 

22# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 

23# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 

24# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 

25# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 

26# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 

27# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 

28# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 

29# POSSIBILITY OF SUCH DAMAGE. 

30 

31import struct 

32from abc import ABC, abstractmethod 

33from collections.abc import Iterable, Iterator, Mapping, Sequence 

34from datetime import datetime 

35from typing import ( 

36 Any, 

37 NamedTuple, 

38 cast, 

39) 

40 

41from ._configuration import get_configuration 

42from ._encryption import Encryption 

43from ._page import PageObject, _VirtualList 

44from ._page_labels import index2labels 

45from ._utils import ( 

46 _TraversalState, 

47 deprecation_no_replacement, 

48 logger_warning, 

49 parse_iso8824_date, 

50) 

51from .constants import CatalogAttributes as CA 

52from .constants import ( 

53 CheckboxRadioButtonAttributes, 

54 Core, 

55 GoToActionArguments, 

56 PagesAttributes, 

57 UserAccessPermissions, 

58) 

59from .constants import DocumentInformationAttributes as DI 

60from .constants import FieldDictionaryAttributes as FA 

61from .constants import PageAttributes as PG 

62from .errors import LimitReachedError, PdfReadError, PyPdfError 

63from .filters import _decompress_with_limit 

64from .generic import ( 

65 ArrayObject, 

66 BooleanObject, 

67 ByteStringObject, 

68 Destination, 

69 DictionaryObject, 

70 EncodedStreamObject, 

71 Field, 

72 Fit, 

73 FloatObject, 

74 IndirectObject, 

75 NameObject, 

76 NullObject, 

77 PdfObject, 

78 TextStringObject, 

79 TreeObject, 

80 ViewerPreferences, 

81 create_string_object, 

82 is_null_or_none, 

83) 

84from .generic._files import EmbeddedFile 

85from .types import OutlineType, PagemodeType 

86from .xmp import XmpInformation 

87 

88 

89def convert_to_int(d: bytes, size: int) -> int | tuple[Any, ...]: 

90 if size > 8: 

91 raise PdfReadError("Invalid size in convert_to_int") 

92 d = b"\x00\x00\x00\x00\x00\x00\x00\x00" + d 

93 d = d[-8:] 

94 return cast(int, struct.unpack(">Q", d)[0]) 

95 

96 

97# Attributes a page inherits from its ancestors in the page tree. 

98_INHERITABLE_PAGE_ATTRIBUTES = ( 

99 NameObject(PG.RESOURCES), 

100 NameObject(PG.MEDIABOX), 

101 NameObject(PG.CROPBOX), 

102 NameObject(PG.ROTATE), 

103) 

104 

105 

106class _PageTreeItem(NamedTuple): 

107 """A page tree node waiting to be flattened by :meth:`PdfDocCommon._flatten`.""" 

108 

109 node: DictionaryObject 

110 #: Inherited attributes. Shared read-only between the kids of one node. 

111 inherit: dict[str, Any] 

112 indirect_reference: IndirectObject | None 

113 depth: int 

114 

115 

116#: A ``/Pages`` node currently being walked: the node - carrying the attributes its 

117#: kids inherit - and the part of its ``/Kids`` which has not been reached yet. 

118_PageTreeFrame = tuple[_PageTreeItem, Iterator[PdfObject]] 

119 

120_UNSET = object() 

121 

122 

123class DocumentInformation(DictionaryObject): 

124 """ 

125 A class representing the basic document metadata provided in a PDF File. 

126 This class is accessible through 

127 :py:class:`PdfReader.metadata<pypdf.PdfReader.metadata>`. 

128 

129 All text properties of the document metadata have 

130 *two* properties, e.g. author and author_raw. The non-raw property will 

131 always return a ``TextStringObject``, making it ideal for a case where the 

132 metadata is being displayed. The raw property can sometimes return a 

133 ``ByteStringObject``, if pypdf was unable to decode the string's text 

134 encoding; this requires additional safety in the caller and therefore is not 

135 as commonly accessed. 

136 """ 

137 

138 def __init__(self) -> None: 

139 DictionaryObject.__init__(self) 

140 

141 def _get_text(self, key: str) -> str | None: 

142 retval = self.get(key, None) 

143 if isinstance(retval, TextStringObject): 

144 return retval 

145 if isinstance(retval, ByteStringObject): 

146 return str(retval) 

147 return None 

148 

149 @property 

150 def title(self) -> str | None: 

151 """ 

152 Read-only property accessing the document's title. 

153 

154 Returns a ``TextStringObject`` or ``None`` if the title is not 

155 specified. 

156 """ 

157 return ( 

158 self._get_text(DI.TITLE) or self.get(DI.TITLE).get_object() # type: ignore[union-attr] 

159 if self.get(DI.TITLE) 

160 else None 

161 ) 

162 

163 @property 

164 def title_raw(self) -> str | None: 

165 """The "raw" version of title; can return a ``ByteStringObject``.""" 

166 return self.get(DI.TITLE) 

167 

168 @property 

169 def author(self) -> str | None: 

170 """ 

171 Read-only property accessing the document's author. 

172 

173 Returns a ``TextStringObject`` or ``None`` if the author is not 

174 specified. 

175 """ 

176 return self._get_text(DI.AUTHOR) 

177 

178 @property 

179 def author_raw(self) -> str | None: 

180 """The "raw" version of author; can return a ``ByteStringObject``.""" 

181 return self.get(DI.AUTHOR) 

182 

183 @property 

184 def subject(self) -> str | None: 

185 """ 

186 Read-only property accessing the document's subject. 

187 

188 Returns a ``TextStringObject`` or ``None`` if the subject is not 

189 specified. 

190 """ 

191 return self._get_text(DI.SUBJECT) 

192 

193 @property 

194 def subject_raw(self) -> str | None: 

195 """The "raw" version of subject; can return a ``ByteStringObject``.""" 

196 return self.get(DI.SUBJECT) 

197 

198 @property 

199 def creator(self) -> str | None: 

200 """ 

201 Read-only property accessing the document's creator. 

202 

203 If the document was converted to PDF from another format, this is the 

204 name of the application (e.g. OpenOffice) that created the original 

205 document from which it was converted. Returns a ``TextStringObject`` or 

206 ``None`` if the creator is not specified. 

207 """ 

208 return self._get_text(DI.CREATOR) 

209 

210 @property 

211 def creator_raw(self) -> str | None: 

212 """The "raw" version of creator; can return a ``ByteStringObject``.""" 

213 return self.get(DI.CREATOR) 

214 

215 @property 

216 def producer(self) -> str | None: 

217 """ 

218 Read-only property accessing the document's producer. 

219 

220 If the document was converted to PDF from another format, this is the 

221 name of the application (for example, macOS Quartz) that converted it to 

222 PDF. Returns a ``TextStringObject`` or ``None`` if the producer is not 

223 specified. 

224 """ 

225 return self._get_text(DI.PRODUCER) 

226 

227 @property 

228 def producer_raw(self) -> str | None: 

229 """The "raw" version of producer; can return a ``ByteStringObject``.""" 

230 return self.get(DI.PRODUCER) 

231 

232 @property 

233 def creation_date(self) -> datetime | None: 

234 """Read-only property accessing the document's creation date.""" 

235 return parse_iso8824_date(self._get_text(DI.CREATION_DATE)) 

236 

237 @property 

238 def creation_date_raw(self) -> str | None: 

239 """ 

240 The "raw" version of creation date; can return a ``ByteStringObject``. 

241 

242 Typically in the format ``D:YYYYMMDDhhmmss[+Z-]hh'mm`` where the suffix 

243 is the offset from UTC. 

244 """ 

245 return self.get(DI.CREATION_DATE) 

246 

247 @property 

248 def modification_date(self) -> datetime | None: 

249 """ 

250 Read-only property accessing the document's modification date. 

251 

252 The date and time the document was most recently modified. 

253 """ 

254 return parse_iso8824_date(self._get_text(DI.MOD_DATE)) 

255 

256 @property 

257 def modification_date_raw(self) -> str | None: 

258 """ 

259 The "raw" version of modification date; can return a 

260 ``ByteStringObject``. 

261 

262 Typically, in the format ``D:YYYYMMDDhhmmss[+Z-]hh'mm`` where the suffix 

263 is the offset from UTC. 

264 """ 

265 return self.get(DI.MOD_DATE) 

266 

267 @property 

268 def keywords(self) -> str | None: 

269 """ 

270 Read-only property accessing the document's keywords. 

271 

272 Returns a ``TextStringObject`` or ``None`` if keywords are not 

273 specified. 

274 """ 

275 return self._get_text(DI.KEYWORDS) 

276 

277 @property 

278 def keywords_raw(self) -> str | None: 

279 """The "raw" version of keywords; can return a ``ByteStringObject``.""" 

280 return self.get(DI.KEYWORDS) 

281 

282 

283class PdfDocCommon(ABC): 

284 """ 

285 Common functions from PdfWriter and PdfReader objects. 

286 

287 This root class is strongly abstracted. 

288 """ 

289 

290 strict: bool = False # default 

291 

292 flattened_pages: list[PageObject] | None = None 

293 

294 _encryption: Encryption | None = None 

295 

296 _readonly: bool = False 

297 

298 @property 

299 @abstractmethod 

300 def root_object(self) -> DictionaryObject: 

301 ... # pragma: no cover 

302 

303 @property 

304 @abstractmethod 

305 def pdf_header(self) -> str: 

306 ... # pragma: no cover 

307 

308 @abstractmethod 

309 def get_object( 

310 self, indirect_reference: int | IndirectObject 

311 ) -> PdfObject | None: 

312 ... # pragma: no cover 

313 

314 @abstractmethod 

315 def _replace_object(self, indirect_reference: IndirectObject, obj: PdfObject) -> PdfObject: 

316 ... # pragma: no cover 

317 

318 @property 

319 @abstractmethod 

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

321 ... # pragma: no cover 

322 

323 @property 

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

325 """ 

326 Retrieve the PDF file's document information dictionary, if it exists. 

327 

328 Note that some PDF files use metadata streams instead of document 

329 information dictionaries, and these metadata streams will not be 

330 accessed by this function. 

331 """ 

332 retval = DocumentInformation() 

333 if self._info is None: 

334 return None 

335 retval.update(self._info) 

336 return retval 

337 

338 @property 

339 @abstractmethod 

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

341 ... # pragma: no cover 

342 

343 @property 

344 def viewer_preferences(self) -> ViewerPreferences | None: 

345 """Returns the existing ViewerPreferences as an overloaded dictionary.""" 

346 o = self.root_object.get(CA.VIEWER_PREFERENCES, None) 

347 if o is None: 

348 return None 

349 o = o.get_object() 

350 if not isinstance(o, DictionaryObject): 

351 logger_warning( 

352 "Viewer preferences are not a dictionary: %(preferences)s", 

353 source=__name__, 

354 preferences=o, 

355 ) 

356 return None 

357 if not isinstance(o, ViewerPreferences): 

358 o = ViewerPreferences(o) 

359 if hasattr(o, "indirect_reference") and o.indirect_reference is not None: 

360 self._replace_object(o.indirect_reference, o) 

361 else: 

362 self.root_object[NameObject(CA.VIEWER_PREFERENCES)] = o 

363 return o 

364 

365 def get_num_pages(self) -> int: 

366 """ 

367 Calculate the number of pages in this PDF file. 

368 

369 Returns: 

370 The number of pages of the parsed PDF file. 

371 

372 Raises: 

373 PdfReadError: If restrictions prevent this action. 

374 

375 """ 

376 # The page tree cannot be walked while the document is still encrypted; 

377 # the PDF file's page count is used in this case. Once the document has 

378 # been decrypted (or if it is not encrypted at all), the flattened page 

379 # tree is used instead, as the /Count value might be wrong. 

380 encryption = self._encryption 

381 if self.is_encrypted and (encryption is None or not encryption.is_decrypted()): 

382 return self.root_object["/Pages"]["/Count"] # type: ignore[no-any-return, index] 

383 if self.flattened_pages is None: 

384 self._flatten(self._readonly) 

385 assert self.flattened_pages is not None 

386 return len(self.flattened_pages) 

387 

388 def get_page(self, page_number: int) -> PageObject: 

389 """ 

390 Retrieve a page by number from this PDF file. 

391 Most of the time ``.pages[page_number]`` is preferred. 

392 

393 Args: 

394 page_number: The page number to retrieve 

395 (pages begin at zero) 

396 

397 Returns: 

398 A :class:`PageObject<pypdf._page.PageObject>` instance. 

399 

400 """ 

401 if self.flattened_pages is None: 

402 self._flatten(self._readonly) 

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

404 return self.flattened_pages[page_number] 

405 

406 def _get_page_in_node( 

407 self, 

408 page_number: int, 

409 ) -> tuple[DictionaryObject, int]: 

410 """ 

411 Retrieve the node and position within the /Kids containing the page. 

412 If page_number is greater than the number of pages, it returns the top node, -1. 

413 """ 

414 top = cast(DictionaryObject, self.root_object["/Pages"]) 

415 visited: set[int] = set() 

416 

417 def recursive_call( 

418 _node: DictionaryObject, mi: int 

419 ) -> tuple[PdfObject | None, int]: 

420 _node_id = id(_node) 

421 if _node_id in visited: 

422 raise LimitReachedError("Detected cycle in /Pages hierarchy when retrieving page.") 

423 visited.add(_node_id) 

424 ma = cast(int, _node.get("/Count", 1)) # default 1 for /Page types 

425 if _node.get("/Type") == "/Page": 

426 if page_number == mi: 

427 return _node, -1 

428 return None, mi + 1 

429 if (page_number - mi) >= ma: # not in nodes below 

430 if _node == top: 

431 return top, -1 

432 return None, mi + ma 

433 for _idx, kid in enumerate(cast(ArrayObject, _node["/Kids"])): 

434 kid = cast(DictionaryObject, kid.get_object()) 

435 n, i = recursive_call(kid, mi) 

436 if n is not None: # page has just been found ... 

437 if i < 0: # ... just below! 

438 return _node, _idx 

439 # ... at lower levels 

440 return n, i 

441 mi = i 

442 raise PyPdfError("Unexpectedly cannot find the node.") 

443 

444 node, idx = recursive_call(top, 0) 

445 assert isinstance(node, DictionaryObject), "mypy" 

446 return node, idx 

447 

448 @property 

449 def named_destinations(self) -> dict[str, Destination]: 

450 """A read-only dictionary which maps names to destinations.""" 

451 return self._get_named_destinations() 

452 

453 def get_named_dest_root(self) -> ArrayObject: 

454 named_dest = ArrayObject() 

455 if CA.NAMES in self.root_object and isinstance( 

456 self.root_object[CA.NAMES], DictionaryObject 

457 ): 

458 names = cast(DictionaryObject, self.root_object[CA.NAMES]) 

459 if CA.DESTS in names and isinstance(names[CA.DESTS], DictionaryObject): 

460 # §3.6.3 Name Dictionary (PDF spec 1.7) 

461 dests = cast(DictionaryObject, names[CA.DESTS]) 

462 if CA.NAMES in dests: 

463 # §7.9.6, entries in a name tree node dictionary 

464 named_dest = cast(ArrayObject, dests[CA.NAMES]) 

465 else: 

466 named_dest = ArrayObject() 

467 dests[NameObject(CA.NAMES)] = named_dest 

468 elif hasattr(self, "_add_object"): 

469 dests = DictionaryObject() 

470 dests_ref = self._add_object(dests) 

471 names[NameObject(CA.DESTS)] = dests_ref 

472 dests[NameObject(CA.NAMES)] = named_dest 

473 

474 elif hasattr(self, "_add_object"): 

475 names = DictionaryObject() 

476 names_ref = self._add_object(names) 

477 self.root_object[NameObject(CA.NAMES)] = names_ref 

478 dests = DictionaryObject() 

479 dests_ref = self._add_object(dests) 

480 names[NameObject(CA.DESTS)] = dests_ref 

481 dests[NameObject(CA.NAMES)] = named_dest 

482 

483 return named_dest 

484 

485 ## common 

486 def _get_named_destinations( 

487 self, 

488 *, 

489 tree: DictionaryObject | None = None, 

490 retval: dict[str, Destination] | None = None, 

491 visited: set[int] | None = None, 

492 ) -> dict[str, Destination]: 

493 """ 

494 Retrieve the named destinations present in the document. 

495 

496 Args: 

497 tree: The current tree. 

498 retval: The previously retrieved destinations for nested calls. 

499 visited: Already known/visited objects. 

500 

501 Returns: 

502 A dictionary which maps names to destinations. 

503 

504 """ 

505 if visited is None: 

506 visited = set() 

507 if retval is None: 

508 retval = {} 

509 catalog = self.root_object 

510 

511 # get the name tree 

512 candidate: PdfObject | None = None 

513 if CA.DESTS in catalog: 

514 candidate = catalog[CA.DESTS].get_object() 

515 elif CA.NAMES in catalog: 

516 names = catalog[CA.NAMES].get_object() 

517 if isinstance(names, DictionaryObject) and CA.DESTS in names: 

518 candidate = names[CA.DESTS].get_object() 

519 if candidate is not None and not isinstance(candidate, DictionaryObject): 

520 logger_warning( 

521 "Destination tree is not a dictionary: %(tree)s", 

522 source=__name__, 

523 tree=candidate, 

524 ) 

525 return retval 

526 if candidate is not None: 

527 tree = candidate 

528 

529 if is_null_or_none(tree): 

530 return retval 

531 assert tree is not None, "mypy" 

532 

533 tree_id = id(tree) 

534 if tree_id in visited: 

535 logger_warning("Detected cycle in destination tree.", source=__name__) 

536 return retval 

537 visited.add(tree_id) 

538 

539 if PagesAttributes.KIDS in tree: 

540 kids = tree[PagesAttributes.KIDS].get_object() 

541 if not isinstance(kids, ArrayObject): 

542 logger_warning( 

543 "Destination tree kids are not an array: %(kids)s", 

544 source=__name__, 

545 kids=kids, 

546 ) 

547 return retval 

548 # recurse down the tree 

549 for kid in kids: 

550 self._get_named_destinations(tree=kid.get_object(), retval=retval, visited=visited) 

551 # §7.9.6, entries in a name tree node dictionary 

552 elif CA.NAMES in tree: # /Kids and /Names are exclusives (§7.9.6) 

553 names = tree[CA.NAMES].get_object() 

554 if not isinstance(names, ArrayObject): 

555 logger_warning( 

556 "Destination tree names are not an array: %(names)s", 

557 source=__name__, 

558 names=names, 

559 ) 

560 return retval 

561 i = 0 

562 while i < len(names): 

563 key = names[i].get_object() 

564 i += 1 

565 if not isinstance(key, (bytes, str)): 

566 continue 

567 try: 

568 value = names[i].get_object() 

569 except IndexError: 

570 break 

571 i += 1 

572 if isinstance(value, DictionaryObject): 

573 if "/D" in value: 

574 value = value["/D"] 

575 else: 

576 continue 

577 dest = self._build_destination(key, value) 

578 if dest is not None: 

579 retval[cast(str, dest["/Title"])] = dest 

580 # Remain backwards-compatible. 

581 retval[str(key)] = dest 

582 else: # case where /Dests is in the document's catalog dictionary (PDF 1.7 specs, §2 about PDF 1.1) 

583 for k__, v__ in tree.items(): 

584 val = v__.get_object() 

585 if isinstance(val, DictionaryObject): 

586 if "/D" in val: 

587 val = val["/D"].get_object() 

588 else: 

589 continue 

590 dest = self._build_destination(k__, val) 

591 if dest is not None: 

592 retval[k__] = dest 

593 return retval 

594 

595 # A select group of relevant field attributes. For the complete list, 

596 # see §12.3.2 of the PDF 1.7 or PDF 2.0 specification. 

597 

598 def get_fields( 

599 self, 

600 tree: DictionaryObject | None = None, 

601 retval: dict[Any, Any] | None = None, 

602 fileobj: Any | None = None, 

603 stack: Any = _UNSET, 

604 *, 

605 _visited: set[int] | None = None, 

606 _depth: int = 0, 

607 _traversal_state: _TraversalState | None = None, 

608 ) -> dict[str, Any] | None: 

609 """ 

610 Extract field data if this PDF contains interactive form fields. 

611 

612 The *tree*, *retval*, *visited*, *depth* parameters are for internal use. 

613 

614 Args: 

615 tree: Current object to parse. 

616 retval: In-progress list of fields. 

617 fileobj: A file object (usually a text file) to write 

618 a report to on all interactive form fields found. 

619 stack: The stack to use. Deprecated. 

620 _visited: Set of already visited IDs. Callers should usually omit this. 

621 _depth: The current field depth. 

622 _traversal_state: The current traversal state. 

623 

624 Returns: 

625 A dictionary where each key is a field name, and each 

626 value is a :class:`Field<pypdf.generic.Field>` object. By 

627 default, the mapping name is used for keys. 

628 ``None`` if form data could not be located. 

629 

630 """ 

631 if stack is not _UNSET: 

632 deprecation_no_replacement(name="stack", removed_in="7.0.0") 

633 

634 configuration = get_configuration() 

635 if _depth >= configuration.form_fields_maximum_depth: 

636 raise LimitReachedError("Reached maximum allowed form field depth.") 

637 if _traversal_state is None: 

638 _traversal_state = _TraversalState() 

639 

640 def _check_field_limit(_increment: int) -> None: 

641 _traversal_state.entry_count += _increment 

642 if _traversal_state.entry_count > configuration.form_fields_maximum_entries: 

643 raise LimitReachedError("Exceeded maximum number of fields allowed.") 

644 

645 field_attributes = FA.attributes_dict() 

646 field_attributes.update(CheckboxRadioButtonAttributes.attributes_dict()) 

647 if retval is None: 

648 retval = {} 

649 catalog = self.root_object 

650 _visited = set() 

651 # get the AcroForm tree 

652 if CA.ACRO_FORM in catalog: 

653 entry = catalog[CA.ACRO_FORM] 

654 acro_form = None if entry is None else entry.get_object() 

655 if acro_form is not None and not isinstance( 

656 acro_form, DictionaryObject 

657 ): 

658 logger_warning( 

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

660 source=__name__, 

661 acro_form=acro_form, 

662 ) 

663 return None 

664 tree = acro_form 

665 else: 

666 return None 

667 if tree is None: 

668 return retval 

669 assert _visited is not None 

670 if "/Fields" in tree: 

671 fields = tree["/Fields"].get_object() 

672 if not isinstance(fields, ArrayObject): 

673 logger_warning( 

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

675 source=__name__, 

676 fields=fields, 

677 ) 

678 return retval 

679 _check_field_limit(len(fields)) 

680 for f in fields: 

681 field = f.get_object() 

682 self._build_field( 

683 field=field, retval=retval, fileobj=fileobj, field_attributes=field_attributes, 

684 visited=_visited, depth=_depth, traversal_state=_traversal_state, 

685 ) 

686 elif any(attr in tree for attr in field_attributes): 

687 # Tree is a field 

688 _check_field_limit(1) 

689 self._build_field( 

690 field=tree, retval=retval, fileobj=fileobj, field_attributes=field_attributes, 

691 visited=_visited, depth=_depth, traversal_state=_traversal_state, 

692 ) 

693 return retval 

694 

695 def _get_qualified_field_name( 

696 self, 

697 *, 

698 parent: DictionaryObject, 

699 visited: set[int] | None = None 

700 ) -> str: 

701 if visited is None: 

702 visited = set() 

703 parent_id = id(parent) 

704 if parent_id in visited: 

705 raise LimitReachedError("Detected cycle in /Parent hierarchy when retrieving qualified field name.") 

706 visited.add(parent_id) 

707 

708 if "/TM" in parent: 

709 return cast(str, parent["/TM"]) 

710 if "/Parent" in parent: 

711 return ( 

712 self._get_qualified_field_name( 

713 parent=cast(DictionaryObject, parent["/Parent"]), 

714 visited=visited, 

715 ) 

716 + "." 

717 + cast(str, parent.get("/T", "")) 

718 ) 

719 return cast(str, parent.get("/T", "")) 

720 

721 @staticmethod 

722 def _normal_appearance(appearance: Any) -> DictionaryObject: 

723 """Return the /N normal-appearance sub-dictionary of an /AP entry.""" 

724 appearance = appearance.get_object() 

725 if not isinstance(appearance, DictionaryObject): 

726 raise PdfReadError(f"Expected appearance dictionary, got {appearance!r}") 

727 normal = appearance.get("/N") 

728 if normal is not None: 

729 normal = normal.get_object() 

730 if not isinstance(normal, DictionaryObject): 

731 raise PdfReadError(f"Expected /N appearance dictionary, got {normal!r}") 

732 return normal 

733 

734 def _build_field( 

735 self, 

736 *, 

737 field: TreeObject | DictionaryObject, 

738 retval: dict[Any, Any], 

739 fileobj: Any, 

740 field_attributes: Any, 

741 visited: set[int], 

742 depth: int, 

743 traversal_state: _TraversalState, 

744 ) -> None: 

745 if not isinstance(field, DictionaryObject): 

746 logger_warning( 

747 "Form field is not a dictionary: %(field)s", 

748 source=__name__, 

749 field=field, 

750 ) 

751 return 

752 if all(attr not in field for attr in ("/T", "/TM")): 

753 return 

754 key = self._get_qualified_field_name(parent=field) 

755 if fileobj: 

756 self._write_field(fileobj, field, field_attributes) 

757 fileobj.write("\n") 

758 retval[key] = Field(field) 

759 obj = retval[key].indirect_reference.get_object() # to get the full object 

760 if obj.get(FA.FT, "") == "/Ch" and obj.get(NameObject(FA.Opt)): 

761 retval[key][NameObject("/_States_")] = obj[NameObject(FA.Opt)] 

762 if obj.get(FA.FT, "") == "/Btn" and "/AP" in obj: 

763 # Checkbox 

764 normal = self._normal_appearance(obj["/AP"]) 

765 retval[key][NameObject("/_States_")] = ArrayObject(list(normal.keys())) 

766 if "/Off" not in retval[key]["/_States_"]: 

767 retval[key][NameObject("/_States_")].append(NameObject("/Off")) 

768 elif obj.get(FA.FT, "") == "/Btn" and obj.get(FA.Ff, 0) & FA.FfBits.Radio != 0: 

769 states: list[str] = [] 

770 retval[key][NameObject("/_States_")] = ArrayObject(states) 

771 for k in obj.get(FA.Kids, {}): 

772 k = k.get_object() 

773 if "/AP" not in k: 

774 raise PdfReadError(f"Button field kid missing /AP: {k!r}") 

775 normal = self._normal_appearance(k["/AP"]) 

776 for s in list(normal.keys()): 

777 if s not in states: 

778 states.append(s) 

779 retval[key][NameObject("/_States_")] = ArrayObject(states) 

780 if ( 

781 obj.get(FA.Ff, 0) & FA.FfBits.NoToggleToOff != 0 

782 and "/Off" in retval[key]["/_States_"] 

783 ): 

784 del retval[key]["/_States_"][retval[key]["/_States_"].index("/Off")] 

785 # at last for order 

786 self._check_kids( 

787 tree=field, retval=retval, fileobj=fileobj, visited=visited, depth=depth, traversal_state=traversal_state 

788 ) 

789 

790 def _check_kids( 

791 self, 

792 *, 

793 tree: TreeObject | DictionaryObject, 

794 retval: Any, 

795 fileobj: Any, 

796 visited: set[int], 

797 depth: int, 

798 traversal_state: _TraversalState, 

799 ) -> None: 

800 tree_id = id(tree) 

801 if tree_id in visited: 

802 logger_warning( 

803 "%(field_name)s already parsed", 

804 source=__name__, 

805 field_name=self._get_qualified_field_name(parent=tree), 

806 ) 

807 return 

808 visited.add(tree_id) 

809 if PagesAttributes.KIDS in tree: 

810 # recurse down the tree 

811 for kid in tree[PagesAttributes.KIDS]: # type: ignore[attr-defined] 

812 kid = kid.get_object() 

813 self.get_fields( 

814 tree=kid, retval=retval, fileobj=fileobj, 

815 _visited=visited, _depth=depth + 1, _traversal_state=traversal_state 

816 ) 

817 

818 def _write_field(self, fileobj: Any, field: Any, field_attributes: Any) -> None: 

819 field_attributes_tuple = FA.attributes() 

820 field_attributes_tuple = ( 

821 field_attributes_tuple + CheckboxRadioButtonAttributes.attributes() 

822 ) 

823 

824 for attr in field_attributes_tuple: 

825 if attr in ( 

826 FA.Kids, 

827 FA.AA, 

828 ): 

829 continue 

830 attr_name = field_attributes[attr] 

831 try: 

832 if attr == FA.FT: 

833 # Make the field type value clearer 

834 types = { 

835 "/Btn": "Button", 

836 "/Tx": "Text", 

837 "/Ch": "Choice", 

838 "/Sig": "Signature", 

839 } 

840 if field[attr] in types: 

841 fileobj.write(f"{attr_name}: {types[field[attr]]}\n") 

842 elif attr == FA.Parent: 

843 # Let's just write the name of the parent 

844 try: 

845 name = field[attr][FA.TM] 

846 except KeyError: 

847 name = field[attr][FA.T] 

848 fileobj.write(f"{attr_name}: {name}\n") 

849 else: 

850 fileobj.write(f"{attr_name}: {field[attr]}\n") 

851 except KeyError: 

852 # Field attribute is N/A or unknown, so don't write anything 

853 pass 

854 

855 def get_form_text_fields(self, full_qualified_name: bool = False) -> dict[str, Any]: 

856 """ 

857 Retrieve form fields from the document with textual data. 

858 

859 Args: 

860 full_qualified_name: to get full name 

861 

862 Returns: 

863 A dictionary. The key is the name of the form field, 

864 the value is the content of the field. 

865 

866 If the document contains multiple form fields with the same name, the 

867 second and following will get the suffix .2, .3, ... 

868 

869 """ 

870 

871 def indexed_key(k: str, fields: dict[Any, Any]) -> str: 

872 if k not in fields: 

873 return k 

874 return ( 

875 k 

876 + "." 

877 + str(sum(1 for kk in fields if kk.startswith(k + ".")) + 2) 

878 ) 

879 

880 # Retrieve document form fields 

881 form_fields = self.get_fields() 

882 if form_fields is None: 

883 return {} 

884 ff = {} 

885 for field, value in form_fields.items(): 

886 if value.get("/FT") == "/Tx": 

887 if full_qualified_name: 

888 ff[field] = value.get("/V") 

889 else: 

890 ff[indexed_key(cast(str, value.get("/T", field)), ff)] = value.get("/V") 

891 return ff 

892 

893 def get_pages_showing_field( 

894 self, field: Field | PdfObject | IndirectObject 

895 ) -> list[PageObject]: 

896 """ 

897 Provides list of pages where the field is called. 

898 

899 Args: 

900 field: Field Object, PdfObject or IndirectObject referencing a Field 

901 

902 Returns: 

903 List of pages: 

904 - Empty list: 

905 The field has no widgets attached 

906 (either hidden field or ancestor field). 

907 - Single page list: 

908 Page where the widget is present 

909 (most common). 

910 - Multi-page list: 

911 Field with multiple kids widgets 

912 (example: radio buttons, field repeated on multiple pages). 

913 

914 """ 

915 try: 

916 # to cope with all types 

917 field = cast(DictionaryObject, field.indirect_reference.get_object()) # type: ignore[union-attr] 

918 except Exception as exc: 

919 raise ValueError("Field type is invalid") from exc 

920 if is_null_or_none(field.get_inherited(key="/FT", default=None)): 

921 raise ValueError("Field is not valid") 

922 ret = [] 

923 if field.get("/Subtype", "") == "/Widget": 

924 if "/P" in field: 

925 ret = [field["/P"].get_object()] 

926 else: 

927 ret = [ 

928 p 

929 for p in self.pages 

930 if field.indirect_reference in p.get("/Annots", "") 

931 ] 

932 else: 

933 kids = field.get("/Kids", ()) 

934 for k in kids: 

935 k = k.get_object() 

936 if (k.get("/Subtype", "") == "/Widget") and ("/T" not in k): 

937 # Kid that is just a widget, not a field: 

938 if "/P" in k: 

939 ret += [k["/P"].get_object()] 

940 else: 

941 ret += [ 

942 p 

943 for p in self.pages 

944 if k.indirect_reference in p.get("/Annots", "") 

945 ] 

946 return [ 

947 x 

948 if isinstance(x, PageObject) 

949 else (self.pages[self._get_page_number_by_indirect(x.indirect_reference)]) # type: ignore[index, union-attr] 

950 for x in ret 

951 ] 

952 

953 @property 

954 def open_destination( 

955 self, 

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

957 """ 

958 Property to access the opening destination (``/OpenAction`` entry in 

959 the PDF catalog). It returns ``None`` if the entry does not exist 

960 or is not set. 

961 

962 Raises: 

963 Exception: If a destination is invalid. 

964 

965 """ 

966 if "/OpenAction" not in self.root_object: 

967 return None 

968 oa: Any = self.root_object["/OpenAction"] 

969 if isinstance(oa, bytes): # pragma: no cover 

970 oa = oa.decode() 

971 if isinstance(oa, str): 

972 return create_string_object(oa) 

973 if isinstance(oa, ArrayObject): 

974 try: 

975 page, typ, *array = oa 

976 fit = Fit(typ, tuple(array)) 

977 return Destination("OpenAction", page, fit) 

978 except Exception as exc: 

979 raise Exception(f"Invalid Destination {oa}: {exc}") from exc 

980 else: 

981 return None 

982 

983 @open_destination.setter 

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

985 raise NotImplementedError("No setter for open_destination") 

986 

987 @property 

988 def outline(self) -> OutlineType: 

989 """ 

990 Read-only property for the outline present in the document 

991 (i.e., a collection of 'outline items' which are also known as 

992 'bookmarks'). 

993 """ 

994 return self._get_outline() 

995 

996 def _get_outline( 

997 self, 

998 *, 

999 node: DictionaryObject | None = None, 

1000 outline: Any | None = None, 

1001 visited: set[int] | None = None, 

1002 depth: int = 0, 

1003 traversal_state: _TraversalState | None = None 

1004 ) -> OutlineType: 

1005 if traversal_state is None: 

1006 traversal_state = _TraversalState() 

1007 

1008 if outline is None: 

1009 outline = [] 

1010 catalog = self.root_object 

1011 

1012 # get the outline dictionary and named destinations 

1013 if Core.OUTLINES in catalog: 

1014 lines = catalog[Core.OUTLINES] 

1015 

1016 # A reference to an object which is missing or free in the xref table 

1017 # resolves to None. 

1018 if is_null_or_none(lines): 

1019 return outline 

1020 

1021 if not isinstance(lines, DictionaryObject): 

1022 logger_warning( 

1023 "Outlines are not a dictionary: %(lines)s", 

1024 source=__name__, 

1025 lines=lines, 

1026 ) 

1027 return outline 

1028 

1029 # §12.3.3 Document outline, entries in the outline dictionary 

1030 if "/First" in lines: 

1031 node = cast(DictionaryObject, lines["/First"]) 

1032 self._named_destinations = self._get_named_destinations() 

1033 

1034 if node is None: 

1035 return outline 

1036 

1037 configuration = get_configuration() 

1038 if depth > configuration.outline_maximum_depth: 

1039 raise LimitReachedError(f"Maximum outline depth reached: {depth} > {configuration.outline_maximum_depth}.") 

1040 

1041 # see if there are any more outline items 

1042 if visited is None: 

1043 visited = set() 

1044 while True: 

1045 node_id = id(node) 

1046 if node_id in visited: 

1047 logger_warning("Detected cycle in outline structure for %(node)s", source=__name__, node=node) 

1048 break 

1049 visited.add(node_id) 

1050 traversal_state.entry_count += 1 

1051 if traversal_state.entry_count > configuration.outline_maximum_entries: 

1052 raise LimitReachedError( 

1053 f"Maximum outline entry limit reached: " 

1054 f"{traversal_state.entry_count} > {configuration.outline_maximum_entries}." 

1055 ) 

1056 

1057 if not isinstance(node, DictionaryObject): 

1058 logger_warning( 

1059 "Outline node is not a dictionary: %(node)s", 

1060 source=__name__, 

1061 node=node, 

1062 ) 

1063 break 

1064 

1065 outline_obj = self._build_outline_item(node) 

1066 if outline_obj: 

1067 outline.append(outline_obj) 

1068 

1069 # check for sub-outline 

1070 if "/First" in node: 

1071 sub_outline: list[Any] = [] 

1072 # Pass a copy to allow multiple outer entries to reference the same inner one. 

1073 inner_visited = visited.copy() 

1074 self._get_outline( 

1075 node=cast(DictionaryObject, node["/First"]), 

1076 outline=sub_outline, 

1077 visited=inner_visited, 

1078 depth=depth + 1, 

1079 traversal_state=traversal_state, 

1080 ) 

1081 if sub_outline: 

1082 outline.append(sub_outline) 

1083 

1084 if "/Next" not in node: 

1085 break 

1086 node = cast(DictionaryObject, node["/Next"]) 

1087 

1088 return outline 

1089 

1090 @property 

1091 def threads(self) -> ArrayObject | None: 

1092 """ 

1093 Read-only property for the list of threads. 

1094 

1095 See §12.4.3 from the PDF 1.7 or 2.0 specification. 

1096 

1097 It is an array of dictionaries with "/F" (the first bead in the thread) 

1098 and "/I" (a thread information dictionary containing information about 

1099 the thread, such as its title, author, and creation date) properties or 

1100 None if there are no articles. 

1101 

1102 Since PDF 2.0 it can also contain an indirect reference to a metadata 

1103 stream containing information about the thread, such as its title, 

1104 author, and creation date. 

1105 """ 

1106 catalog = self.root_object 

1107 if Core.THREADS in catalog: 

1108 return cast("ArrayObject", catalog[Core.THREADS]) 

1109 return None 

1110 

1111 @abstractmethod 

1112 def _get_page_number_by_indirect( 

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

1114 ) -> int | None: 

1115 ... # pragma: no cover 

1116 

1117 def get_page_number(self, page: PageObject) -> int | None: 

1118 """ 

1119 Retrieve page number of a given PageObject. 

1120 

1121 Args: 

1122 page: The page to get page number. Should be 

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

1124 

1125 Returns: 

1126 The page number or None if page is not found 

1127 

1128 """ 

1129 return self._get_page_number_by_indirect(page.indirect_reference) 

1130 

1131 def get_destination_page_number(self, destination: Destination) -> int | None: 

1132 """ 

1133 Retrieve page number of a given Destination object. 

1134 

1135 Args: 

1136 destination: The destination to get page number. 

1137 

1138 Returns: 

1139 The page number or None if page is not found 

1140 

1141 """ 

1142 return self._get_page_number_by_indirect(destination.page) 

1143 

1144 def _build_destination( 

1145 self, 

1146 title: str | bytes, 

1147 array: ArrayObject | None, 

1148 ) -> Destination: 

1149 page, typ = None, None 

1150 # A valid destination is an array of at least a page and a fit type. 

1151 # Anything else (a name, a bare number, a NullObject, None, ...) cannot 

1152 # be unpacked below, so treat it as a missing destination. 

1153 if not isinstance(array, ArrayObject) or len(array) < 2: 

1154 page = NullObject() 

1155 return Destination(title, page, Fit.fit()) 

1156 page, typ, *fit_args = array 

1157 try: 

1158 return Destination(title, page, Fit(fit_type=typ, fit_args=fit_args)) 

1159 except PdfReadError: 

1160 logger_warning( 

1161 "Unknown destination: %(title)r %(fit_args)s", 

1162 source=__name__, 

1163 title=title, 

1164 fit_args=fit_args, 

1165 ) 

1166 if self.strict: 

1167 raise 

1168 # create a link to first Page 

1169 tmp = self.pages[0].indirect_reference 

1170 indirect_reference = NullObject() if tmp is None else tmp 

1171 return Destination(title, indirect_reference, Fit.fit()) 

1172 

1173 def _build_outline_item(self, node: DictionaryObject) -> Destination | None: 

1174 dest, title, outline_item = None, None, None 

1175 

1176 # title required for valid outline 

1177 # §12.3.3, entries in an outline item dictionary 

1178 if "/Title" in node: 

1179 title = cast("str", node["/Title"]) 

1180 else: 

1181 if self.strict: 

1182 raise PdfReadError(f"Outline Entry Missing /Title attribute: {node!r}") 

1183 title = "" 

1184 

1185 if "/A" in node: 

1186 # Action, PDF 1.7 and PDF 2.0 §12.6 (only type GoTo supported) 

1187 action = cast(DictionaryObject, node["/A"]) 

1188 if GoToActionArguments.S in action: 

1189 action_type = cast(NameObject, action[GoToActionArguments.S]) 

1190 if action_type == "/GoTo": 

1191 if GoToActionArguments.D in action: 

1192 dest = action[GoToActionArguments.D] 

1193 elif self.strict: 

1194 raise PdfReadError(f"Outline Action Missing /D attribute: {node!r}") 

1195 elif self.strict: 

1196 raise PdfReadError(f"Outline Action Missing /S attribute: {node!r}") 

1197 elif "/Dest" in node: 

1198 # Destination, PDF 1.7 and PDF 2.0 §12.3.2 

1199 dest = node["/Dest"] 

1200 # if array was referenced in another object, will be a dict w/ key "/D" 

1201 if isinstance(dest, DictionaryObject) and "/D" in dest: 

1202 dest = dest["/D"] 

1203 

1204 if isinstance(dest, ArrayObject): 

1205 outline_item = self._build_destination(title, dest) 

1206 elif isinstance(dest, str): 

1207 # named destination, addresses NameObject Issue #193 

1208 # TODO: Keep named destination instead of replacing it? 

1209 try: 

1210 outline_item = self._build_destination( 

1211 title, self._named_destinations[dest].dest_array 

1212 ) 

1213 except KeyError: 

1214 # named destination not found in Name Dict 

1215 outline_item = self._build_destination(title, None) 

1216 elif dest is None: 

1217 # outline item not required to have destination or action 

1218 # PDFv1.7 Table 153 

1219 outline_item = self._build_destination(title, dest) 

1220 else: 

1221 if self.strict: 

1222 raise PdfReadError(f"Unexpected destination {dest!r}") 

1223 logger_warning( 

1224 "Removed unexpected destination %(dest)r from destination", 

1225 source=__name__, 

1226 dest=dest, 

1227 ) 

1228 outline_item = self._build_destination(title, None) 

1229 

1230 # if outline item created, add color, format, and child count if present 

1231 if outline_item: 

1232 if "/C" in node: 

1233 # Color of outline item font in (R, G, B) with values ranging 0.0-1.0 

1234 color = node["/C"] 

1235 if isinstance(color, list): 

1236 outline_item[NameObject("/C")] = ArrayObject(FloatObject(c) for c in color) 

1237 else: 

1238 logger_warning( 

1239 "Ignoring non-array outline color %(color)r", 

1240 source=__name__, 

1241 color=color, 

1242 ) 

1243 if "/F" in node: 

1244 # specifies style characteristics bold and/or italic 

1245 # with 1=italic, 2=bold, 3=both 

1246 outline_item[NameObject("/F")] = node["/F"] 

1247 if "/Count" in node: 

1248 # absolute value = num. visible children 

1249 # with positive = open/unfolded, negative = closed/folded 

1250 outline_item[NameObject("/Count")] = node["/Count"] 

1251 # if count is 0 we will consider it as open (to have available is_open) 

1252 outline_item[NameObject("/%is_open%")] = BooleanObject( 

1253 node.get("/Count", 0) >= 0 

1254 ) 

1255 outline_item.node = node 

1256 try: 

1257 outline_item.indirect_reference = node.indirect_reference 

1258 except AttributeError: 

1259 pass 

1260 return outline_item 

1261 

1262 @property 

1263 def pages(self) -> Sequence[PageObject]: 

1264 """ 

1265 Property that emulates a list of :class:`PageObject<pypdf._page.PageObject>`. 

1266 This property allows to get a page or a range of pages. 

1267 

1268 The returned object supports indexing, slicing, ``len()``, iteration and 

1269 (for PdfWriter) ``del``, but it is not a :class:`list` - pages are looked 

1270 up on demand rather than materialized up front, so list-only operations 

1271 such as ``append()`` or concatenation with ``+`` are not available. 

1272 

1273 Note: 

1274 For PdfWriter only: Provides the capability to remove a page/range of 

1275 page from the list (using the del operator). Remember: Only the page 

1276 entry is removed, as the objects beneath can be used elsewhere. A 

1277 solution to completely remove them - if they are not used anywhere - is 

1278 to write to a buffer/temporary file and then load it into a new 

1279 PdfWriter. 

1280 

1281 """ 

1282 return _VirtualList(self.get_num_pages, self.get_page) 

1283 

1284 @property 

1285 def page_labels(self) -> list[str]: 

1286 """ 

1287 A list of labels for the pages in this document. 

1288 

1289 This property is read-only. The labels are in the order that the pages 

1290 appear in the document. 

1291 """ 

1292 return index2labels(self, len(self.pages)) 

1293 

1294 @property 

1295 def page_layout(self) -> str | None: 

1296 """ 

1297 Get the page layout currently being used. 

1298 

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

1300 :widths: 50 200 

1301 

1302 * - /NoLayout 

1303 - Layout explicitly not specified 

1304 * - /SinglePage 

1305 - Show one page at a time 

1306 * - /OneColumn 

1307 - Show one column at a time 

1308 * - /TwoColumnLeft 

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

1310 * - /TwoColumnRight 

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

1312 * - /TwoPageLeft 

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

1314 * - /TwoPageRight 

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

1316 """ 

1317 try: 

1318 return cast(NameObject, self.root_object[CA.PAGE_LAYOUT]) 

1319 except KeyError: 

1320 return None 

1321 

1322 @property 

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

1324 """ 

1325 Get the page mode currently being used. 

1326 

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

1328 :widths: 50 200 

1329 

1330 * - /UseNone 

1331 - Do not show outline or thumbnails panels 

1332 * - /UseOutlines 

1333 - Show outline (aka bookmarks) panel 

1334 * - /UseThumbs 

1335 - Show page thumbnails panel 

1336 * - /FullScreen 

1337 - Fullscreen view 

1338 * - /UseOC 

1339 - Show Optional Content Group (OCG) panel 

1340 * - /UseAttachments 

1341 - Show attachments panel 

1342 """ 

1343 try: 

1344 return self.root_object["/PageMode"] # type: ignore[return-value] 

1345 except KeyError: 

1346 return None 

1347 

1348 def _flatten(self, list_only: bool = False) -> None: 

1349 """ 

1350 Process the document pages to ease searching. 

1351 

1352 Attributes of a page may inherit from ancestor nodes 

1353 in the page tree. Flattening means moving 

1354 any inheritance data into descendant nodes, 

1355 effectively removing the inheritance dependency. 

1356 The result is stored in ``self.flattened_pages``. 

1357 

1358 Note: It is distinct from another use of "flattening" applied to PDFs. 

1359 Flattening a PDF also means combining all the contents into one single layer 

1360 and making the file less editable. 

1361 

1362 The page tree is walked with an explicit stack instead of recursion, so the 

1363 traversal is bound by ``Configuration.page_tree_maximum_depth`` and 

1364 ``Configuration.page_tree_maximum_entries`` only, not by the interpreter 

1365 recursion limit. 

1366 

1367 Args: 

1368 list_only: If True, the page's own entries are not copied into the 

1369 generated :class:`PageObject`. Attributes inherited from ancestor 

1370 nodes are applied either way. Note that a page reached through an 

1371 indirect reference is already populated by :class:`PageObject` 

1372 itself, so this only has an effect for ``/Kids`` entries that are 

1373 inline dictionaries. 

1374 

1375 """ 

1376 configuration = get_configuration() 

1377 self.flattened_pages = None 

1378 pages = self.root_object.get("/Pages", NullObject()).get_object() 

1379 if not isinstance(pages, DictionaryObject): 

1380 raise PdfReadError("Invalid object in /Pages") 

1381 

1382 flattened_pages: list[PageObject] = [] 

1383 traversal_state = _TraversalState() 

1384 remaining_page_entries = _TraversalState(entry_count=configuration.page_tree_maximum_page_entries) 

1385 # id() values of the nodes on the path from the root to the current node. 

1386 # Detects multi-hop cycles such as A→B→C→A that the single-parent check misses. 

1387 ancestor_ids: set[int] = set() 

1388 # The /Pages nodes of that path whose /Kids are not exhausted yet. 

1389 stack: list[_PageTreeFrame] = [] 

1390 item: _PageTreeItem | None = _PageTreeItem( 

1391 node=pages, inherit={}, indirect_reference=None, depth=0 

1392 ) 

1393 while item is not None: 

1394 if item.depth > configuration.page_tree_maximum_depth: 

1395 raise LimitReachedError( 

1396 f"Maximum page tree depth reached: {item.depth} > {configuration.page_tree_maximum_depth}." 

1397 ) 

1398 

1399 # Get the current node_type 

1400 node = item.node 

1401 if PagesAttributes.TYPE in node: 

1402 node_type = cast(str, node[PagesAttributes.TYPE]) 

1403 # if the page tree node has no /Type, consider as a page if /Kids is also missing 

1404 elif PagesAttributes.KIDS not in node: 

1405 # Without /Type, only accept it as a page if it carries a structural page key. 

1406 if self.strict and not any(key in node for key in (PG.CONTENTS, PG.MEDIABOX, PG.PARENT)): 

1407 raise PdfReadError(f"Non-page object reached through /Kids: {node!r}") 

1408 node_type = "/Page" 

1409 else: 

1410 node_type = "/Pages" 

1411 

1412 # Flatten that type of node 

1413 if node_type == "/Pages": 

1414 ancestor_ids.add(id(node)) 

1415 stack.append(self._enter_page_tree_node(item)) 

1416 elif node_type == "/Page": 

1417 flattened_pages.append( 

1418 self._flatten_leaf_page( 

1419 item=item, list_only=list_only, remaining_page_entries=remaining_page_entries 

1420 ) 

1421 ) 

1422 

1423 item = self._pop_next_page_tree_kid(stack, ancestor_ids, traversal_state) 

1424 

1425 # Assigned only here, so that a failed traversal does not leave a partial page list behind. 

1426 self.flattened_pages = flattened_pages 

1427 

1428 def _enter_page_tree_node(self, item: _PageTreeItem) -> _PageTreeFrame: 

1429 """ 

1430 Start walking an intermediate ``/Pages`` node: propagate its inheritable 

1431 attributes and pair it with an iterator over its ``/Kids``. 

1432 """ 

1433 pages = item.node 

1434 # Copied before being modified, as the kids of the enclosing node share it. 

1435 inherit = dict(item.inherit) 

1436 for attr in _INHERITABLE_PAGE_ATTRIBUTES: 

1437 if attr in pages: 

1438 inherit[attr] = pages[attr] 

1439 

1440 kids = pages.get(PagesAttributes.KIDS, ArrayObject()).get_object() 

1441 if isinstance(kids, NullObject): 

1442 kids = ArrayObject() 

1443 elif not isinstance(kids, ArrayObject): 

1444 raise PdfReadError(f"Expected /Kids to be an array, got {type(kids).__name__}.") 

1445 

1446 return item._replace(inherit=inherit), iter(kids) 

1447 

1448 def _pop_next_page_tree_kid( 

1449 self, 

1450 stack: list[_PageTreeFrame], 

1451 ancestor_ids: set[int], 

1452 traversal_state: _TraversalState, 

1453 ) -> _PageTreeItem | None: 

1454 """ 

1455 Return the next page tree node to flatten, leaving the ``/Pages`` nodes whose 

1456 ``/Kids`` are exhausted, or ``None`` when the traversal is complete. 

1457 

1458 Cyclic references and the configured page-tree entry limit are enforced here. 

1459 """ 

1460 configuration = get_configuration() 

1461 while stack: 

1462 parent, kids = stack[-1] 

1463 pages_reference = getattr(parent.node, "indirect_reference", object()) 

1464 for page in kids: 

1465 if getattr(page, "indirect_reference", object()) == pages_reference: 

1466 raise PdfReadError("Detected cyclic page references.") 

1467 

1468 obj = page.get_object() 

1469 if not isinstance(obj, DictionaryObject): 

1470 if not is_null_or_none(obj): 

1471 logger_warning( 

1472 "Ignoring page tree entry that is not a dictionary: %(entry)s", 

1473 source=__name__, 

1474 entry=obj, 

1475 ) 

1476 # damaged file may have invalid child in /Pages 

1477 continue 

1478 if not obj: 

1479 # An empty dictionary would otherwise be read as a blank page. 

1480 continue 

1481 if id(obj) in ancestor_ids: 

1482 raise PdfReadError("Detected cyclic page references.") 

1483 traversal_state.entry_count += 1 

1484 if traversal_state.entry_count > configuration.page_tree_maximum_entries: 

1485 raise LimitReachedError( 

1486 "Maximum page tree entry limit reached: " 

1487 f"{traversal_state.entry_count} > {configuration.page_tree_maximum_entries}." 

1488 ) 

1489 return _PageTreeItem( 

1490 node=obj, 

1491 inherit=parent.inherit, 

1492 indirect_reference=page if isinstance(page, IndirectObject) else None, 

1493 depth=parent.depth + 1, 

1494 ) 

1495 stack.pop() 

1496 ancestor_ids.discard(id(parent.node)) 

1497 return None 

1498 

1499 def _flatten_leaf_page( 

1500 self, *, item: _PageTreeItem, list_only: bool, remaining_page_entries: _TraversalState 

1501 ) -> PageObject: 

1502 """ 

1503 Build the :class:`PageObject` for a leaf ``/Page`` node. 

1504 

1505 ``list_only`` suppresses copying the page's own entries; the inherited 

1506 attributes are applied regardless. When the node has an indirect reference, 

1507 :class:`PageObject` has already copied those entries in its constructor, 

1508 so the flag only matters for inline ``/Kids`` dictionaries. 

1509 """ 

1510 node = item.node 

1511 

1512 # Indirect PageObjects are populated by the constructor even when 

1513 # list_only=True. Inline dictionaries are copied only when list_only=False. 

1514 entry_count = ( 

1515 len(node) 

1516 if item.indirect_reference is not None or not list_only 

1517 else 0 

1518 ) 

1519 

1520 # Inherited attributes are inserted only when missing from the page. 

1521 entry_count += sum( 

1522 attribute not in node for attribute in item.inherit 

1523 ) 

1524 

1525 remaining_page_entries.entry_count -= entry_count 

1526 if remaining_page_entries.entry_count < 0: 

1527 raise LimitReachedError("Maximum page tree page entry limit exceeded!") 

1528 

1529 page = PageObject(self, item.indirect_reference) 

1530 if not list_only: 

1531 page.update(node) 

1532 for attribute, value in item.inherit.items(): 

1533 # If the page has its own value, it does not inherit the parent's value. 

1534 if attribute not in page: 

1535 page[attribute] = value 

1536 

1537 return page 

1538 

1539 def remove_page( 

1540 self, 

1541 page: int | PageObject | IndirectObject, 

1542 clean: bool = False, 

1543 ) -> None: 

1544 """ 

1545 Remove page from pages list. 

1546 

1547 Args: 

1548 page: 

1549 * :class:`int`: Page number to be removed. 

1550 * :class:`~pypdf._page.PageObject`: page to be removed. If the page appears many times 

1551 only the first one will be removed. 

1552 * :class:`~pypdf.generic.IndirectObject`: Reference to page to be removed. 

1553 

1554 clean: replace PageObject with NullObject to prevent annotations 

1555 or destinations to reference a detached page. 

1556 

1557 """ 

1558 if self.flattened_pages is None: 

1559 self._flatten(self._readonly) 

1560 assert self.flattened_pages is not None 

1561 if isinstance(page, IndirectObject): 

1562 p = page.get_object() 

1563 if not isinstance(p, PageObject): 

1564 logger_warning("IndirectObject is not referencing a page", source=__name__) 

1565 return 

1566 page = p 

1567 

1568 if not isinstance(page, int): 

1569 try: 

1570 page = self.flattened_pages.index(page) 

1571 except ValueError: 

1572 logger_warning("Cannot find page in pages", source=__name__) 

1573 return 

1574 if not (0 <= page < len(self.flattened_pages)): 

1575 logger_warning("Page number is out of range", source=__name__) 

1576 return 

1577 

1578 ind = self.pages[page].indirect_reference 

1579 # `pages` is typed as a Sequence because it is not a list, but the 

1580 # concrete _VirtualList does implement deletion. 

1581 del cast(_VirtualList, self.pages)[page] 

1582 if clean and ind is not None: 

1583 self._replace_object(ind, NullObject()) 

1584 

1585 def _get_indirect_object(self, num: int, gen: int) -> PdfObject | None: 

1586 """ 

1587 Used to ease development. 

1588 

1589 This is equivalent to generic.IndirectObject(num,gen,self).get_object() 

1590 

1591 Args: 

1592 num: The object number of the indirect object. 

1593 gen: The generation number of the indirect object. 

1594 

1595 Returns: 

1596 A PdfObject 

1597 

1598 """ 

1599 return IndirectObject(num, gen, self).get_object() 

1600 

1601 @property 

1602 def user_access_permissions(self) -> UserAccessPermissions | None: 

1603 """ 

1604 Get the user access permissions for encrypted documents. 

1605 Returns None if not encrypted. 

1606 

1607 .. warning:: 

1608 

1609 For AES-256 encrypted documents (R=5/R=6), the returned 

1610 permissions are derived from the ``/P`` field, which is 

1611 only trustworthy if the ``/Perms`` integrity check passed. 

1612 Check :attr:`are_permissions_valid` to verify. 

1613 """ 

1614 if self._encryption is None: 

1615 return None 

1616 return UserAccessPermissions(self._encryption.P) 

1617 

1618 @property 

1619 def are_permissions_valid(self) -> bool | None: 

1620 """ 

1621 Whether the ``/Perms`` integrity check passed for this document. 

1622 

1623 For AES-256 encrypted documents (R=5/R=6), the ``/Perms`` field 

1624 is an encrypted copy of the permissions that can be verified 

1625 independently. Returns ``False`` if this check fails (the ``/P`` 

1626 permissions may have been tampered with). 

1627 

1628 Returns ``None`` if the document is not encrypted or has not yet 

1629 been decrypted via :meth:`decrypt()<pypdf.PdfReader.decrypt>`. 

1630 Returns ``True`` for non-AES-256 encryption (no ``/Perms`` to check). 

1631 """ 

1632 if self._encryption is None: 

1633 return None 

1634 if not self._encryption.is_decrypted(): 

1635 return None 

1636 return self._encryption._are_permissions_valid 

1637 

1638 @property 

1639 @abstractmethod 

1640 def is_encrypted(self) -> bool: 

1641 """ 

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

1643 

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

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

1646 """ 

1647 ... # pragma: no cover 

1648 

1649 @property 

1650 def xfa(self) -> dict[str, Any] | None: 

1651 retval: dict[str, Any] = {} 

1652 catalog = self.root_object 

1653 

1654 if "/AcroForm" not in catalog or not catalog["/AcroForm"]: 

1655 return None 

1656 

1657 tree = cast(TreeObject, catalog["/AcroForm"]) 

1658 

1659 if "/XFA" in tree: 

1660 fields = tree["/XFA"].get_object() 

1661 if not isinstance(fields, ArrayObject): 

1662 logger_warning( 

1663 "XFA entry is not an array: %(fields)s", 

1664 source=__name__, 

1665 fields=fields, 

1666 ) 

1667 return retval 

1668 i = iter(fields) 

1669 for f in i: 

1670 tag = f 

1671 f = next(i, None) 

1672 if isinstance(f, IndirectObject): 

1673 field = cast(EncodedStreamObject | None, f.get_object()) 

1674 if field: 

1675 es = _decompress_with_limit(field._data) 

1676 retval[tag] = es 

1677 return retval 

1678 

1679 @property 

1680 def attachments(self) -> Mapping[str, list[bytes]]: 

1681 """Mapping of attachment filenames to their content.""" 

1682 entries: dict[str, list[EmbeddedFile]] = {} 

1683 

1684 for entry in self.attachment_list: 

1685 for name in entry._names: 

1686 entries.setdefault(name, []).append(entry) 

1687 

1688 return LazyDict( 

1689 { 

1690 name: (self._get_attachment_contents, attachment_entries) 

1691 for name, attachment_entries in entries.items() 

1692 } 

1693 ) 

1694 

1695 @classmethod 

1696 def _get_attachment_contents(cls, entries: list[EmbeddedFile]) -> list[bytes]: 

1697 return [entry.content for entry in entries] 

1698 

1699 @property 

1700 def attachment_list(self) -> Iterator[EmbeddedFile]: 

1701 """Iterable of attachment objects.""" 

1702 yield from EmbeddedFile._load(self.root_object, strict=self.strict) 

1703 

1704 @abstractmethod 

1705 def _repr_mimebundle_( 

1706 self, 

1707 include: Iterable[str] | None = None, 

1708 exclude: Iterable[str] | None = None, 

1709 ) -> dict[str, Any]: 

1710 """ 

1711 Integration into Jupyter Notebooks. 

1712 

1713 This method returns a dictionary that maps a mime-type to its 

1714 representation. 

1715 

1716 .. seealso:: 

1717 

1718 https://ipython.readthedocs.io/en/stable/config/integrating.html 

1719 """ 

1720 ... # pragma: no cover 

1721 

1722 

1723class LazyDict(Mapping[Any, Any]): 

1724 def __init__(self, *args: Any, **kwargs: Any) -> None: 

1725 self._raw_dict = dict(*args, **kwargs) 

1726 

1727 def __getitem__(self, key: str) -> Any: 

1728 func, arg = self._raw_dict.__getitem__(key) 

1729 return func(arg) 

1730 

1731 def __iter__(self) -> Iterator[Any]: 

1732 return iter(self._raw_dict) 

1733 

1734 def __len__(self) -> int: 

1735 return len(self._raw_dict) 

1736 

1737 def __str__(self) -> str: 

1738 return f"LazyDict(keys={list(self.keys())})"