Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/pypdf/_reader.py: 33%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# Copyright (c) 2006, Mathieu Fenniak
2# Copyright (c) 2007, Ashish Kulkarni <kulkarni.ashish@gmail.com>
3#
4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without
7# modification, are permitted provided that the following conditions are
8# met:
9#
10# * Redistributions of source code must retain the above copyright notice,
11# this list of conditions and the following disclaimer.
12# * Redistributions in binary form must reproduce the above copyright notice,
13# this list of conditions and the following disclaimer in the documentation
14# and/or other materials provided with the distribution.
15# * The name of the author may not be used to endorse or promote products
16# derived from this software without specific prior written permission.
17#
18# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
22# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28# POSSIBILITY OF SUCH DAMAGE.
30import os
31import re
32import sys
33from collections.abc import Callable, Iterable
34from io import BytesIO, UnsupportedOperation
35from operator import itemgetter
36from pathlib import Path
37from types import TracebackType
38from typing import (
39 TYPE_CHECKING,
40 Any,
41 cast,
42)
44if sys.version_info >= (3, 11):
45 from typing import Self
46else:
47 from typing_extensions import Self
49from ._configuration import apply_legacy_configuration
50from ._doc_common import PdfDocCommon, convert_to_int
51from ._encryption import Encryption, PasswordType
52from ._utils import (
53 WHITESPACES_AS_BYTES,
54 StrByteType,
55 StreamType,
56 get_stream_data,
57 get_stream_size,
58 logger_warning,
59 read_non_whitespace,
60 read_previous_line,
61 read_until_whitespace,
62 skip_over_comment,
63 skip_over_whitespace,
64)
65from .constants import TrailerKeys as TK
66from .errors import (
67 EmptyFileError,
68 FileNotDecryptedError,
69 LimitReachedError,
70 PdfReadError,
71 PdfStreamError,
72 WrongPasswordError,
73)
74from .generic import (
75 ArrayObject,
76 ByteStringObject,
77 Destination,
78 DictionaryObject,
79 EncodedStreamObject,
80 IndirectObject,
81 NameObject,
82 NullObject,
83 NumberObject,
84 PdfObject,
85 StreamObject,
86 TextStringObject,
87 is_null_or_none,
88 read_object,
89)
90from .xmp import XmpInformation
92if TYPE_CHECKING:
93 from ._page import PageObject
96class PdfReader(PdfDocCommon):
97 """
98 Initialize a PdfReader object.
100 This operation can take some time, as the PDF stream's cross-reference
101 tables are read into memory.
103 Args:
104 stream: A File object or an object that supports the standard read
105 and seek methods similar to a File object. Could also be a
106 string representing a path to a PDF file.
107 strict: Determines whether user should be warned of all
108 problems and also causes some correctable problems to be fatal.
109 Defaults to ``False``.
110 password: Decrypt PDF file at initialization. If the
111 password is None, the file will not be decrypted.
112 Defaults to ``None``.
113 root_object_recovery_limit: The maximum number of objects to query
114 for recovering the Root object in non-strict mode. To disable
115 this security measure, pass ``None``.
116 xref_stream_maximum_entries: The maximum number of entries which are
117 allowed inside a stream-based cross-reference stream.
119 """
121 xref: dict[int, dict[Any, Any]]
122 trailer: DictionaryObject
124 def __init__(
125 self,
126 stream: StrByteType | Path,
127 strict: bool = False,
128 password: str | bytes | None = None,
129 *,
130 root_object_recovery_limit: int | None = 10_000,
131 xref_stream_maximum_entries: int = 2_000_000,
132 ) -> None:
133 self.strict = strict
134 self.flattened_pages: list[PageObject] | None = None
136 #: Storage of parsed PDF objects.
137 self.resolved_objects: dict[tuple[Any, Any], PdfObject | None] = {}
139 self._startxref: int = 0
140 self.xref_index = 0
141 self.xref = {}
142 self.xref_free_entry: dict[int, dict[Any, Any]] = {}
143 self.xref_objStm: dict[int, tuple[Any, Any]] = {}
144 self.trailer = DictionaryObject()
146 # Security parameters.
147 self._root_object_recovery_limit = (
148 root_object_recovery_limit if isinstance(root_object_recovery_limit, int) else sys.maxsize
149 )
150 self._xref_stream_maximum_entries = xref_stream_maximum_entries
151 self._xref_stream_entry_count = 0
152 apply_legacy_configuration()
154 # Map page indirect_reference number to page number
155 self._page_id2num: dict[Any, Any] | None = None
157 self._validated_root: DictionaryObject | None = None
159 self._initialize_stream(stream)
160 self._known_objects: set[tuple[int, int]] = set()
162 self._override_encryption = False
163 self._encryption: Encryption | None = None
164 if self.is_encrypted:
165 self._handle_encryption(password)
166 elif password is not None:
167 raise PdfReadError("Not an encrypted file")
169 self._named_destinations_cache: dict[str, Destination] | None = None
170 self._object_stream_resolution_stack: list[int] = []
172 def _initialize_stream(self, stream: StrByteType | Path) -> None:
173 if hasattr(stream, "mode") and "b" not in stream.mode:
174 logger_warning(
175 "PdfReader stream/file object is not in binary mode. "
176 "It may not be read correctly.",
177 source=__name__,
178 )
179 self._stream_opened = False
180 if isinstance(stream, (str, Path)):
181 with open(stream, "rb") as fh:
182 stream = BytesIO(fh.read())
183 self._stream_opened = True
184 self.read(stream)
185 self.stream = stream
187 def _handle_encryption(self, password: str | bytes | None) -> None:
188 self._override_encryption = True
189 # Some documents may not have a /ID, use two empty
190 # byte strings instead. Solves
191 # https://github.com/py-pdf/pypdf/issues/608
192 id_entry = self.trailer.get(TK.ID, NullObject()).get_object()
193 id1_entry = b""
194 if isinstance(id_entry, ArrayObject) and id_entry:
195 first_id_entry = id_entry[0].get_object()
196 if isinstance(first_id_entry, (ByteStringObject, TextStringObject)):
197 id1_entry = first_id_entry.original_bytes
198 else:
199 logger_warning("Ignoring non-string first /ID entry of the trailer", source=__name__)
200 elif not isinstance(id_entry, NullObject):
201 logger_warning("Ignoring malformed /ID entry of the trailer", source=__name__)
202 encrypt_entry = self.trailer[TK.ENCRYPT]
203 if not isinstance(encrypt_entry, DictionaryObject):
204 raise PdfReadError("/Encrypt entry of the trailer is not a dictionary")
205 self._encryption = Encryption.read(encrypt_entry, id1_entry)
207 # try empty password if no password provided
208 pwd = password if password is not None else b""
209 if (
210 self._encryption.verify(pwd, strict=self.strict) == PasswordType.NOT_DECRYPTED
211 and password is not None
212 ):
213 # raise if password provided
214 raise WrongPasswordError("Wrong password")
215 self._override_encryption = False
217 def __enter__(self) -> Self:
218 return self
220 def __exit__(
221 self,
222 exc_type: type[BaseException] | None,
223 exc_val: BaseException | None,
224 exc_tb: TracebackType | None,
225 ) -> None:
226 self.close()
228 def close(self) -> None:
229 """Close the stream if opened in __init__ and clear memory."""
230 if self._stream_opened:
231 self.stream.close()
232 self.flattened_pages = []
233 self.resolved_objects = {}
234 self.trailer = DictionaryObject()
235 self.xref = {}
236 self.xref_free_entry = {}
237 self.xref_objStm = {}
239 @property
240 def root_object(self) -> DictionaryObject:
241 """Provide access to "/Root". Standardized with PdfWriter."""
242 if self._validated_root:
243 return self._validated_root
244 root = self.trailer.get(TK.ROOT, NullObject()).get_object()
245 root_dictionary: DictionaryObject
246 if isinstance(root, DictionaryObject):
247 root_dictionary = root
248 else:
249 # The catalog has to be a dictionary. Anything else cannot be used,
250 # thus treat it like an empty one and attempt the recovery below.
251 root_dictionary = DictionaryObject()
252 if is_null_or_none(root):
253 logger_warning('Cannot find "/Root" key in trailer', source=__name__)
254 elif root_dictionary.get("/Type") == "/Catalog":
255 self._validated_root = root_dictionary
256 else:
257 logger_warning("Invalid Root object in trailer", source=__name__)
258 if self._validated_root is None:
259 logger_warning('Searching object with "/Catalog" key', source=__name__)
260 number_of_objects = cast(int, self.trailer.get("/Size", 0))
261 for i in range(number_of_objects):
262 if i >= self._root_object_recovery_limit:
263 raise LimitReachedError("Maximum Root object recovery limit reached.")
264 try:
265 obj = self.get_object(i + 1)
266 except MemoryError: # pragma: no cover # TODO: BLE001
267 raise
268 except Exception: # to be sure to capture all errors
269 obj = None
270 if isinstance(obj, DictionaryObject) and obj.get("/Type") == "/Catalog":
271 self._validated_root = obj
272 logger_warning(
273 "Root found at %(obj_reference)r",
274 source=__name__,
275 obj_reference=obj.indirect_reference,
276 )
277 break
278 if self._validated_root is None:
279 if "/Pages" in root_dictionary:
280 logger_warning(
281 "Possible root found at %(root_ref)r, but missing /Catalog key",
282 source=__name__,
283 root_ref=root_dictionary.indirect_reference,
284 )
285 self._validated_root = root_dictionary
286 else:
287 raise PdfReadError("Cannot find Root object in pdf")
288 return self._validated_root
290 @property
291 def _info(self) -> DictionaryObject | None:
292 """
293 Provide access to "/Info". Standardized with PdfWriter.
295 Returns:
296 /Info Dictionary; None if the entry does not exist
298 """
299 info = self.trailer.get(TK.INFO, None)
300 if is_null_or_none(info):
301 return None
302 assert info is not None, "mypy"
303 info = info.get_object()
304 if not isinstance(info, DictionaryObject):
305 raise PdfReadError(
306 "Trailer not found or does not point to a document information dictionary"
307 )
308 return info
310 @property
311 def _ID(self) -> ArrayObject | None:
312 """
313 Provide access to "/ID". Standardized with PdfWriter.
315 Returns:
316 /ID array; None if the entry does not exist
318 """
319 file_identifiers = self.trailer.get(TK.ID, None)
320 if is_null_or_none(file_identifiers):
321 return None
322 assert file_identifiers is not None, "mypy"
323 return cast(ArrayObject, file_identifiers.get_object())
325 @property
326 def pdf_header(self) -> str:
327 """
328 The first 8 bytes of the file.
330 This is typically something like ``'%PDF-1.6'`` and can be used to
331 detect if the file is actually a PDF file and which version it is.
332 """
333 # TODO: Make this return a bytes object for consistency
334 # but that needs a deprecation
335 loc = self.stream.tell()
336 self.stream.seek(0, 0)
337 pdf_file_version = self.stream.read(8).decode("utf-8", "backslashreplace")
338 self.stream.seek(loc, 0) # return to where it was
339 return pdf_file_version
341 @property
342 def xmp_metadata(self) -> XmpInformation | None:
343 """XMP (Extensible Metadata Platform) data."""
344 try:
345 # The document-level metadata stream is exempt from encryption
346 # only if /EncryptMetadata is false (ISO 32000-2, Table 21).
347 self._override_encryption = (
348 self._encryption is not None and not self._encryption.EncryptMetadata
349 )
350 return cast(XmpInformation, self.root_object.xmp_metadata)
351 finally:
352 self._override_encryption = False
354 def _get_page_number_by_indirect(
355 self, indirect_reference: int | NullObject | IndirectObject | None
356 ) -> int | None:
357 """
358 Retrieve the page number from an indirect reference.
360 Args:
361 indirect_reference: The indirect reference to locate.
363 Returns:
364 Page number or None.
366 """
367 if self._page_id2num is None:
368 self._page_id2num = {
369 x.indirect_reference.idnum: i for i, x in enumerate(self.pages) # type: ignore[union-attr]
370 }
372 if is_null_or_none(indirect_reference):
373 return None
374 assert isinstance(indirect_reference, (int, IndirectObject)), "mypy"
375 if isinstance(indirect_reference, int):
376 idnum = indirect_reference
377 else:
378 idnum = indirect_reference.idnum
379 assert self._page_id2num is not None, "hint for mypy"
380 return self._page_id2num.get(idnum, None)
382 def _get_object_from_stream(
383 self, indirect_reference: IndirectObject
384 ) -> PdfObject:
385 obj_id = indirect_reference.idnum
386 if obj_id in self._object_stream_resolution_stack:
387 start = self._object_stream_resolution_stack.index(obj_id)
388 cycle = [*self._object_stream_resolution_stack[start:], obj_id]
389 raise PdfReadError(
390 "Circular object-stream reference detected: " + " -> ".join(map(str, cycle))
391 )
392 self._object_stream_resolution_stack.append(obj_id)
394 try:
395 # indirect reference to object in object stream
396 # read the entire object stream into memory
397 stmnum, _idx = self.xref_objStm[indirect_reference.idnum]
398 obj_stm: EncodedStreamObject = IndirectObject(stmnum, 0, self).get_object() # type: ignore[assignment]
399 # This is an xref to a stream, so its type better be a stream
400 assert cast(str, obj_stm["/Type"]) == "/ObjStm"
401 # Parse ALL objects in this stream in one pass and cache them.
402 # This avoids O(N²) behavior when many objects from the same stream
403 # are resolved individually (each call would re-parse the header).
404 stream_data = BytesIO(obj_stm.get_data())
405 n_value = obj_stm.get("/N")
406 first_value = obj_stm.get("/First")
407 if not isinstance(n_value, NumberObject) or not isinstance(
408 first_value, NumberObject
409 ):
410 raise PdfReadError(
411 f"Invalid /ObjStm header for object {stmnum}: "
412 "/N or /First missing or not a number"
413 )
414 n = int(n_value)
415 first_offset = int(first_value)
417 stream_length = get_stream_size(stream_data)
418 if n < 0 or not 0 <= first_offset <= stream_length:
419 # A negative /N, or a /First outside the stream, cannot
420 # describe a valid object stream; treating it as empty
421 # avoids leaking a ValueError/OverflowError from a bad seek.
422 if self.strict:
423 raise PdfReadError(
424 f"Invalid /N ({n}) or /First ({first_offset}) in object stream {stmnum}."
425 )
426 logger_warning(
427 (
428 "Invalid /N (%(n)d) or /First (%(first)d) in object stream "
429 "%(stmnum)d; ignoring the stream."
430 ),
431 source=__name__,
432 n=n,
433 first=first_offset,
434 stmnum=stmnum,
435 )
436 return NullObject()
438 # ObjStm header format: "objnum offset objnum offset ..."
439 # smallest possible entry: "0 0" = 3 bytes (1 digit + 1 space + 1 digit)
440 # using // 4 would reject a valid 3-byte single entry (3 // 4 = 0)
441 max_n = stream_length // 3
442 stream_data.seek(0)
443 if n > max_n:
444 if self.strict:
445 raise LimitReachedError(f"Value /N {n} for object {stmnum} exceeds maximum allowed value {max_n}.")
446 logger_warning(
447 (
448 "Value /N %(n)d for object %(stmnum)d exceeds maximum allowed value %(max_n)d. "
449 "Limiting to %(max_n)d."
450 ),
451 source=__name__,
452 n=n,
453 stmnum=stmnum,
454 max_n=max_n,
455 )
456 n = max_n
458 # Phase 1: Read the index (objnum, offset) pairs from the header.
459 obj_index: list[tuple[int, int]] = []
460 for _i in range(n):
461 read_non_whitespace(stream_data)
462 stream_data.seek(-1, 1)
463 objnum = NumberObject.read_from_stream(stream_data)
464 read_non_whitespace(stream_data)
465 stream_data.seek(-1, 1)
466 offset = NumberObject.read_from_stream(stream_data)
467 read_non_whitespace(stream_data)
468 stream_data.seek(-1, 1)
469 if objnum < 0 or offset < 0 or first_offset + offset > stream_length:
470 # An object number or target position outside the stream
471 # cannot be valid; skipping the entry avoids leaking a
472 # ValueError/OverflowError from a bad seek while keeping
473 # the other entries.
474 if self.strict:
475 raise PdfReadError(
476 f"Invalid object number ({objnum}) or offset ({offset}) "
477 f"in object stream {stmnum}."
478 )
479 logger_warning(
480 (
481 "Invalid object number (%(objnum)d) or offset (%(offset)d) "
482 "in object stream %(stmnum)d; skipping the entry."
483 ),
484 source=__name__,
485 objnum=objnum,
486 offset=offset,
487 stmnum=stmnum,
488 )
489 continue
490 obj_index.append((int(objnum), int(offset)))
492 # Phase 2: Parse each object and cache it.
493 target_obj: PdfObject = NullObject()
494 found = False
495 for i, (obj_num, obj_offset) in enumerate(obj_index):
496 # Skip objects already in the cache.
497 cached = self.cache_get_indirect_object(0, obj_num)
498 if cached is not None:
499 if obj_num == indirect_reference.idnum:
500 target_obj = cached
501 found = True
502 continue
504 stream_data.seek(first_offset + obj_offset, 0)
506 # To cope with case where the 'pointer' is on a white space
507 read_non_whitespace(stream_data)
508 stream_data.seek(-1, 1)
510 try:
511 obj = read_object(stream_data, self)
512 except PdfStreamError as exc:
513 # Stream object cannot be read. Normally, a critical error, but
514 # Adobe Reader doesn't complain, so continue (in strict mode?)
515 logger_warning(
516 "Invalid stream (index %(index)d) within object %(obj_num)d 0: %(exc)s",
517 source=__name__,
518 index=i,
519 obj_num=obj_num,
520 exc=exc,
521 )
522 if self.strict: # pragma: no cover
523 raise PdfReadError(
524 f"Cannot read object stream: {exc}"
525 ) from exc # pragma: no cover
526 obj = NullObject() # pragma: no cover
528 # Only cache if this stream is the authoritative source for the object.
529 # Incremental updates may override objects originally in the stream;
530 # caching those stale versions would shadow the newer xref entry.
531 authoritative_stm, _idx = self.xref_objStm.get(obj_num, (None, None))
532 if authoritative_stm == stmnum:
533 self.cache_indirect_object(0, obj_num, obj)
535 if obj_num == indirect_reference.idnum:
536 target_obj = obj
537 found = True
539 if not found and self.strict: # pragma: no cover
540 raise PdfReadError(
541 "This is a fatal error in strict mode."
542 ) # pragma: no cover
543 return target_obj
544 finally:
545 self._object_stream_resolution_stack.pop()
547 def get_object(
548 self, indirect_reference: int | IndirectObject
549 ) -> PdfObject | None:
550 if isinstance(indirect_reference, int):
551 indirect_reference = IndirectObject(indirect_reference, 0, self)
553 retval = self.cache_get_indirect_object(
554 indirect_reference.generation, indirect_reference.idnum
555 )
556 key = (
557 indirect_reference.generation,
558 indirect_reference.idnum,
559 )
560 if key in self.resolved_objects:
561 return retval
563 if (
564 indirect_reference.generation == 0
565 and indirect_reference.idnum in self.xref_objStm
566 ):
567 retval = self._get_object_from_stream(indirect_reference)
568 elif (
569 indirect_reference.generation in self.xref
570 and indirect_reference.idnum in self.xref[indirect_reference.generation]
571 ):
572 if self.xref_free_entry.get(indirect_reference.generation, {}).get(
573 indirect_reference.idnum, False
574 ):
575 return NullObject()
576 start = self.xref[indirect_reference.generation][indirect_reference.idnum]
577 self.stream.seek(start, 0)
578 try:
579 idnum, generation = self.read_object_header(self.stream)
580 if (
581 idnum != indirect_reference.idnum
582 or generation != indirect_reference.generation
583 ):
584 raise PdfReadError("Not matching, we parse the file for it")
585 except MemoryError: # pragma: no cover # TODO: BLE001
586 raise
587 except Exception:
588 buf = get_stream_data(self.stream)
589 m = re.search(
590 rf"\s{indirect_reference.idnum}\s+{indirect_reference.generation}\s+obj".encode(),
591 buf,
592 )
593 if m is not None:
594 logger_warning(
595 "Object ID %(idnum)d,%(generation)d ref repaired",
596 source=__name__,
597 idnum=indirect_reference.idnum,
598 generation=indirect_reference.generation,
599 )
600 self.xref[indirect_reference.generation][
601 indirect_reference.idnum
602 ] = (m.start(0) + 1)
603 self.stream.seek(m.start(0) + 1)
604 idnum, generation = self.read_object_header(self.stream)
605 else:
606 idnum = -1
607 generation = -1 # exception will be raised below
608 if idnum != indirect_reference.idnum and self.xref_index:
609 # xref table probably had bad indexes due to not being zero-indexed
610 if self.strict:
611 raise PdfReadError(
612 f"Expected object ID ({indirect_reference.idnum} {indirect_reference.generation}) "
613 f"does not match actual ({idnum} {generation}); "
614 "xref table not zero-indexed."
615 )
616 # xref table is corrected in non-strict mode
617 elif idnum != indirect_reference.idnum and self.strict:
618 # some other problem
619 raise PdfReadError(
620 f"Expected object ID ({indirect_reference.idnum} {indirect_reference.generation}) "
621 f"does not match actual ({idnum} {generation})."
622 )
623 if self.strict:
624 assert generation == indirect_reference.generation
626 current_object = (indirect_reference.idnum, indirect_reference.generation)
627 if current_object in self._known_objects:
628 raise LimitReachedError(f"Detected loop with self reference for {indirect_reference!r}.")
629 self._known_objects.add(current_object)
630 retval = read_object(self.stream, self)
631 self._known_objects.remove(current_object)
633 # override encryption is used for the /Encrypt dictionary
634 if not self._override_encryption and self._encryption is not None:
635 # if we don't have the encryption key:
636 if not self._encryption.is_decrypted():
637 raise FileNotDecryptedError("File has not been decrypted")
638 # otherwise, decrypt here...
639 retval = self._encryption.decrypt_object(
640 retval, indirect_reference.idnum, indirect_reference.generation,
641 strict=self.strict,
642 )
643 else:
644 buf = get_stream_data(self.stream)
645 m = re.search(
646 rf"\s{indirect_reference.idnum}\s+{indirect_reference.generation}\s+obj".encode(),
647 buf,
648 )
649 if m is not None:
650 logger_warning(
651 "Object %(idnum)d %(generation)d found",
652 source=__name__,
653 idnum=indirect_reference.idnum,
654 generation=indirect_reference.generation,
655 )
656 if indirect_reference.generation not in self.xref:
657 self.xref[indirect_reference.generation] = {}
658 self.xref[indirect_reference.generation][indirect_reference.idnum] = (
659 m.start(0) + 1
660 )
661 self.stream.seek(m.end(0) + 1)
662 skip_over_whitespace(self.stream)
663 self.stream.seek(-1, 1)
664 retval = read_object(self.stream, self)
666 # override encryption is used for the /Encrypt dictionary
667 if not self._override_encryption and self._encryption is not None:
668 # if we don't have the encryption key:
669 if not self._encryption.is_decrypted():
670 raise FileNotDecryptedError("File has not been decrypted")
671 # otherwise, decrypt here...
672 retval = self._encryption.decrypt_object(
673 retval, indirect_reference.idnum, indirect_reference.generation,
674 strict=self.strict,
675 )
676 else:
677 logger_warning(
678 "Object %(idnum)d %(generation)d not defined.",
679 source=__name__,
680 idnum=indirect_reference.idnum,
681 generation=indirect_reference.generation,
682 )
683 if self.strict:
684 raise PdfReadError("Could not find object.")
685 # For ObjStm objects, _get_object_from_stream already cached
686 # the result during batch parsing; skip the redundant cache write
687 # to avoid "Overwriting cache" warnings. For non-ObjStm objects
688 # (including encrypted ones that need decrypted values cached),
689 # always write.
690 if not (
691 indirect_reference.generation == 0
692 and indirect_reference.idnum in self.xref_objStm
693 ):
694 self.cache_indirect_object(
695 indirect_reference.generation, indirect_reference.idnum, retval
696 )
697 return retval
699 def read_object_header(self, stream: StreamType) -> tuple[int, int]:
700 # Should never be necessary to read out whitespace, since the
701 # cross-reference table should put us in the right spot to read the
702 # object header. In reality some files have stupid cross-reference
703 # tables that are off by whitespace bytes.
704 skip_over_comment(stream)
705 extra = skip_over_whitespace(stream)
706 stream.seek(-1, 1)
707 idnum = read_until_whitespace(stream, max_bytes=IndirectObject._MAXIMUM_PART_LENGTH, strict=self.strict)
708 extra |= skip_over_whitespace(stream)
709 stream.seek(-1, 1)
710 generation = read_until_whitespace(stream, max_bytes=IndirectObject._MAXIMUM_PART_LENGTH, strict=self.strict)
711 extra |= skip_over_whitespace(stream)
712 stream.seek(-1, 1)
714 # although it's not used, it might still be necessary to read
715 _obj = stream.read(3)
717 read_non_whitespace(stream)
718 stream.seek(-1, 1)
719 if extra and self.strict:
720 logger_warning(
721 "Superfluous whitespace found in object header %(idnum)r %(generation)r",
722 source=__name__,
723 idnum=idnum,
724 generation=generation,
725 )
727 try:
728 return int(idnum), int(generation)
729 except (ValueError, OverflowError) as exception:
730 # Only raise a ValueError here as other types would break future processing.
731 raise ValueError(
732 f"Invalid indirect object reference ({idnum!r} {generation!r} R): {exception}"
733 ) from exception
735 def cache_get_indirect_object(
736 self, generation: int, idnum: int
737 ) -> PdfObject | None:
738 try:
739 return self.resolved_objects.get((generation, idnum))
740 except RecursionError as exception: # pragma: no cover
741 raise PdfReadError("Maximum recursion depth reached.") from exception # pragma: no cover
743 def cache_indirect_object(
744 self, generation: int, idnum: int, obj: PdfObject | None
745 ) -> PdfObject | None:
746 if (generation, idnum) in self.resolved_objects:
747 msg = "Overwriting cache for %(generation)d %(idnum)d"
748 values = {"generation": generation, "idnum": idnum}
749 if self.strict:
750 raise PdfReadError(msg % values)
751 logger_warning(msg, source=__name__, **values)
752 self.resolved_objects[(generation, idnum)] = obj
753 if obj is not None:
754 obj.indirect_reference = IndirectObject(idnum, generation, self)
755 return obj
757 def _replace_object(self, indirect_reference: IndirectObject, obj: PdfObject) -> PdfObject:
758 # function reserved for future development
759 if indirect_reference.pdf != self:
760 raise ValueError("Cannot update PdfReader with external object")
761 if (indirect_reference.generation, indirect_reference.idnum) not in self.resolved_objects:
762 raise ValueError("Cannot find referenced object")
763 self.resolved_objects[(indirect_reference.generation, indirect_reference.idnum)] = obj
764 obj.indirect_reference = indirect_reference
765 return obj
767 def read(self, stream: StreamType) -> None:
768 """
769 Read and process the PDF stream, extracting necessary data.
771 Args:
772 stream: The PDF file stream.
774 """
775 self._basic_validation(stream)
776 self._find_eof_marker(stream)
777 startxref = self._find_startxref_pos(stream)
778 if startxref < 0:
779 # A negative offset cannot point into the file. Treat it like the
780 # zero case (#3157) so the xref table is repaired instead of
781 # leaking a ValueError from a negative seek.
782 logger_warning(
783 "Negative startxref pointer (%(startxref)d), treating it as zero.",
784 source=__name__,
785 startxref=startxref,
786 )
787 startxref = 0
788 self._startxref = startxref
790 # check and eventually correct the startxref only if not strict
791 xref_issue_nr = self._get_xref_issues(stream, startxref)
792 if xref_issue_nr != 0:
793 if self.strict and xref_issue_nr:
794 raise PdfReadError("Broken xref table")
795 logger_warning(
796 "incorrect startxref pointer(%(xref_issue_nr)d)",
797 source=__name__,
798 xref_issue_nr=xref_issue_nr,
799 )
801 # read all cross-reference tables and their trailers
802 self._read_xref_tables_and_trailers(stream, startxref, xref_issue_nr)
804 # if not zero-indexed, verify that the table is correct; change it if necessary
805 if self.xref_index and not self.strict:
806 loc = stream.tell()
807 for gen, xref_entry in self.xref.items():
808 if gen == 65535:
809 continue
810 xref_k = sorted(
811 xref_entry.keys()
812 ) # ensure ascending to prevent damage
813 for xref_id in xref_k:
814 stream.seek(xref_entry[xref_id], 0)
815 try:
816 pid, _pgen = self.read_object_header(stream)
817 except ValueError:
818 self._rebuild_xref_table(stream)
819 break
820 if pid == xref_id - self.xref_index:
821 # fixing index item per item is required for revised PDF.
822 self.xref[gen][pid] = self.xref[gen][xref_id]
823 del self.xref[gen][xref_id]
824 # if not, then either it's just plain wrong, or the
825 # non-zero-index is actually correct
826 stream.seek(loc, 0) # return to where it was
828 # remove wrong objects (not pointing to correct structures) - cf #2326
829 if not self.strict:
830 loc = stream.tell()
831 for gen, xref_entry in self.xref.items():
832 if gen == 65535:
833 continue
834 ids = list(xref_entry.keys())
835 for xref_id in ids:
836 stream.seek(xref_entry[xref_id], 0)
837 try:
838 self.read_object_header(stream)
839 except ValueError:
840 logger_warning(
841 "Ignoring wrong pointing object %(id)d %(gen)d (offset %(offset)d)",
842 source=__name__,
843 id=xref_id,
844 gen=gen,
845 offset=xref_entry[xref_id],
846 )
847 del xref_entry[xref_id] # we can delete the id, we are parsing ids
848 stream.seek(loc, 0) # return to where it was
850 def _basic_validation(self, stream: StreamType) -> None:
851 """Ensure the stream is valid and not empty."""
852 stream.seek(0, os.SEEK_SET)
853 try:
854 header_byte = stream.read(5)
855 except UnicodeDecodeError as exception:
856 raise UnsupportedOperation("cannot read header") from exception
857 if header_byte == b"":
858 raise EmptyFileError("Cannot read an empty file")
859 if header_byte != b"%PDF-":
860 if self.strict:
861 raise PdfReadError(
862 f"PDF starts with '{header_byte.decode('utf8')}', "
863 "but '%PDF-' expected"
864 )
865 logger_warning("invalid pdf header: %(header_byte)r", source=__name__, header_byte=header_byte)
866 stream.seek(0, os.SEEK_END)
868 def _find_eof_marker(self, stream: StreamType) -> None:
869 """
870 Jump to the %%EOF marker.
872 According to the specs, the %%EOF marker should be at the very end of
873 the file. Hence for standard-compliant PDF documents this function will
874 read only the last part (DEFAULT_BUFFER_SIZE).
876 Producers that omit the line break before the marker (``startxref
877 256%%EOF`` or ``256%%EOF``) are accepted as well (#4127).
878 """
879 header_size = 8 # to parse whole file, Header is e.g. '%PDF-1.6'
880 line = b""
881 first = True
882 # Bytes of `line` end at this position. An inline %%EOF therefore
883 # begins at end_position - len(line) + marker_index.
884 end_position = stream.tell()
885 while True:
886 marker_index = line.find(b"%%EOF")
887 if marker_index == 0:
888 break
889 if marker_index > 0 and first:
890 # Only the trailing line is allowed to carry an inline marker.
891 # Earlier lines keep the historical "starts with %%EOF" rule so
892 # a %%EOF buried in stream data is not treated as the trailer.
893 # Leading whitespace in front of the marker is ignored.
894 if line[:marker_index].lstrip(WHITESPACES_AS_BYTES):
895 logger_warning(
896 "EOF marker not at start of line",
897 source=__name__,
898 )
899 stream.seek(end_position - len(line) + marker_index)
900 break
901 if line != b"" and first:
902 if any(
903 line.strip().endswith(tr) for tr in (b"%%EO", b"%%E", b"%%", b"%")
904 ):
905 # Consider the file as truncated while
906 # having enough confidence to carry on.
907 logger_warning("EOF marker seems truncated", source=__name__)
908 break
909 first = False
910 if b"startxref" in line:
911 logger_warning(
912 "CAUTION: startxref found while searching for %%EOF. "
913 "The file might be truncated and some data might not be read.",
914 source=__name__,
915 )
916 if stream.tell() < header_size:
917 if self.strict:
918 raise PdfReadError("EOF marker not found")
919 logger_warning("EOF marker not found", source=__name__)
920 end_position = stream.tell()
921 line = read_previous_line(stream)
923 def _find_startxref_pos(self, stream: StreamType) -> int:
924 """
925 Find startxref entry - the location of the xref table.
927 Args:
928 stream:
930 Returns:
931 The bytes offset
933 """
934 line = read_previous_line(stream)
935 # Some producers append further %%EOF markers below the one that
936 # closes the last revision (#4008). _find_eof_marker() stops at the
937 # very last of them, so the line above it is another marker rather
938 # than the offset. Skip that trailing run to reach the real offset;
939 # the revision being read is unchanged, only the marker padding is
940 # ignored.
941 duplicate_markers = 0
942 while line.startswith(b"%%EOF") and stream.tell() > 0:
943 if duplicate_markers == self._MAX_STARTXREF_RECOVERY_LINES:
944 break
945 line = read_previous_line(stream)
946 duplicate_markers += 1
947 if duplicate_markers:
948 logger_warning(
949 "Duplicate %%EOF marker(s) found, skipping them", source=__name__
950 )
951 try:
952 startxref = int(line)
953 except ValueError as exception: # pragma: no cover
954 # 'startxref' may be on the same line as the location
955 if not line.startswith(b"startxref"):
956 raise PdfReadError("startxref not found") from exception
957 value = line[9:].strip()
958 if not self._is_valid_startxref_value(value):
959 raise PdfReadError("startxref not found") from exception
960 startxref = int(value)
961 logger_warning("startxref on same line as offset", source=__name__)
962 else:
963 line = read_previous_line(stream)
964 if not line.startswith(b"startxref"):
965 # The 'startxref' keyword expected just above the offset is
966 # missing or corrupt (for example a truncated 'tartxref').
967 # Some producers append a broken trailing cross-reference
968 # pointer while an earlier, intact 'startxref' from a previous
969 # revision is still present. Recovering from this violates the
970 # standard, so only attempt it in non-strict mode (#3238).
971 if self.strict:
972 raise PdfReadError("startxref not found")
973 startxref = self._find_previous_startxref_pos(stream)
974 return startxref
976 # Upper bound on the number of lines _find_previous_startxref_pos scans
977 # backwards while recovering a corrupt trailing startxref pointer. Kept
978 # fixed and non-configurable so a crafted file cannot trigger an unbounded
979 # backwards scan.
980 _MAX_STARTXREF_RECOVERY_LINES = 1000
982 @staticmethod
983 def _is_valid_startxref_value(value: bytes) -> bool:
984 if re.fullmatch(rb"[+-]?[0-9]+(?:_[0-9]+)*", value) is None:
985 return False
986 # Respect Python's integer conversion limit without attempting int().
987 max_digits = getattr(sys, "get_int_max_str_digits", lambda: 0)()
988 digits = value.lstrip(b"+-").replace(b"_", b"")
989 return not max_digits or len(digits) <= max_digits
991 @classmethod
992 def _find_previous_startxref_pos(cls, stream: StreamType) -> int:
993 """
994 Recover the most recent intact ``startxref`` pointer by scanning
995 backwards from the current position.
997 This is used as a fallback when the ``startxref`` keyword belonging to
998 the final ``%%EOF`` is corrupt (#3238). The offset always appears on
999 the line directly below the keyword, so the value read immediately
1000 before encountering ``startxref`` (while moving backwards) is returned.
1001 At most ``_MAX_STARTXREF_RECOVERY_LINES`` lines are inspected.
1003 Args:
1004 stream: The PDF byte stream, positioned just above the corrupt
1005 trailing pointer.
1007 Returns:
1008 The bytes offset of the recovered ``startxref``.
1010 """
1011 offset: int | None = None
1012 for _ in range(cls._MAX_STARTXREF_RECOVERY_LINES):
1013 if stream.tell() <= 0:
1014 break
1015 line = read_previous_line(stream)
1016 if not line.startswith(b"startxref"):
1017 try:
1018 offset = int(line)
1019 except ValueError:
1020 offset = None
1021 continue
1022 if len(line) > 9:
1023 # 'startxref' on the same line as the offset
1024 value = line[9:].strip()
1025 if not cls._is_valid_startxref_value(value):
1026 continue
1027 return int(value)
1028 if offset is not None:
1029 logger_warning(
1030 "found startxref pointing to a previous revision after "
1031 "a corrupt one",
1032 source=__name__,
1033 )
1034 return offset
1035 break
1036 raise PdfReadError("startxref not found")
1038 def _load_recovery_cache(self, data: bytes) -> dict[int, tuple[int, int]]:
1039 cache = {}
1040 for object_number, generation_number, object_start in self._find_pdf_objects(data):
1041 if object_number in cache:
1042 # Always use the first match.
1043 continue
1044 cache[object_number] = (object_start, generation_number)
1045 return cache
1047 def _read_standard_xref_table__handle_size(self, stream: StreamType) -> int | None:
1048 size = cast(int, read_object(stream, self))
1049 if not isinstance(size, int):
1050 logger_warning(
1051 "Invalid/Truncated xref table. Rebuilding it.",
1052 source=__name__,
1053 )
1054 self._rebuild_xref_table(stream)
1055 stream.read()
1056 return None
1057 # A valid entry has a size of 20 bytes.
1058 size_limit = get_stream_size(stream) // 20
1059 if size > size_limit:
1060 raise LimitReachedError(f"Declared size {size} exceeds allowed limit of {size_limit}!")
1061 return size
1063 def _read_standard_xref_table(self, stream: StreamType) -> None:
1064 # standard cross-reference table
1065 ref = stream.read(3)
1066 if ref != b"ref":
1067 raise PdfReadError("xref table read error")
1068 read_non_whitespace(stream)
1069 stream.seek(-1, 1)
1070 first_time = True # check if the first time looking at the xref table
1071 recovery_cache: dict[int, tuple[int, int]] | None = None
1072 previous_position: int | None = None
1073 while True:
1074 num = cast(int, read_object(stream, self))
1075 if first_time and num != 0:
1076 self.xref_index = num
1077 if self.strict:
1078 logger_warning(
1079 "Xref table not zero-indexed. ID numbers for objects will be corrected.",
1080 source=__name__,
1081 )
1082 # if table not zero indexed, could be due to error from when PDF was created
1083 # which will lead to mismatched indices later on, only warned and corrected if self.strict==True
1084 first_time = False
1085 read_non_whitespace(stream)
1086 stream.seek(-1, 1)
1087 size = self._read_standard_xref_table__handle_size(stream)
1088 if size is None:
1089 return
1090 read_non_whitespace(stream)
1091 stream.seek(-1, 1)
1092 cnt = 0
1093 while cnt < size:
1094 line = stream.read(20)
1095 if not line:
1096 raise PdfReadError("Unexpected empty line in Xref table.")
1098 # It's very clear in section 3.4.3 of the PDF spec
1099 # that all cross-reference table lines are a fixed
1100 # 20 bytes (as of PDF 1.7). However, some files have
1101 # 21-byte entries (or more) due to the use of \r\n
1102 # (CRLF) EOL's. Detect that case, and adjust the line
1103 # until it does not begin with a \r (CR) or \n (LF).
1104 while line[0] in b"\x0D\x0A":
1105 stream.seek(-20 + 1, 1)
1106 line = stream.read(20)
1107 if len(line) != 20:
1108 raise PdfReadError("Unexpected EOF in Xref table.")
1110 # On the other hand, some malformed PDF files
1111 # use a single character EOL without a preceding
1112 # space. Detect that case, and seek the stream
1113 # back one character (0-9 means we've bled into
1114 # the next xref entry, t means we've bled into the
1115 # text "trailer"):
1116 if line[-1] in b"0123456789t":
1117 stream.seek(-1, 1)
1119 try:
1120 offset_b, generation_b = line[:16].split(b" ")
1121 entry_type_b = line[17:18]
1123 offset, generation = int(offset_b), int(generation_b)
1124 except MemoryError: # pragma: no cover # TODO: BLE001
1125 raise
1126 except Exception:
1127 if recovery_cache is None:
1128 buf = get_stream_data(stream)
1129 recovery_cache = self._load_recovery_cache(buf)
1131 if num not in recovery_cache:
1132 logger_warning(
1133 "entry %(num)d in Xref table invalid; object not found",
1134 source=__name__,
1135 num=num,
1136 )
1137 generation = 65535
1138 offset = -1
1139 entry_type_b = b"f"
1140 else:
1141 logger_warning(
1142 "entry %(num)d in Xref table invalid but object found",
1143 source=__name__,
1144 num=num,
1145 )
1146 generation, offset = recovery_cache[num]
1147 entry_type_b = b"n"
1149 if generation not in self.xref:
1150 self.xref[generation] = {}
1151 self.xref_free_entry[generation] = {}
1152 if num in self.xref[generation]:
1153 # It really seems like we should allow the last
1154 # xref table in the file to override previous
1155 # ones. Since we read the file backwards, assume
1156 # any existing key is already set correctly.
1157 pass
1158 else:
1159 if entry_type_b == b"n":
1160 self.xref[generation][num] = offset
1161 try:
1162 self.xref_free_entry[generation][num] = entry_type_b == b"f"
1163 except MemoryError: # pragma: no cover # TODO: BLE001
1164 raise
1165 except Exception:
1166 pass
1167 try:
1168 self.xref_free_entry[65535][num] = entry_type_b == b"f"
1169 except MemoryError: # pragma: no cover # TODO: BLE001
1170 raise
1171 except Exception:
1172 pass
1173 cnt += 1
1174 num += 1
1175 read_non_whitespace(stream)
1176 stream.seek(-1, 1)
1177 # Skip any PDF comments between xref entries and the trailer
1178 # keyword. Some PDF producers (e.g. Vectorizer.AI) insert
1179 # comments here which are legal per the PDF spec (§7.2.3).
1180 while stream.read(1) == b"%":
1181 stream.seek(-1, 1)
1182 skip_over_comment(stream)
1183 read_non_whitespace(stream)
1184 stream.seek(-1, 1)
1185 stream.seek(-1, 1)
1186 trailer_tag = stream.read(7)
1187 if trailer_tag == b"trailer":
1188 break
1190 # More xrefs should move the parser to another section.
1191 stream.seek(-7, 1)
1193 # Detect a repeated read at the same position.
1194 rewound_position = stream.tell()
1195 if rewound_position == previous_position:
1196 raise PdfReadError(
1197 f"Xref parsing stuck at position {rewound_position}: {trailer_tag!r}"
1198 )
1199 previous_position = rewound_position
1201 def _read_xref_tables_and_trailers(
1202 self, stream: StreamType, startxref: int | None, xref_issue_nr: int
1203 ) -> None:
1204 """Read the cross-reference tables and trailers in the PDF stream."""
1205 self.xref = {}
1206 self.xref_free_entry = {}
1207 self.xref_objStm = {}
1208 self._xref_stream_entry_count = 0
1209 self.trailer = DictionaryObject()
1210 visited_xref_offsets: set[int] = set()
1211 while startxref is not None:
1212 # Detect circular /Prev references in the xref chain
1213 if startxref in visited_xref_offsets:
1214 logger_warning(
1215 "Circular xref chain detected at offset %(startxref)d, stopping",
1216 source=__name__,
1217 startxref=startxref,
1218 )
1219 break
1220 visited_xref_offsets.add(startxref)
1221 # load the xref table
1222 stream.seek(startxref, 0)
1223 x = stream.read(1)
1224 if x in b"\r\n":
1225 x = stream.read(1)
1226 if x == b"x":
1227 startxref = self._read_xref(stream)
1228 elif xref_issue_nr:
1229 try:
1230 self._rebuild_xref_table(stream)
1231 break
1232 except MemoryError: # pragma: no cover # TODO: BLE001
1233 raise
1234 except Exception:
1235 xref_issue_nr = 0
1236 elif x.isdigit():
1237 try:
1238 xrefstream = self._read_pdf15_xref_stream(stream)
1239 except Exception as exception: # pragma: no cover
1240 if TK.ROOT in self.trailer:
1241 logger_warning(
1242 "Previous trailer cannot be read: %(args)s",
1243 source=__name__,
1244 args=exception.args,
1245 )
1246 break
1247 raise PdfReadError(f"Trailer cannot be read: {exception!s}") from exception # pragma: no cover
1248 self._process_xref_stream(xrefstream)
1249 if "/Prev" in xrefstream:
1250 startxref = cast(int, xrefstream["/Prev"])
1251 else:
1252 break
1253 else:
1254 startxref = self._read_xref_other_error(stream, startxref)
1256 # The trailer keys a PDF 1.5+ cross-reference stream carries in place of a
1257 # `trailer` keyword (PDF 2.0 specification, table 17).
1258 _XREF_STREAM_TRAILER_KEYS = (TK.ROOT, TK.ENCRYPT, TK.INFO, TK.ID, TK.SIZE)
1260 def _process_xref_stream(self, xrefstream: DictionaryObject) -> None:
1261 """Process and handle the xref stream."""
1262 for key in self._XREF_STREAM_TRAILER_KEYS:
1263 if key in xrefstream and key not in self.trailer:
1264 self.trailer[NameObject(key)] = xrefstream.raw_get(key)
1265 if "/XRefStm" in xrefstream:
1266 p = self.stream.tell()
1267 self.stream.seek(cast(int, xrefstream["/XRefStm"]) + 1, 0)
1268 self._read_pdf15_xref_stream(self.stream)
1269 self.stream.seek(p, 0)
1271 def _read_xref(self, stream: StreamType) -> int | None:
1272 self._read_standard_xref_table(stream)
1273 if stream.read(1) == b"":
1274 return None
1275 stream.seek(-1, 1)
1276 read_non_whitespace(stream)
1277 stream.seek(-1, 1)
1278 new_trailer = cast(dict[str, Any], read_object(stream, self))
1279 for key, value in new_trailer.items():
1280 if key not in self.trailer:
1281 self.trailer[key] = value
1282 if "/XRefStm" in new_trailer:
1283 p = stream.tell()
1284 stream.seek(cast(int, new_trailer["/XRefStm"]) + 1, 0)
1285 try:
1286 self._read_pdf15_xref_stream(stream)
1287 except MemoryError: # pragma: no cover # TODO: BLE001
1288 raise
1289 except Exception:
1290 logger_warning(
1291 "XRef object at %(xref_stm)d can not be read, some object may be missing",
1292 source=__name__,
1293 xref_stm=int(new_trailer["/XRefStm"]),
1294 )
1295 stream.seek(p, 0)
1296 if "/Prev" in new_trailer:
1297 return cast(int, new_trailer["/Prev"])
1298 return None
1300 def _read_xref_other_error(
1301 self, stream: StreamType, startxref: int
1302 ) -> int | None:
1303 # some PDFs have /Prev=0 in the trailer, instead of no /Prev
1304 if startxref == 0:
1305 if self.strict:
1306 raise PdfReadError(
1307 "/Prev=0 in the trailer (try opening with strict=False)"
1308 )
1309 logger_warning(
1310 "/Prev=0 in the trailer - assuming there is no previous xref table",
1311 source=__name__,
1312 )
1313 return None
1314 # bad xref character at startxref. Let's see if we can find
1315 # the xref table nearby, as we've observed this error with an
1316 # off-by-one before.
1317 stream.seek(-11, 1)
1318 tmp = stream.read(20)
1319 xref_loc = tmp.find(b"xref")
1320 if xref_loc != -1:
1321 startxref -= 10 - xref_loc
1322 return startxref
1323 # No explicit xref table, try finding a cross-reference stream.
1324 stream.seek(startxref, 0)
1325 for look in range(25): # value extended to cope with more linearized files
1326 if stream.read(1).isdigit():
1327 # This is not a standard PDF, consider adding a warning
1328 startxref += look
1329 return startxref
1330 # no xref table found at specified location
1331 if "/Root" in self.trailer and not self.strict:
1332 # if Root has been already found, just raise warning
1333 logger_warning("Invalid parent xref., rebuild xref", source=__name__)
1334 try:
1335 self._rebuild_xref_table(stream)
1336 except Exception as exception: # pragma: no cover
1337 raise PdfReadError("Cannot rebuild xref") from exception # pragma: no cover
1338 return None
1339 raise PdfReadError("Could not find xref table at specified location")
1341 def _sanitize_pdf15_xref_stream_index_pairs(
1342 self, index_pairs: list[int], entry_sizes: list[int], xref_stream: StreamObject
1343 ) -> list[int]:
1344 # `entry_sizes` holds the byte widths for the entries. Summing determines the total number of bytes per entry.
1345 # We expect up to 3 values. `min_entry_bytes` will be the smallest plausible size of one xref entry.
1346 min_entry_bytes = sum(int(entry_sizes[i]) for i in range(min(len(entry_sizes), 3)))
1347 if min_entry_bytes == 0:
1348 message = "Cross-reference stream encodes no entry data."
1349 if self.strict:
1350 raise PdfStreamError(message)
1351 logger_warning(message, source=__name__)
1352 return []
1354 # maximum number of entries that could physically fit
1355 max_entries = len(xref_stream.get_data()) // min_entry_bytes + 1
1357 result = []
1358 total = 0
1360 for index, pair_value in enumerate(index_pairs):
1361 pair_value_int = int(pair_value)
1363 # `index_pairs` has the format `[start0, count0, start1, count1, ...]`
1364 # Only modify the counts here, but keep the start values.
1365 if index % 2 == 1:
1366 if pair_value_int < 0:
1367 if self.strict:
1368 raise PdfStreamError(f"Negative XRef count {pair_value_int}.")
1369 logger_warning(
1370 "Negative XRef count %(count)d, using 0.",
1371 source=__name__,
1372 count=pair_value_int,
1373 )
1374 pair_value_int = 0
1376 if total + pair_value_int > max_entries:
1377 if self.strict:
1378 raise LimitReachedError(
1379 f"Total XRef entries {total + pair_value_int} exceed maximum allowed value {max_entries}."
1380 )
1381 new_v = max(0, max_entries - total)
1382 logger_warning(
1383 "Clamping XRef count from %(old_count)d to %(new_count)d to fit stream size.",
1384 source=__name__,
1385 old_count=pair_value_int,
1386 new_count=new_v,
1387 )
1388 pair_value_int = new_v
1390 total += pair_value_int
1392 result.append(pair_value_int)
1394 return result
1396 def _read_pdf15_xref_stream(self, stream: StreamType) -> StreamObject:
1397 """Read the cross-reference stream for PDF 1.5+."""
1398 stream.seek(-1, 1)
1399 stream_idnum, stream_generation = self.read_object_header(stream)
1400 xref_stream = cast(StreamObject, read_object(stream, self))
1401 if cast(str, xref_stream["/Type"]) != "/XRef":
1402 raise PdfReadError(f"Unexpected type {xref_stream['/Type']!r}")
1403 self.cache_indirect_object(stream_generation, stream_idnum, xref_stream)
1405 # Index pairs specify the subsections in the dictionary.
1406 # If none, create one subsection that spans everything.
1407 if "/Size" not in xref_stream:
1408 # According to table 17 of the PDF 2.0 specification, this key is required.
1409 raise PdfReadError(f"Size missing from XRef stream {xref_stream!r}!")
1410 index_pairs = xref_stream.get("/Index", [0, xref_stream["/Size"]])
1412 entry_sizes = cast(list[int], xref_stream.get("/W"))
1413 assert len(entry_sizes) >= 3
1414 if self.strict and len(entry_sizes) > 3:
1415 raise PdfReadError(f"Too many entry sizes: {entry_sizes}")
1416 index_pairs = self._sanitize_pdf15_xref_stream_index_pairs(
1417 index_pairs=index_pairs, entry_sizes=entry_sizes, xref_stream=xref_stream
1418 )
1420 self._xref_stream_entry_count += sum(index_pairs[1::2])
1421 if self._xref_stream_entry_count > self._xref_stream_maximum_entries:
1422 raise LimitReachedError(
1423 f"Maximum XRef stream entry limit reached: "
1424 f"{self._xref_stream_entry_count} > {self._xref_stream_maximum_entries}."
1425 )
1427 stream_data = BytesIO(xref_stream.get_data())
1429 def get_entry(i: int) -> int | tuple[int, ...]:
1430 # Reads the correct number of bytes for each entry. See the
1431 # discussion of the W parameter in PDF spec table 17.
1432 if entry_sizes[i] > 0:
1433 d = stream_data.read(entry_sizes[i])
1434 return convert_to_int(d, entry_sizes[i])
1436 # PDF Spec Table 17: A value of zero for an element in the
1437 # W array indicates...the default value shall be used
1438 if i == 0:
1439 return 1 # First value defaults to 1
1440 return 0
1442 def used_before(num: int, generation: int | tuple[int, ...]) -> bool:
1443 # We move backwards through the xrefs, don't replace any.
1444 return num in self.xref.get(generation, []) or num in self.xref_objStm # type: ignore[arg-type]
1446 # Iterate through each subsection
1447 self._read_xref_subsections(index_pairs, get_entry, used_before)
1448 return xref_stream
1450 @staticmethod
1451 def _get_xref_issues(stream: StreamType, startxref: int) -> int:
1452 """
1453 Return an int which indicates an issue. 0 means there is no issue.
1455 Args:
1456 stream:
1457 startxref:
1459 Returns:
1460 0 means no issue, other values represent specific issues.
1462 """
1463 if startxref == 0:
1464 return 4
1466 stream.seek(startxref - 1, 0) # -1 to check character before
1467 line = stream.read(1)
1468 if line == b"j":
1469 line = stream.read(1)
1470 if line not in b"\r\n \t":
1471 return 1
1472 line = stream.read(4)
1473 if line != b"xref":
1474 # not a xref so check if it is an XREF object
1475 line = b""
1476 while line in b"0123456789 \t":
1477 line = stream.read(1)
1478 if line == b"":
1479 return 2
1480 line += stream.read(2) # 1 char already read, +2 to check "obj"
1481 if line.lower() != b"obj":
1482 return 3
1483 return 0
1485 @classmethod
1486 def _find_pdf_objects(cls, data: bytes) -> Iterable[tuple[int, int, int]]:
1487 index = 0
1488 ord_0 = ord("0")
1489 ord_9 = ord("9")
1490 while True:
1491 index = data.find(b" obj", index)
1492 if index == -1:
1493 return
1495 index_before_space = index - 1
1497 # Skip whitespace backwards
1498 while index_before_space >= 0 and data[index_before_space] in WHITESPACES_AS_BYTES:
1499 index_before_space -= 1
1501 # Read generation number
1502 generation_end = index_before_space + 1
1503 while index_before_space >= 0 and ord_0 <= data[index_before_space] <= ord_9:
1504 index_before_space -= 1
1505 generation_start = index_before_space + 1
1507 # Skip whitespace
1508 while index_before_space >= 0 and data[index_before_space] in WHITESPACES_AS_BYTES:
1509 index_before_space -= 1
1511 # Read object number
1512 object_end = index_before_space + 1
1513 while index_before_space >= 0 and ord_0 <= data[index_before_space] <= ord_9:
1514 index_before_space -= 1
1515 object_start = index_before_space + 1
1517 # Validate
1518 if object_start < object_end and generation_start < generation_end:
1519 object_number = int(data[object_start:object_end])
1520 generation_number = int(data[generation_start:generation_end])
1522 yield object_number, generation_number, object_start
1524 index += 4 # len(b" obj")
1526 @classmethod
1527 def _find_pdf_trailers(cls, data: bytes) -> Iterable[int]:
1528 index = 0
1529 data_length = len(data)
1530 while True:
1531 index = data.find(b"trailer", index)
1532 if index == -1:
1533 return
1535 index_after_trailer = index + 7 # len(b"trailer")
1537 # Skip whitespace
1538 while index_after_trailer < data_length and data[index_after_trailer] in WHITESPACES_AS_BYTES:
1539 index_after_trailer += 1
1541 # Must be dictionary start
1542 if index_after_trailer + 1 < data_length and data[index_after_trailer:index_after_trailer+2] == b"<<":
1543 yield index_after_trailer # offset of '<<'
1545 index += 7 # len(b"trailer")
1547 def _rebuild_xref_table(self, stream: StreamType) -> None:
1548 self.xref = {}
1549 stream.seek(0, 0)
1550 stream_data = stream.read(-1)
1552 for object_number, generation_number, object_start in self._find_pdf_objects(stream_data):
1553 if generation_number not in self.xref:
1554 self.xref[generation_number] = {}
1555 self.xref[generation_number][object_number] = object_start
1557 logger_warning("parsing for Object Streams", source=__name__)
1558 # PDF 1.5+ files may carry the trailer keys inside a cross-reference
1559 # stream instead of behind a `trailer` keyword. Collect them here,
1560 # keyed by their offset, to merge them below in file order.
1561 xref_stream_trailers: list[tuple[int, DictionaryObject]] = []
1562 for generation_number in self.xref:
1563 for object_number in self.xref[generation_number]:
1564 # get_object in manual
1565 object_start = self.xref[generation_number][object_number]
1566 stream.seek(object_start, 0)
1567 try:
1568 _ = self.read_object_header(stream)
1569 obj = cast(StreamObject, read_object(stream, self))
1570 object_type = obj.get("/Type", "")
1571 if object_type == "/XRef":
1572 trailer = DictionaryObject()
1573 for key in self._XREF_STREAM_TRAILER_KEYS:
1574 if key in obj:
1575 trailer[NameObject(key)] = obj.raw_get(key)
1576 xref_stream_trailers.append((object_start, trailer))
1577 continue
1578 if object_type != "/ObjStm":
1579 continue
1580 object_stream = BytesIO(obj.get_data())
1581 actual_count = 0
1582 while True:
1583 current = read_until_whitespace(
1584 object_stream, max_bytes=IndirectObject._MAXIMUM_PART_LENGTH, strict=self.strict
1585 )
1586 if not current.isdigit():
1587 break
1588 inner_object_number = int(current)
1589 skip_over_whitespace(object_stream)
1590 object_stream.seek(-1, 1)
1591 current = read_until_whitespace(
1592 object_stream, max_bytes=IndirectObject._MAXIMUM_PART_LENGTH, strict=self.strict
1593 )
1594 if not current.isdigit(): # pragma: no cover
1595 break # pragma: no cover
1596 inner_offset = int(current)
1597 self.xref_objStm[inner_object_number] = (object_number, inner_offset)
1598 actual_count += 1
1599 expected_count = cast(int, obj["/N"])
1600 if actual_count != expected_count: # pragma: no cover
1601 logger_warning( # pragma: no cover
1602 (
1603 "found %(actual_count)d objects within "
1604 "Object(%(object_number)d,%(generation_number)d) "
1605 "whereas %(expected)d expected"
1606 ),
1607 source=__name__,
1608 actual_count=actual_count,
1609 object_number=object_number,
1610 generation_number=generation_number,
1611 expected=expected_count,
1612 )
1613 except LimitReachedError:
1614 # Do not let the broad recovery below bypass the token-length limit
1615 # when strict parsing is enabled.
1616 raise
1617 except MemoryError: # pragma: no cover # TODO: BLE001
1618 raise
1619 except Exception: # could be multiple causes
1620 pass
1622 stream.seek(0, 0)
1623 trailers: list[tuple[int, dict[Any, Any]]] = list(xref_stream_trailers)
1624 for position in self._find_pdf_trailers(stream_data):
1625 stream.seek(position, 0)
1626 trailers.append((position, cast(dict[Any, Any], read_object(stream, self))))
1627 # Here, we are parsing the file from start to end, the new data have to erase the existing.
1628 for _, new_trailer in sorted(trailers, key=itemgetter(0)):
1629 for key, value in new_trailer.items():
1630 self.trailer[key] = value
1632 def _read_xref_subsections(
1633 self,
1634 idx_pairs: list[int],
1635 get_entry: Callable[[int], int | tuple[int, ...]],
1636 used_before: Callable[[int, int | tuple[int, ...]], bool],
1637 ) -> None:
1638 """Read and process the subsections of the xref."""
1639 for start, size in self._pairs(idx_pairs):
1640 # The subsections must increase
1641 for num in range(start, start + size):
1642 # The first entry is the type
1643 xref_type = get_entry(0)
1644 # The rest of the elements depend on the xref_type
1645 if xref_type == 0:
1646 # linked list of free objects
1647 next_free_object = get_entry(1) # noqa: F841
1648 next_generation = get_entry(2) # noqa: F841
1649 elif xref_type == 1:
1650 # objects that are in use but are not compressed
1651 byte_offset = get_entry(1)
1652 generation = get_entry(2)
1653 if generation not in self.xref:
1654 self.xref[generation] = {} # type: ignore[index]
1655 if not used_before(num, generation):
1656 self.xref[generation][num] = byte_offset # type: ignore[index]
1657 elif xref_type == 2:
1658 # compressed objects
1659 objstr_num = get_entry(1)
1660 obstr_idx = get_entry(2)
1661 generation = 0 # PDF spec table 18, generation is 0
1662 if not used_before(num, generation):
1663 self.xref_objStm[num] = (objstr_num, obstr_idx)
1664 elif self.strict:
1665 raise PdfReadError(f"Unknown xref type: {xref_type}")
1667 def _pairs(self, array: list[int]) -> Iterable[tuple[int, int]]:
1668 """Iterate over pairs in the array."""
1669 i = 0
1670 while i + 1 < len(array):
1671 yield array[i], array[i + 1]
1672 i += 2
1674 def decrypt(self, password: str | bytes) -> PasswordType:
1675 """
1676 When using an encrypted / secured PDF file with the PDF Standard
1677 encryption handler, this function will allow the file to be decrypted.
1678 It checks the given password against the document's user password and
1679 owner password, and then stores the resulting decryption key if either
1680 password is correct.
1682 It does not matter which password was matched. Both passwords provide
1683 the correct decryption key that will allow the document to be used with
1684 this library.
1686 Args:
1687 password: The password to match.
1689 Returns:
1690 An indicator if the document was decrypted and whether it was the
1691 owner password or the user password.
1693 """
1694 if not self._encryption:
1695 raise PdfReadError("Not encrypted file")
1696 # TODO: raise Exception for wrong password
1697 return self._encryption.verify(password, strict=self.strict)
1699 @property
1700 def is_encrypted(self) -> bool:
1701 """
1702 Read-only boolean property showing whether this PDF file is encrypted.
1704 Note that this property, if true, will remain true even after the
1705 :meth:`decrypt()<pypdf.PdfReader.decrypt>` method is called.
1706 """
1707 return TK.ENCRYPT in self.trailer
1709 def add_form_topname(self, name: str) -> DictionaryObject | None:
1710 """
1711 Add a top level form that groups all form fields below it.
1713 Args:
1714 name: text string of the "/T" Attribute of the created object
1716 Returns:
1717 The created object. ``None`` means no object was created.
1719 """
1720 catalog = self.root_object
1722 if "/AcroForm" not in catalog or not isinstance(
1723 catalog["/AcroForm"], DictionaryObject
1724 ):
1725 return None
1726 acroform = cast(DictionaryObject, catalog[NameObject("/AcroForm")])
1727 if "/Fields" not in acroform:
1728 # TODO: No error but this may be extended for XFA Forms
1729 return None
1731 interim = DictionaryObject()
1732 interim[NameObject("/T")] = TextStringObject(name)
1733 interim[NameObject("/Kids")] = acroform[NameObject("/Fields")]
1734 # Allocate the new object_id beyond the source-file range and all cached object IDs.
1735 object_id = max(
1736 cast(int, self.trailer.get("/Size", 0)) - 1,
1737 max((i for entries in self.xref.values() for i in entries), default=0),
1738 max(self.xref_objStm, default=0),
1739 max((i for _, i in self.resolved_objects), default=0),
1740 ) + 1
1741 self.cache_indirect_object(0, object_id, interim)
1742 arr = ArrayObject()
1743 arr.append(interim.indirect_reference)
1744 acroform[NameObject("/Fields")] = arr
1745 for o in cast(ArrayObject, interim["/Kids"]):
1746 obj = o.get_object()
1747 if "/Parent" in obj:
1748 logger_warning(
1749 "Top Level Form Field %(obj_ref)s has a non-expected parent",
1750 source=__name__,
1751 obj_ref=obj.indirect_reference,
1752 )
1753 obj[NameObject("/Parent")] = interim.indirect_reference
1754 return interim
1756 def rename_form_topname(self, name: str) -> DictionaryObject | None:
1757 """
1758 Rename top level form field that all form fields below it.
1760 Args:
1761 name: text string of the "/T" field of the created object
1763 Returns:
1764 The modified object. ``None`` means no object was modified.
1766 """
1767 catalog = self.root_object
1769 if "/AcroForm" not in catalog or not isinstance(
1770 catalog["/AcroForm"], DictionaryObject
1771 ):
1772 return None
1773 acroform = cast(DictionaryObject, catalog[NameObject("/AcroForm")])
1774 if "/Fields" not in acroform:
1775 return None
1777 interim = cast(
1778 DictionaryObject,
1779 cast(ArrayObject, acroform[NameObject("/Fields")])[0].get_object(),
1780 )
1781 interim[NameObject("/T")] = TextStringObject(name)
1782 return interim
1784 def _repr_mimebundle_(
1785 self,
1786 include: Iterable[str] | None = None,
1787 exclude: Iterable[str] | None = None,
1788 ) -> dict[str, Any]:
1789 """
1790 Integration into Jupyter Notebooks.
1792 This method returns a dictionary that maps a mime-type to its
1793 representation.
1795 .. seealso::
1797 https://ipython.readthedocs.io/en/stable/config/integrating.html
1798 """
1799 self.stream.seek(0)
1800 pdf_data = self.stream.read()
1801 data = {
1802 "application/pdf": pdf_data,
1803 }
1805 if include is not None:
1806 # Filter representations based on include list
1807 data = {k: v for k, v in data.items() if k in include}
1809 if exclude is not None:
1810 # Remove representations based on exclude list
1811 data = {k: v for k, v in data.items() if k not in exclude}
1813 return data
1815 def _get_named_destinations(
1816 self,
1817 *,
1818 tree: DictionaryObject | None = None,
1819 retval: dict[str, Destination] | None = None,
1820 visited: set[int] | None = None,
1821 ) -> dict[str, Destination]:
1822 """Override from PdfDocCommon. In the reader we can assume this is
1823 static, but not in the writer.
1824 """
1825 if tree or retval:
1826 return super()._get_named_destinations(tree=tree, retval=retval, visited=visited)
1828 if self._named_destinations_cache is None:
1829 self._named_destinations_cache = super()._get_named_destinations()
1830 return self._named_destinations_cache