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