1# Copyright (c) 2006, Mathieu Fenniak
2# All rights reserved.
3#
4# Redistribution and use in source and binary forms, with or without
5# modification, are permitted provided that the following conditions are
6# met:
7#
8# * Redistributions of source code must retain the above copyright notice,
9# this list of conditions and the following disclaimer.
10# * Redistributions in binary form must reproduce the above copyright notice,
11# this list of conditions and the following disclaimer in the documentation
12# and/or other materials provided with the distribution.
13# * The name of the author may not be used to endorse or promote products
14# derived from this software without specific prior written permission.
15#
16# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
20# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26# POSSIBILITY OF SUCH DAMAGE.
27
28__author__ = "Mathieu Fenniak"
29__author_email__ = "biziqe@mathieu.fenniak.net"
30
31import contextlib
32import inspect
33import logging
34import os
35import re
36import sys
37from collections.abc import Callable, Iterable, Iterator, Sequence
38from functools import cache
39from io import BytesIO
40from typing import (
41 Any,
42 NamedTuple,
43 Optional,
44 Union,
45 cast,
46)
47
48from .. import get_configuration
49from .._protocols import PdfReaderProtocol, PdfWriterProtocol, XmpInformationProtocol
50from .._utils import (
51 WHITESPACES,
52 BinaryStreamType,
53 StreamType,
54 deprecate_no_replacement,
55 logger_warning,
56 read_non_whitespace,
57 read_until_regex,
58 read_until_whitespace,
59 skip_over_comment,
60 skip_over_comments,
61)
62from ..constants import (
63 CheckboxRadioButtonAttributes,
64 FieldDictionaryAttributes,
65 FilterTypes,
66 OutlineFontFlag,
67 StreamAttributes,
68 TypArguments,
69 TypFitArguments,
70)
71from ..errors import STREAM_TRUNCATED_PREMATURELY, LimitReachedError, PdfReadError, PdfStreamError
72from ._base import (
73 BooleanObject,
74 ByteStringObject,
75 FloatObject,
76 IndirectObject,
77 NameObject,
78 NullObject,
79 NumberObject,
80 PdfObject,
81 TextStringObject,
82 is_null_or_none,
83)
84from ._fit import Fit
85from ._utils import StreamParsingBudget, read_hex_string_from_stream, read_string_from_stream
86
87if sys.version_info >= (3, 11):
88 from typing import Self
89else:
90 from typing_extensions import Self
91
92logger = logging.getLogger(__name__)
93
94IndirectPattern = re.compile(rb"[+-]?(\d+)\s+(\d+)\s+R[^a-zA-Z]")
95
96
97# The tokens making up most of a content stream, preceded by whitespace. Each
98# alternative only matches what the generic parsing in
99# ContentStream._parse_content_stream would read the same way; everything else,
100# like strings, arrays, inline images or overlong tokens, is left to it.
101#
102# The PDF specification defines no maximum length of a token (ISO 32000-2:2020,
103# Annex C), but the generic parsing raises LimitReachedError for numbers longer
104# than NumberObject._LENGTH_LIMIT (64), operators longer than
105# ContentStream._OPERATOR_LENGTH_LIMIT (128) and names longer than
106# NameObject._LENGTH_LIMIT (4,096). It reads these tokens with
107# read_until_regex(), which checks the limit after reading each chunk, but
108# before searching the chunk for the end of the token. Whether a token slightly
109# shorter than the limit raises thus depends on the bytes after it: a name of
110# 4,092 bytes before " gs" is read, but raises before " 1 1 1 gs".
111#
112# The maximum lengths below are those up to which the generic parsing never
113# raises, whatever follows the token: one byte less than the end of the last
114# chunk below the limit. The chunks have 16, 32, 64, ... bytes (see
115# _READ_UNTIL_REGEX_FIRST_CHUNK_SIZE and _READ_UNTIL_REGEX_MAXIMUM_CHUNK_SIZE in
116# pypdf/_utils.py), so they end at 16, 48, 112, 240, ..., 4,080 bytes. This
117# gives 47 bytes for numbers, 111 for operators and 4,079 for names, counted
118# after the slash like in NameObject.read_from_stream(). Longer tokens are left
119# to the generic parsing, which raises or not as before.
120_CONTENT_STREAM_SIMPLE_TOKEN = re.compile(
121 # Skip the whitespace before the token, like read_non_whitespace() does.
122 rb"[\x00\t\n\f\r ]*"
123 rb"(?:"
124 # A number, which the generic parsing reads up to the first character
125 # NumberObject.NumberPattern matches. The lookahead limits this run of
126 # characters to 47 bytes.
127 rb"(?=[+,\-.0-9]{1,47}(?![+,\-.0-9]))"
128 rb"(?:"
129 # A decimal number with an optional sign, like 1.5, -1. or .5. The
130 # lookahead rejects runs going on with more characters, like 1.2.3, 1,5 or
131 # 1-2, which the generic parsing reads differently.
132 rb"(?P<float>[+-]?(?:\d+\.\d*|\.\d+))(?![+,\-.0-9])"
133 # An integer with an optional sign. The second lookahead rejects the object
134 # number of what looks like an indirect reference, like "1 0 R", which
135 # read_object() reads instead.
136 rb"|(?P<int>[+-]?\d+)(?![+,\-.0-9])(?!\s+\d+\s+R(?![a-zA-Z]))"
137 rb")"
138 # A name of at most 4,079 bytes after the slash, ending at whitespace, a
139 # delimiter or the end of the data. Only printable ASCII characters without
140 # # are matched, so that names with # escapes or other bytes are decoded by
141 # NameObject.read_from_stream().
142 rb"|(?P<name>/[^\x00-\x20\x7f-\xff()<>\[\]{}/%#]{0,4079})(?=[\s()<>\[\]{}/%]|\Z)"
143 # An operator of at most 111 bytes, starting with a letter, ' or " like in
144 # the generic parsing, and ending at whitespace, a delimiter or the end of
145 # the data. BI is rejected, as an inline image follows it.
146 rb"|(?P<operator>(?!BI(?:[\s()<>\[\]{}/%]|\Z))[A-Za-z'\"][^\s()<>\[\]{}/%]{0,110})(?=[\s()<>\[\]{}/%]|\Z)"
147 rb")"
148)
149
150
151# Direct objects of these types are neither streams nor indirect objects.
152# Large arrays consist mostly of them, for example in the /ParentTree of the
153# structure tree, so the clone loops check the exact type first and skip the
154# slower isinstance() checks.
155_SCALAR_TYPES = frozenset(
156 (BooleanObject, ByteStringObject, FloatObject, NameObject, NullObject, NumberObject, TextStringObject)
157)
158
159
160class ArrayObject(list[Any], PdfObject):
161 def replicate(
162 self,
163 pdf_dest: PdfWriterProtocol,
164 ) -> "ArrayObject":
165 arr = cast(
166 "ArrayObject",
167 self._reference_clone(ArrayObject(), pdf_dest, False),
168 )
169 for data in self:
170 if hasattr(data, "replicate"):
171 arr.append(data.replicate(pdf_dest))
172 else:
173 arr.append(data)
174 return arr
175
176 def clone(
177 self,
178 pdf_dest: PdfWriterProtocol,
179 force_duplicate: bool = False,
180 ignore_fields: Sequence[str | int] | None = (),
181 ) -> "ArrayObject":
182 """Clone object into pdf_dest."""
183 try:
184 if self.indirect_reference.pdf == pdf_dest and not force_duplicate: # type: ignore[union-attr]
185 return self
186 except MemoryError: # pragma: no cover # TODO: BLE001
187 raise
188 except Exception:
189 pass
190 arr = cast(
191 "ArrayObject",
192 self._reference_clone(ArrayObject(), pdf_dest, force_duplicate=True),
193 )
194 for data in self:
195 if type(data) in _SCALAR_TYPES:
196 # Same as the generic case below, but without the isinstance() checks.
197 arr.append(data.clone(pdf_dest, force_duplicate, ignore_fields))
198 elif isinstance(data, StreamObject):
199 dup = data._reference_clone(
200 data.clone(pdf_dest, force_duplicate, ignore_fields),
201 pdf_dest,
202 force_duplicate,
203 )
204 arr.append(dup.indirect_reference)
205 elif isinstance(data, IndirectObject) and isinstance(resolved := data.get_object(), StreamObject):
206 dup = data._reference_clone(
207 resolved.clone(pdf_dest, force_duplicate=True, ignore_fields=ignore_fields),
208 pdf_dest,
209 force_duplicate,
210 )
211 arr.append(dup.indirect_reference)
212 elif hasattr(data, "clone"):
213 arr.append(data.clone(pdf_dest, force_duplicate, ignore_fields))
214 else:
215 arr.append(data)
216 return arr
217
218 def hash_bin(self) -> int:
219 """
220 Used to detect modified object.
221
222 Returns:
223 Hash considering type and value.
224
225 """
226 return hash((self.__class__, tuple(x.hash_bin() for x in self)))
227
228 def items(self) -> Iterable[Any]:
229 """Emulate DictionaryObject.items for a list (index, object)."""
230 return enumerate(self)
231
232 def _to_lst(self, lst: Any) -> list[Any]:
233 # Convert to list, internal
234 result: list[Any]
235 if isinstance(lst, (list, tuple, set)):
236 result = list(lst)
237 elif isinstance(lst, PdfObject):
238 result = [lst]
239 elif isinstance(lst, str):
240 if lst[0] == "/":
241 result = [NameObject(lst)]
242 else:
243 result = [TextStringObject(lst)]
244 elif isinstance(lst, bytes):
245 result = [ByteStringObject(lst)]
246 else: # for numbers,...
247 result = [lst]
248 return result
249
250 def __add__(self, lst: Any) -> "ArrayObject":
251 """
252 Allow extension by adding list or add one element only
253
254 Args:
255 lst: any list, tuples are extended the list.
256 other types(numbers,...) will be appended.
257 if str is passed it will be converted into TextStringObject
258 or NameObject (if starting with "/")
259 if bytes is passed it will be converted into ByteStringObject
260
261 Returns:
262 ArrayObject with all elements
263
264 """
265 temp = ArrayObject(self)
266 temp.extend(self._to_lst(lst))
267 return temp
268
269 def __iadd__(self, lst: Any) -> Self:
270 """
271 Allow extension by adding list or add one element only
272
273 Args:
274 lst: any list, tuples are extended the list.
275 other types(numbers,...) will be appended.
276 if str is passed it will be converted into TextStringObject
277 or NameObject (if starting with "/")
278 if bytes is passed it will be converted into ByteStringObject
279
280 """
281 self.extend(self._to_lst(lst))
282 return self
283
284 def __isub__(self, lst: Any) -> Self:
285 """Allow to remove items"""
286 for x in self._to_lst(lst):
287 try:
288 index = self.index(x)
289 del self[index]
290 except ValueError:
291 pass
292 return self
293
294 def write_to_stream(self, stream: StreamType) -> None:
295 stream.write(b"[")
296 for data in self:
297 stream.write(b" ")
298 data.write_to_stream(stream)
299 stream.write(b" ]")
300
301 @staticmethod
302 def _check_limits(*, remaining_elements: int, parsing_budget: StreamParsingBudget | None) -> int:
303 remaining_elements -= 1
304 if remaining_elements < 0:
305 raise LimitReachedError("Reached maximum array element count.")
306 if parsing_budget is not None:
307 parsing_budget.remaining_budget -= 1
308 if parsing_budget.remaining_budget < 0:
309 raise LimitReachedError("Reached maximum number of tokens.")
310 return remaining_elements
311
312 @staticmethod
313 def read_from_stream(
314 stream: StreamType,
315 pdf: PdfReaderProtocol | None,
316 forced_encoding: str | list[str] | dict[int, str] | None = None,
317 *,
318 parsing_budget: StreamParsingBudget | None = None,
319 ) -> "ArrayObject":
320 arr = ArrayObject()
321 tmp = stream.read(1)
322 if tmp != b"[":
323 raise PdfReadError("Could not read array")
324 remaining_elements = get_configuration().array_maximum_element_count
325 while True:
326 # skip leading whitespace
327 tok = stream.read(1)
328 while tok.isspace() or tok in WHITESPACES:
329 tok = stream.read(1)
330 if tok == b"":
331 break
332 if tok == b"%":
333 stream.seek(-1, 1)
334 skip_over_comment(stream)
335 continue
336 # check for array ending
337 if tok == b"]":
338 break
339
340 remaining_elements = ArrayObject._check_limits(
341 remaining_elements=remaining_elements, parsing_budget=parsing_budget
342 )
343 if tok == b"n":
344 # Shortcut for null, as some arrays consist mostly of nulls
345 rest = stream.read(3)
346 if rest == b"ull":
347 arr.append(NullObject())
348 continue
349 stream.seek(-len(rest), 1)
350 stream.seek(-1, 1)
351 # read and append object
352 try:
353 obj = read_object(stream, pdf, forced_encoding, parsing_budget=parsing_budget)
354 except LimitReachedError:
355 # Always propagate security issues.
356 raise
357 except (MemoryError, RecursionError) as exc:
358 raise PdfReadError("Error reading PDF file.") from exc
359 arr.append(obj)
360 return arr
361
362
363@cache
364def _requires_constructor_arguments(cls: type["DictionaryObject"]) -> bool:
365 """Report whether ``cls`` can only be instantiated with arguments."""
366 parameters = inspect.signature(cls.__init__).parameters
367 return any(
368 parameter.default is inspect.Parameter.empty
369 and parameter.kind
370 in (
371 inspect.Parameter.POSITIONAL_ONLY,
372 inspect.Parameter.POSITIONAL_OR_KEYWORD,
373 inspect.Parameter.KEYWORD_ONLY,
374 )
375 for parameter in list(parameters.values())[1:]
376 )
377
378
379class DictionaryObject(dict[Any, Any], PdfObject):
380 def _new_for_clone(self) -> "DictionaryObject":
381 """Create a blank instance of this class to receive cloned entries.
382
383 Most dictionary classes can be instantiated without arguments, but some
384 subclasses - the annotation dictionaries for instance - can only be
385 instantiated with arguments. Those arguments are not needed to receive a
386 clone, because every entry is copied from the source object afterwards,
387 so such classes are instantiated without calling ``__init__``.
388 """
389 if _requires_constructor_arguments(self.__class__):
390 return self.__class__.__new__(self.__class__)
391 return self.__class__()
392
393 def replicate(
394 self,
395 pdf_dest: PdfWriterProtocol,
396 ) -> "DictionaryObject":
397 d__ = cast(
398 "DictionaryObject",
399 self._reference_clone(self._new_for_clone(), pdf_dest, False),
400 )
401 for k, v in self.items():
402 d__[k.replicate(pdf_dest)] = (
403 v.replicate(pdf_dest) if hasattr(v, "replicate") else v
404 )
405 return d__
406
407 def clone(
408 self,
409 pdf_dest: PdfWriterProtocol,
410 force_duplicate: bool = False,
411 ignore_fields: Sequence[str | int] | None = (),
412 ) -> "DictionaryObject":
413 """Clone object into pdf_dest."""
414 try:
415 if self.indirect_reference.pdf == pdf_dest and not force_duplicate: # type: ignore[union-attr]
416 return self
417 except MemoryError: # pragma: no cover # TODO: BLE001
418 raise
419 except Exception:
420 pass
421
422 visited: set[tuple[int, int]] = set() # (idnum, generation)
423 d__ = cast(
424 "DictionaryObject",
425 self._reference_clone(self._new_for_clone(), pdf_dest, force_duplicate),
426 )
427 if ignore_fields is None:
428 ignore_fields = []
429 if len(d__.keys()) == 0:
430 d__._clone(self, pdf_dest, force_duplicate, ignore_fields, visited)
431 return d__
432
433 def _clone(
434 self,
435 src: "DictionaryObject",
436 pdf_dest: PdfWriterProtocol,
437 force_duplicate: bool,
438 ignore_fields: Sequence[str | int] | None,
439 visited: set[tuple[int, int]], # (idnum, generation)
440 ) -> None:
441 """
442 Update the object from src.
443
444 Args:
445 src: "DictionaryObject":
446 pdf_dest:
447 force_duplicate:
448 ignore_fields:
449
450 """
451 # First we remove the ignore_fields
452 # that are for a limited number of levels
453 assert ignore_fields is not None
454 ignore_fields = list(ignore_fields)
455 x = 0
456 while x < len(ignore_fields):
457 if isinstance(ignore_fields[x], int):
458 if cast(int, ignore_fields[x]) <= 0:
459 del ignore_fields[x]
460 del ignore_fields[x]
461 continue
462 ignore_fields[x] -= 1 # type: ignore[operator]
463 x += 1
464 # Check if this is a chain list, we need to loop to prevent recur.
465 # Only indirect objects are chain nodes: a direct dictionary has no
466 # object number for the cycle detection below, so its links are
467 # cloned by the generic loop at the end.
468 if getattr(src, "indirect_reference", None) is not None and any(
469 field not in ignore_fields
470 and field in src
471 and isinstance(src.raw_get(field), IndirectObject)
472 and isinstance(src[field], DictionaryObject)
473 and (
474 src.get("/Type", None) is None
475 or cast(DictionaryObject, src[field]).get("/Type", None) is None
476 or src.get("/Type", None)
477 == cast(DictionaryObject, src[field]).get("/Type", None)
478 )
479 for field in ["/Next", "/Prev", "/N", "/V"]
480 ):
481 ignore_fields = list(ignore_fields)
482 for lst in (("/Next", "/Prev"), ("/N", "/V")):
483 for k in lst:
484 objs = []
485 if (
486 k in src
487 and k not in self
488 and isinstance(src.raw_get(k), IndirectObject)
489 and isinstance(src[k], DictionaryObject)
490 # If need to go further the idea is to check
491 # that the types are the same
492 and (
493 src.get("/Type", None) is None
494 or cast(DictionaryObject, src[k]).get("/Type", None) is None
495 or src.get("/Type", None)
496 == cast(DictionaryObject, src[k]).get("/Type", None)
497 )
498 ):
499 cur_obj: DictionaryObject | None = cast(
500 "DictionaryObject", src[k]
501 )
502 prev_obj: DictionaryObject | None = self
503 while cur_obj is not None:
504 source_reference = getattr(cur_obj, "indirect_reference", None)
505 clon = cast(
506 "DictionaryObject",
507 cur_obj._reference_clone(
508 cur_obj._new_for_clone(), pdf_dest, force_duplicate
509 ),
510 )
511 # Check to see if we've previously processed our item
512 if source_reference is not None:
513 source_idnum = source_reference.idnum
514 source_generation = source_reference.generation
515 if (source_idnum, source_generation) in visited:
516 cur_obj = None
517 break
518 visited.add((source_idnum, source_generation))
519 objs.append((cur_obj, clon))
520 assert prev_obj is not None
521 clone_reference = getattr(clon, "indirect_reference", None)
522 prev_obj[NameObject(k)] = clone_reference if clone_reference is not None else clon
523 prev_obj = clon
524 try:
525 if cur_obj == src:
526 cur_obj = None
527 else:
528 next_obj = cur_obj[k]
529 if isinstance(next_obj, DictionaryObject):
530 cur_obj = next_obj
531 else:
532 cur_obj = None
533 except MemoryError: # pragma: no cover # TODO: BLE001
534 raise
535 except Exception:
536 cur_obj = None
537 for s, c in objs:
538 c._clone(
539 s, pdf_dest, force_duplicate, ignore_fields, visited
540 )
541
542 for k, v in src.items():
543 if k not in ignore_fields:
544 # The type check does not change the result. It only skips the
545 # slower isinstance() check for the most common values.
546 if type(v) not in _SCALAR_TYPES and isinstance(v, StreamObject):
547 if not hasattr(v, "indirect_reference"):
548 v.indirect_reference = None
549 vv = v.clone(pdf_dest, force_duplicate, ignore_fields)
550 assert vv.indirect_reference is not None
551 self[k.clone(pdf_dest)] = vv.indirect_reference
552 elif k not in self:
553 self[NameObject(k)] = (
554 v.clone(pdf_dest, force_duplicate, ignore_fields)
555 if hasattr(v, "clone")
556 else v
557 )
558
559 def hash_bin(self) -> int:
560 """
561 Used to detect modified object.
562
563 Returns:
564 Hash considering type and value.
565
566 """
567 return hash(
568 (self.__class__, tuple(((k, v.hash_bin()) for k, v in self.items())))
569 )
570
571 def raw_get(self, key: Any) -> Any:
572 return dict.__getitem__(self, key)
573
574 def get_inherited(self, key: str, default: Any = None) -> Any:
575 """
576 Returns the value of a key or from the parent if not found.
577 If not found returns default.
578
579 Args:
580 key: string identifying the field to return
581
582 default: default value to return
583
584 Returns:
585 Current key or inherited one, otherwise default value.
586
587 """
588 current = self
589 visited: set[int] = set()
590
591 while True:
592 # Detect cyclic parent references
593 obj_id = id(current)
594 if obj_id in visited:
595 raise LimitReachedError(f"Detected cycle in /Parent hierarchy when retrieving value for key {key!r}.")
596 visited.add(obj_id)
597
598 if key in current:
599 return current[key]
600
601 if "/Parent" not in current:
602 return default
603
604 # Walk upward
605 parent = current["/Parent"].get_object()
606 if not isinstance(parent, DictionaryObject):
607 # A malformed /Parent that does not resolve to a dictionary
608 # terminates the inheritance walk (the key was not found).
609 return default
610 current = parent
611
612 def __setitem__(self, key: Any, value: Any) -> Any:
613 if not isinstance(key, PdfObject):
614 raise TypeError("Key must be a PdfObject")
615 if not isinstance(value, PdfObject):
616 raise TypeError("Value must be a PdfObject")
617 return dict.__setitem__(self, key, value)
618
619 def setdefault(self, key: Any, value: Any | None = None) -> Any:
620 if not isinstance(key, PdfObject):
621 raise TypeError("Key must be a PdfObject")
622 if not isinstance(value, PdfObject):
623 raise TypeError("Value must be a PdfObject")
624 return dict.setdefault(self, key, value)
625
626 def __getitem__(self, key: Any) -> PdfObject:
627 return cast(PdfObject, dict.__getitem__(self, key).get_object())
628
629 @property
630 def xmp_metadata(self) -> XmpInformationProtocol | None:
631 """
632 Retrieve XMP (Extensible Metadata Platform) data relevant to this
633 object, if available.
634
635 See Table 347 — Additional entries in a metadata stream dictionary.
636
637 Returns:
638 Returns a :class:`~pypdf.xmp.XmpInformation` instance
639 that can be used to access XMP metadata from the document. Can also
640 return None if no metadata was found on the document root.
641
642 """
643 from ..xmp import XmpInformation # noqa: PLC0415
644
645 metadata = self.get("/Metadata", None)
646 if is_null_or_none(metadata):
647 return None
648 assert metadata is not None, "mypy"
649 metadata = metadata.get_object()
650 return XmpInformation(metadata)
651
652 def write_to_stream(self, stream: StreamType) -> None:
653 stream.write(b"<<\n")
654 for key, value in self.items():
655 if len(key) > 2 and key[1] == "%" and key[-1] == "%":
656 continue
657 key.write_to_stream(stream)
658 stream.write(b" ")
659 value.write_to_stream(stream)
660 stream.write(b"\n")
661 stream.write(b">>")
662
663 @classmethod
664 def _get_next_object_position(
665 cls, position_before: int, position_end: int, generations: list[int], pdf: PdfReaderProtocol
666 ) -> int:
667 out = position_end
668 for generation in generations:
669 for x in pdf.xref[generation].values():
670 if position_before < x <= position_end:
671 out = min(out, x)
672 return out
673
674 @classmethod
675 def _read_unsized_from_stream(
676 cls, *, stream: BinaryStreamType, pdf: PdfReaderProtocol, length: int,
677 ) -> bytes:
678 current_position = stream.tell()
679
680 # Determine stream size.
681 try:
682 stream.seek(0, os.SEEK_END)
683 stream_length = stream.tell()
684 finally:
685 stream.seek(current_position)
686
687 object_position = cls._get_next_object_position(
688 position_before=current_position, position_end=stream_length, generations=list(pdf.xref), pdf=pdf
689 )
690
691 bytes_to_read = object_position - current_position
692 if bytes_to_read >= length:
693 raise LimitReachedError(f"Requested length of {bytes_to_read} exceeds maximum allowed length.")
694
695 # Read until the next object position.
696 read_value = stream.read(bytes_to_read)
697 endstream_position = read_value.find(b"endstream")
698 if endstream_position < 0:
699 raise PdfReadError(
700 f"Unable to find 'endstream' marker for obj starting at {current_position}."
701 )
702 # 9 = len(b"endstream")
703 stream.seek(current_position + endstream_position + 9)
704 return read_value[: endstream_position - 1]
705
706 @staticmethod
707 def read_from_stream(
708 stream: StreamType,
709 pdf: PdfReaderProtocol | None,
710 forced_encoding: str | list[str] | dict[int, str] | None = None,
711 *,
712 parsing_budget: StreamParsingBudget | None = None,
713 ) -> "DictionaryObject":
714 tmp = stream.read(2)
715 if tmp != b"<<":
716 raise PdfReadError(
717 f"Dictionary read error at byte {hex(stream.tell())}: "
718 "stream must begin with '<<'"
719 )
720 data: dict[Any, Any] = {}
721 remaining_count = get_configuration().dictionary_maximum_element_count
722 while True:
723 tok = read_non_whitespace(stream)
724 if tok == b"%":
725 stream.seek(-1, 1)
726 skip_over_comment(stream)
727 continue
728 if not tok:
729 raise PdfStreamError(STREAM_TRUNCATED_PREMATURELY)
730
731 if tok == b">":
732 stream.read(1)
733 break
734 stream.seek(-1, 1)
735
736 remaining_count -= 1
737 if remaining_count < 0:
738 raise LimitReachedError("Reached maximum number of dictionary entries.")
739 if parsing_budget is not None:
740 parsing_budget.remaining_budget -= 2
741 if parsing_budget.remaining_budget < 0:
742 raise LimitReachedError("Reached maximum number of tokens.")
743
744 try:
745 try:
746 key = read_object(stream, pdf, parsing_budget=parsing_budget)
747 if isinstance(key, NullObject):
748 break
749 if not isinstance(key, NameObject):
750 raise PdfReadError(
751 f"Expecting a NameObject for key but found {key!r}"
752 )
753 except PdfReadError as exc:
754 if pdf is not None and pdf.strict:
755 raise
756 logger_warning("%(exception)r", source=__name__, exception=exc)
757 continue
758 tok = read_non_whitespace(stream)
759 stream.seek(-1, 1)
760 value = read_object(stream, pdf, forced_encoding, parsing_budget=parsing_budget)
761 except LimitReachedError:
762 # Always propagate security issues.
763 raise
764 except (MemoryError, RecursionError) as exc:
765 raise PdfReadError("Error reading PDF file.") from exc
766 except Exception as exc:
767 if pdf is not None and pdf.strict:
768 raise PdfReadError("Error reading PDF file.") from exc
769 logger_warning("%(exception)s", source=__name__, exception=repr(exc)[:500])
770 retval = DictionaryObject()
771 retval.update(data)
772 return retval # return partial data
773
774 if key not in data:
775 data[key] = value
776 else:
777 # multiple definitions of key not permitted
778 msg = (
779 "Multiple definitions in dictionary at byte "
780 "%(position)s for key %(key)s"
781 )
782 values = {"position": hex(stream.tell()), "key": key}
783 if pdf is not None and pdf.strict:
784 raise PdfReadError(msg % values)
785 logger_warning(msg, source=__name__, **values)
786
787 DictionaryObject._read_stream_data(stream=stream, pdf=pdf, data=data)
788 if "__streamdata__" in data:
789 return StreamObject.initialize_from_dictionary(data)
790 retval = DictionaryObject()
791 retval.update(data)
792 return retval
793
794 @staticmethod
795 def _read_stream_data(
796 *,
797 stream: StreamType,
798 pdf: PdfReaderProtocol | None,
799 data: dict[Any, Any]
800 ) -> None:
801 pos = stream.tell()
802 s = read_non_whitespace(stream)
803 if s == b"s" and stream.read(5) == b"tream":
804 eol = stream.read(1)
805 # Occasional PDF file output has spaces after 'stream' keyword but before EOL.
806 # patch provided by Danial Sandler
807 while eol == b" ":
808 eol = stream.read(1)
809 if eol not in (b"\n", b"\r"):
810 raise PdfStreamError("Stream data must be followed by a newline")
811 if eol == b"\r" and stream.read(1) != b"\n":
812 stream.seek(-1, 1)
813 # this is a stream object, not a dictionary
814 if StreamAttributes.LENGTH not in data:
815 if pdf is not None and pdf.strict:
816 raise PdfStreamError("Stream length not defined")
817 logger_warning(
818 "Stream length not defined @pos=%(position)d",
819 source=__name__,
820 position=stream.tell(),
821 )
822 data[NameObject(StreamAttributes.LENGTH)] = NumberObject(-1)
823 length = data[StreamAttributes.LENGTH]
824 if isinstance(length, IndirectObject):
825 t = stream.tell()
826 assert pdf is not None, "mypy"
827 length = pdf.get_object(length)
828 stream.seek(t, 0)
829 if length is None: # if the PDF is damaged
830 length = -1
831 pstart = stream.tell()
832
833 from .._configuration import get_configuration # noqa: PLC0415
834 configuration = get_configuration()
835 if length >= 0:
836 if length > configuration.maximum_declared_stream_length:
837 raise LimitReachedError(f"Declared stream length of {length} exceeds maximum allowed length.")
838
839 data["__streamdata__"] = stream.read(length)
840 else:
841 data["__streamdata__"] = read_until_regex(
842 stream=stream, regex=re.compile(b"endstream"), length=configuration.maximum_declared_stream_length,
843 )
844 e = read_non_whitespace(stream)
845 ndstream = stream.read(8)
846 if (e + ndstream) != b"endstream":
847 # the odd PDF file has a length that is too long, so
848 # we need to read backwards to find the "endstream" ending.
849 # ReportLab (unknown version) generates files with this bug,
850 # and Python users into PDF files tend to be our audience.
851 # we need to do this to correct the streamdata and chop off
852 # an extra character.
853 pos = stream.tell()
854 stream.seek(-10, 1)
855 end = stream.read(9)
856 if end == b"endstream":
857 # we found it by looking back one character further.
858 data["__streamdata__"] = data["__streamdata__"][:-1]
859 elif pdf is not None and not pdf.strict:
860 stream.seek(pstart, 0)
861 data["__streamdata__"] = DictionaryObject._read_unsized_from_stream(
862 stream=stream, pdf=pdf, length=configuration.maximum_declared_stream_length
863 )
864 pos = stream.tell()
865 else:
866 stream.seek(pos, 0)
867 raise PdfReadError(
868 "Unable to find 'endstream' marker after stream at byte "
869 f"{hex(stream.tell())} (nd='{ndstream!r}', end='{end!r}')."
870 )
871 else:
872 stream.seek(pos, 0)
873
874
875class TreeObject(DictionaryObject):
876 def __init__(self, dct: DictionaryObject | None = None) -> None:
877 DictionaryObject.__init__(self)
878 if dct:
879 self.update(dct)
880
881 def has_children(self) -> bool:
882 return "/First" in self
883
884 def __iter__(self) -> Any:
885 return self.children()
886
887 def children(self) -> Iterable[Any]:
888 if not self.has_children():
889 return
890
891 child_ref = self[NameObject("/First")]
892 last = self[NameObject("/Last")]
893 child = child_ref.get_object()
894 visited: set[int] = set()
895 while True:
896 child_id = id(child)
897 if child_id in visited:
898 logger_warning("Detected cycle in outline structure for %(child)s", source=__name__, child=child)
899 return
900 visited.add(child_id)
901
902 yield child
903
904 if child == last:
905 return
906 child_ref = child.get(NameObject("/Next")) # type: ignore[union-attr]
907 if is_null_or_none(child_ref):
908 return
909 child = child_ref.get_object()
910
911 def add_child(self, child: Any, pdf: PdfWriterProtocol) -> None:
912 self.insert_child(child, None, pdf)
913
914 def inc_parent_counter_default(
915 self, parent: Union[IndirectObject, "TreeObject", None], n: int
916 ) -> None:
917 if is_null_or_none(parent):
918 return
919 assert parent is not None, "mypy"
920 parent = cast("TreeObject", parent.get_object())
921 if "/Count" in parent:
922 parent[NameObject("/Count")] = NumberObject(
923 max(0, cast(int, parent[NameObject("/Count")]) + n)
924 )
925 self.inc_parent_counter_default(parent.get("/Parent", None), n)
926
927 def inc_parent_counter_outline(
928 self, parent: Union[IndirectObject, "TreeObject", None], n: int
929 ) -> None:
930 if is_null_or_none(parent):
931 return
932 assert parent is not None, "mypy"
933 parent = cast("TreeObject", parent.get_object())
934 # BooleanObject requires comparison with == not is
935 opn = parent.get("/%is_open%", True) == True # noqa: E712
936 c = cast(int, parent.get("/Count", 0))
937 if c < 0:
938 c = abs(c)
939 parent[NameObject("/Count")] = NumberObject((c + n) * (1 if opn else -1))
940 if not opn:
941 return
942 self.inc_parent_counter_outline(parent.get("/Parent", None), n)
943
944 def insert_child(
945 self,
946 child: Any,
947 before: IndirectObject | None,
948 pdf: PdfWriterProtocol,
949 inc_parent_counter: Callable[..., Any] | None = None,
950 ) -> IndirectObject:
951 if inc_parent_counter is None:
952 inc_parent_counter = self.inc_parent_counter_default
953 child_obj = child.get_object()
954 assert child.indirect_reference is not None, "mypy"
955 child_reference: IndirectObject = child.indirect_reference
956
957 if "/First" not in self: # no child yet
958 self[NameObject("/First")] = child_reference
959 self[NameObject("/Count")] = NumberObject(0)
960 self[NameObject("/Last")] = child_reference
961 child_obj[NameObject("/Parent")] = self.indirect_reference
962 inc_parent_counter(self, child_obj.get("/Count", 1))
963 if "/Next" in child_obj:
964 del child_obj["/Next"]
965 if "/Prev" in child_obj:
966 del child_obj["/Prev"]
967 return child_reference
968 child_obj[NameObject("/Parent")] = self.indirect_reference
969
970 if before is not None:
971 # The children are linked from /First to /Last by /Next (ISO 32000-2:2020, 12.3.3).
972 previous: DictionaryObject | None = None
973 node = cast("DictionaryObject", self["/First"])
974 visited: set[int] = set()
975 while True:
976 if id(node) in visited:
977 raise LimitReachedError("Detected cycle in tree structure.")
978 visited.add(id(node))
979 if node.indirect_reference == before:
980 self._link_child_before(
981 child_obj=child_obj, child_reference=child_reference, previous=previous, node=node
982 )
983 inc_parent_counter(self, child_obj.get("/Count", 1))
984 return child_reference
985 if "/Next" not in node:
986 break
987 previous = node
988 node = cast("DictionaryObject", node["/Next"])
989 # `before` is no child of this node: append at the end.
990
991 last = cast("DictionaryObject", self["/Last"])
992 visited = set()
993 while "/Next" in last:
994 if id(last) in visited:
995 raise LimitReachedError("Detected cycle in tree structure.")
996 visited.add(id(last))
997 last = cast("DictionaryObject", last["/Next"])
998 last[NameObject("/Next")] = child_reference
999 child_obj[NameObject("/Prev")] = last.indirect_reference
1000 child_obj.pop("/Next", None)
1001 self[NameObject("/Last")] = child_reference
1002 inc_parent_counter(self, child_obj.get("/Count", 1))
1003 return child_reference
1004
1005 def _link_child_before(
1006 self,
1007 *,
1008 child_obj: DictionaryObject,
1009 child_reference: IndirectObject,
1010 previous: DictionaryObject | None,
1011 node: DictionaryObject,
1012 ) -> None:
1013 """
1014 Link ``child_obj`` into the list of children directly in front of ``node``.
1015
1016 ``previous`` is the child in front of ``node``, or None if ``node`` is the first child.
1017 """
1018 if previous is None:
1019 self[NameObject("/First")] = child_reference
1020 child_obj.pop("/Prev", None)
1021 else:
1022 previous[NameObject("/Next")] = child_reference
1023 child_obj[NameObject("/Prev")] = previous.indirect_reference
1024 child_obj[NameObject("/Next")] = node.indirect_reference
1025 node[NameObject("/Prev")] = child_reference
1026
1027 def _remove_node_from_tree(
1028 self, *, previous: Any, previous_reference: Any, current: Any, last: Any
1029 ) -> None:
1030 """Adjust the pointers of the linked list and tree node count."""
1031 next_reference = current.get("/Next", None)
1032 if previous is None:
1033 if next_reference:
1034 # Removing first tree node
1035 next_object = next_reference.get_object()
1036 del next_object["/Prev"]
1037 self[NameObject("/First")] = next_reference
1038 self[NameObject("/Count")] = NumberObject(
1039 self[NameObject("/Count")] - 1 # type: ignore[operator]
1040 )
1041
1042 else:
1043 # Removing only tree node
1044 self[NameObject("/Count")] = NumberObject(0)
1045 del self["/First"]
1046 if NameObject("/Last") in self:
1047 del self[NameObject("/Last")]
1048 else:
1049 if next_reference:
1050 # Removing middle tree node
1051 next_object = next_reference.get_object()
1052 next_object[NameObject("/Prev")] = previous_reference
1053 previous[NameObject("/Next")] = next_reference
1054 else:
1055 # Removing last tree node
1056 assert current == last
1057 del previous["/Next"]
1058 self[NameObject("/Last")] = previous_reference
1059 self[NameObject("/Count")] = NumberObject(self["/Count"] - 1) # type: ignore[operator]
1060
1061 def remove_child(self, child: Any) -> None:
1062 child_object = child.get_object()
1063
1064 if "/Parent" not in child_object:
1065 raise ValueError("Removed child does not appear to be a tree item")
1066 if child_object["/Parent"] != self:
1067 raise ValueError("Removed child is not a member of this tree")
1068
1069 found = False
1070 previous_reference = None
1071 previous = None
1072 current_reference: Any | None = self["/First"]
1073 current: dict[str, Any] | None = current_reference.get_object() # type: ignore[union-attr]
1074 last_reference = self["/Last"]
1075 last = last_reference.get_object()
1076 visited: set[int] = set()
1077 while current is not None:
1078 if current == child_object:
1079 TreeObject._remove_node_from_tree(
1080 self, previous=previous, previous_reference=previous_reference, current=current, last=last
1081 )
1082 found = True
1083 break
1084 current_id = id(current)
1085 if current_id in visited:
1086 raise LimitReachedError("Detected cyclic /Next hierarchy.")
1087 visited.add(current_id)
1088
1089 # Go to the next node.
1090 previous_reference = current_reference
1091 previous = current
1092 if "/Next" not in current:
1093 break
1094 current_reference = current["/Next"]
1095 current = current_reference.get_object()
1096
1097 if not found:
1098 raise ValueError("Removal couldn't find item in tree")
1099
1100 _reset_node_tree_relationship(child_object)
1101
1102 def remove_from_tree(self) -> None:
1103 """Remove the object from the tree it is in."""
1104 if "/Parent" not in self:
1105 raise ValueError("Removed child does not appear to be a tree item")
1106 cast("TreeObject", self["/Parent"]).remove_child(self)
1107
1108 def empty_tree(self) -> None:
1109 for child in self:
1110 child_obj = child.get_object()
1111 _reset_node_tree_relationship(child_obj)
1112
1113 if NameObject("/Count") in self:
1114 del self[NameObject("/Count")]
1115 if NameObject("/First") in self:
1116 del self[NameObject("/First")]
1117 if NameObject("/Last") in self:
1118 del self[NameObject("/Last")]
1119
1120
1121def _reset_node_tree_relationship(child_obj: Any) -> None:
1122 """
1123 Call this after a node has been removed from a tree.
1124
1125 This resets the nodes attributes in respect to that tree.
1126
1127 Args:
1128 child_obj:
1129
1130 """
1131 del child_obj[NameObject("/Parent")]
1132 if NameObject("/Next") in child_obj:
1133 del child_obj[NameObject("/Next")]
1134 if NameObject("/Prev") in child_obj:
1135 del child_obj[NameObject("/Prev")]
1136
1137
1138def _iter_name_tree(tree: DictionaryObject) -> Iterator[Any]:
1139 """Yield the nodes of a name tree in key order, each object once, without changing it."""
1140 pending: list[Any] = [tree]
1141 visited: set[int] = set()
1142 while pending:
1143 node = pending.pop(0).get_object()
1144 if id(node) in visited:
1145 continue
1146 visited.add(id(node))
1147 yield node
1148 if not isinstance(node, DictionaryObject):
1149 continue
1150 kids = node.get("/Kids", NullObject()).get_object()
1151 if isinstance(kids, ArrayObject):
1152 pending[:0] = kids
1153
1154
1155def _flatten_name_tree(tree: DictionaryObject, *, maximum_entries: int | None = None) -> ArrayObject:
1156 """
1157 Turn a name tree into a single node holding all its names, in place.
1158
1159 A node holds either /Kids or /Names (ISO 32000-2, 7.9.6), so a name added
1160 next to /Kids would be ignored by readers.
1161
1162 Args:
1163 tree: The name tree root to flatten.
1164 maximum_entries: Optional maximum number of name/value pairs. When set,
1165 raise ``LimitReachedError`` before adding a pair that would exceed it.
1166 """
1167 names = ArrayObject()
1168 remaining_entries = maximum_entries if maximum_entries is not None else sys.maxsize
1169 for node in _iter_name_tree(tree):
1170 if not isinstance(node, DictionaryObject):
1171 continue
1172 node_names = node.get("/Names", NullObject()).get_object()
1173 if not isinstance(node_names, ArrayObject):
1174 continue
1175 remaining_entries -= (len(node_names) // 2)
1176 if remaining_entries < 0:
1177 raise LimitReachedError("Maximum name tree entry limit reached.")
1178 names.extend(node_names)
1179 tree.pop(NameObject("/Kids"), None)
1180 tree.pop(NameObject("/Limits"), None)
1181 tree[NameObject("/Names")] = names
1182 return names
1183
1184
1185class _FontFileEncoding(NamedTuple):
1186 """The encoding pypdf._cmap derived from an embedded font program. See #4156."""
1187 digest: bytes # SHA-256 digest of the decoded font data the encoding was derived from
1188 embedded_font_encoding: dict[int, str]
1189
1190
1191class StreamObject(DictionaryObject):
1192 _font_file_encoding: _FontFileEncoding | None = None
1193 """
1194 The encoding pypdf._cmap derived from this stream as an embedded font program. Parsing a font program
1195 with fontTools is expensive, and the same program is reached from every font resource and page
1196 referencing it. See #4156.
1197 """
1198
1199 def __init__(self) -> None:
1200 self._data: bytes = b""
1201 self.decoded_self: DecodedStreamObject | None = None
1202
1203 def replicate(
1204 self,
1205 pdf_dest: PdfWriterProtocol,
1206 ) -> "StreamObject":
1207 d__ = cast(
1208 "StreamObject",
1209 self._reference_clone(self.__class__(), pdf_dest, False),
1210 )
1211 d__._data = self._data
1212 try:
1213 decoded_self = self.decoded_self
1214 if decoded_self is None:
1215 self.decoded_self = None
1216 else:
1217 self.decoded_self = cast(
1218 "DecodedStreamObject", decoded_self.replicate(pdf_dest)
1219 )
1220 except MemoryError: # pragma: no cover # TODO: BLE001
1221 raise
1222 except Exception:
1223 pass
1224 for k, v in self.items():
1225 d__[k.replicate(pdf_dest)] = (
1226 v.replicate(pdf_dest) if hasattr(v, "replicate") else v
1227 )
1228 return d__
1229
1230 def _clone(
1231 self,
1232 src: DictionaryObject,
1233 pdf_dest: PdfWriterProtocol,
1234 force_duplicate: bool,
1235 ignore_fields: Sequence[str | int] | None,
1236 visited: set[tuple[int, int]],
1237 ) -> None:
1238 """
1239 Update the object from src.
1240
1241 Args:
1242 src:
1243 pdf_dest:
1244 force_duplicate:
1245 ignore_fields:
1246
1247 """
1248 self._data = cast("StreamObject", src)._data
1249 try:
1250 decoded_self = cast("StreamObject", src).decoded_self
1251 if decoded_self is None:
1252 self.decoded_self = None
1253 else:
1254 self.decoded_self = cast(
1255 "DecodedStreamObject",
1256 decoded_self.clone(pdf_dest, force_duplicate, ignore_fields),
1257 )
1258 except MemoryError: # pragma: no cover # TODO: BLE001
1259 raise
1260 except Exception:
1261 pass
1262 super()._clone(src, pdf_dest, force_duplicate, ignore_fields, visited)
1263
1264 def hash_bin(self) -> int:
1265 """
1266 Used to detect modified object.
1267
1268 Returns:
1269 Hash considering type and value.
1270
1271 """
1272 # Use _data to prevent errors on non-decoded streams.
1273 return hash((super().hash_bin(), self._data))
1274
1275 def get_data(self) -> bytes:
1276 return self._data
1277
1278 def set_data(self, data: bytes) -> None:
1279 self._data = data
1280
1281 def hash_value_data(self) -> bytes:
1282 data = super().hash_value_data()
1283 data += self.get_data()
1284 return data
1285
1286 def write_to_stream(self, stream: StreamType) -> None:
1287 self[NameObject(StreamAttributes.LENGTH)] = NumberObject(len(self._data))
1288 DictionaryObject.write_to_stream(self, stream)
1289 del self[StreamAttributes.LENGTH]
1290 stream.write(b"\nstream\n")
1291 stream.write(self._data)
1292 stream.write(b"\nendstream")
1293
1294 @staticmethod
1295 def initialize_from_dictionary(
1296 data: dict[str, Any]
1297 ) -> Union["EncodedStreamObject", "DecodedStreamObject"]:
1298 retval: EncodedStreamObject | DecodedStreamObject
1299 if StreamAttributes.FILTER in data:
1300 retval = EncodedStreamObject()
1301 else:
1302 retval = DecodedStreamObject()
1303 retval._data = data["__streamdata__"]
1304 del data["__streamdata__"]
1305 if StreamAttributes.LENGTH in data:
1306 del data[StreamAttributes.LENGTH]
1307 retval.update(data)
1308 return retval
1309
1310 def flate_encode(self, level: int = -1) -> "EncodedStreamObject":
1311 from ..filters import FlateDecode # noqa: PLC0415
1312
1313 if StreamAttributes.FILTER in self:
1314 f = self[StreamAttributes.FILTER]
1315 if isinstance(f, ArrayObject):
1316 f = ArrayObject([NameObject(FilterTypes.FLATE_DECODE), *f])
1317 try:
1318 params = ArrayObject(
1319 [NullObject(), *self.get(StreamAttributes.DECODE_PARMS, ArrayObject())]
1320 )
1321 except TypeError:
1322 # case of error where the * operator is not working (not an array
1323 params = ArrayObject(
1324 [NullObject(), self.get(StreamAttributes.DECODE_PARMS, ArrayObject())]
1325 )
1326 else:
1327 f = ArrayObject([NameObject(FilterTypes.FLATE_DECODE), f])
1328 params = ArrayObject(
1329 [NullObject(), self.get(StreamAttributes.DECODE_PARMS, NullObject())]
1330 )
1331 else:
1332 f = NameObject(FilterTypes.FLATE_DECODE)
1333 params = None
1334 retval = EncodedStreamObject()
1335 retval.update(self)
1336 retval[NameObject(StreamAttributes.FILTER)] = f
1337 if params is not None:
1338 retval[NameObject(StreamAttributes.DECODE_PARMS)] = params
1339 retval._data = FlateDecode.encode(self._data, level)
1340 return retval
1341
1342 def decode_as_image(self, pillow_parameters: dict[str, Any] | None = None) -> Any:
1343 """
1344 Try to decode the stream object as an image
1345
1346 Args:
1347 pillow_parameters: parameters provided to Pillow Image.save() method,
1348 cf. <https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.save>
1349
1350 Returns:
1351 a PIL image if proper decoding has been found
1352 Raises:
1353 Exception: Errors during decoding will be reported.
1354 It is recommended to catch exceptions to prevent
1355 stops in your program.
1356
1357 """
1358 from ._image_xobject import _xobj_to_image # noqa: PLC0415
1359
1360 if self.get("/Subtype", "") != "/Image":
1361 try:
1362 logger_warning( # pragma: no cover
1363 "%(indirect_reference)s does not seem to be an Image",
1364 source=__name__,
1365 indirect_reference=self.indirect_reference,
1366 )
1367 except AttributeError:
1368 logger_warning( # pragma: no cover
1369 "%(obj)r object does not seem to be an Image",
1370 source=__name__,
1371 obj=self,
1372 )
1373 extension, _, img = _xobj_to_image(self, pillow_parameters)
1374 if extension is None:
1375 return None # pragma: no cover
1376 return img
1377
1378
1379class DecodedStreamObject(StreamObject):
1380 pass
1381
1382
1383class EncodedStreamObject(StreamObject):
1384 def __init__(self) -> None:
1385 self.decoded_self: DecodedStreamObject | None = None
1386
1387 def hash_value_data(self) -> bytes:
1388 # Hash the encoded bytes instead of the decoded data: decoding is slow,
1389 # it keeps a decoded copy of every stream in memory, and it fails for
1390 # streams that cannot be decoded.
1391 #
1392 # Streams with equal dictionaries and equal encoded bytes still get the
1393 # same hash, so PdfWriter.compress_identical_objects() merges them.
1394 # Streams whose decoded data is equal but whose encoded bytes differ,
1395 # for example the same data compressed with two zlib levels, now get
1396 # different hashes and are no longer merged. The output stays correct;
1397 # it is only not as small as it could be. If users want maximum
1398 # compression at the cost of execution time, a parameter such as
1399 # compare_decoded_streams of compress_identical_objects() could add
1400 # back the comparison of the decoded data.
1401 return DictionaryObject.hash_value_data(self) + self._data
1402
1403 # This overrides the parent method
1404 def get_data(self) -> bytes:
1405 from ..filters import decode_stream_data # noqa: PLC0415
1406
1407 if self.decoded_self is not None:
1408 # Cached version of decoded object
1409 return self.decoded_self.get_data()
1410
1411 # Create decoded object
1412 decoded = DecodedStreamObject()
1413 decoded.set_data(decode_stream_data(self))
1414 for key, value in self.items():
1415 if key not in (StreamAttributes.LENGTH, StreamAttributes.FILTER, StreamAttributes.DECODE_PARMS):
1416 decoded[key] = value
1417 self.decoded_self = decoded
1418 return decoded.get_data()
1419
1420 # This overrides the parent method:
1421 def set_data(self, data: bytes) -> None:
1422 from ..filters import FlateDecode # noqa: PLC0415
1423
1424 if self.get(StreamAttributes.FILTER, "") in (FilterTypes.FLATE_DECODE, [FilterTypes.FLATE_DECODE]):
1425 if not isinstance(data, bytes):
1426 raise TypeError("Data must be bytes")
1427 if self.decoded_self is None:
1428 self.get_data() # to create self.decoded_self
1429 assert self.decoded_self is not None, "mypy"
1430 self.decoded_self.set_data(data)
1431 super().set_data(FlateDecode.encode(data))
1432 else:
1433 raise PdfReadError(
1434 "Streams encoded with a filter different from FlateDecode are not supported"
1435 )
1436
1437
1438CONTENT_STREAM_ARRAY_MAX_LENGTH = 10_000
1439
1440
1441class ContentStream(DecodedStreamObject):
1442 """
1443 In order to be fast, this data structure can contain either:
1444
1445 * raw data in ._data
1446 * parsed stream operations in ._operations.
1447
1448 At any time, ContentStream object can either have both of those fields defined,
1449 or one field defined and the other set to None.
1450
1451 These fields are "rebuilt" lazily, when accessed:
1452
1453 * when .get_data() is called, if ._data is None, it is rebuilt from ._operations.
1454 * when .operations is called, if ._operations is None, it is rebuilt from ._data.
1455
1456 Conversely, these fields can be invalidated:
1457
1458 * when .set_data() is called, ._operations is set to None.
1459 * when .operations is set, ._data is set to None.
1460 """
1461 _OPERATOR_LENGTH_LIMIT = 128
1462
1463 def __init__(
1464 self,
1465 stream: Any,
1466 pdf: Any,
1467 forced_encoding: str | list[str] | dict[int, str] | None = None,
1468 ) -> None:
1469 self.pdf = pdf
1470 self._operations: list[tuple[Any, bytes]] = []
1471
1472 # stream may be a StreamObject or an ArrayObject containing
1473 # StreamObjects to be concatenated together.
1474 if stream is None:
1475 super().set_data(b"")
1476 else:
1477 stream = stream.get_object()
1478 if isinstance(stream, ArrayObject):
1479 from pypdf._configuration import get_configuration # noqa: PLC0415
1480 configuration = get_configuration()
1481
1482 if (stream_length := len(stream)) > CONTENT_STREAM_ARRAY_MAX_LENGTH:
1483 raise LimitReachedError(
1484 f"Array-based stream has {stream_length} > {CONTENT_STREAM_ARRAY_MAX_LENGTH} elements."
1485 )
1486 data = bytearray()
1487 length = 0
1488 for s in stream:
1489 s_resolved = s.get_object()
1490 if isinstance(s_resolved, NullObject):
1491 continue
1492 if not isinstance(s_resolved, StreamObject):
1493 # No need to emit an exception here for now - the PDF structure
1494 # seems to already be broken beforehand in these cases.
1495 logger_warning(
1496 "Expected StreamObject, got %(type_name)s instead. Data might be wrong.",
1497 source=__name__,
1498 type_name=type(s_resolved).__name__,
1499 )
1500 else:
1501 new_data = s_resolved.get_data()
1502 length += len(new_data)
1503 if length > configuration.array_based_stream_maximum_output_length:
1504 raise LimitReachedError(
1505 f"Array-based stream has at least {length} > "
1506 f"{configuration.array_based_stream_maximum_output_length} output bytes."
1507 )
1508 data += new_data
1509 if len(data) == 0 or data[-1:] != b"\n":
1510 # There should be no direct need to check for a change of one byte.
1511 length += 1
1512 data += b"\n"
1513 super().set_data(bytes(data))
1514 else:
1515 stream_data = stream.get_data()
1516 assert stream_data is not None
1517 super().set_data(stream_data)
1518 self.forced_encoding = forced_encoding
1519
1520 def replicate(
1521 self,
1522 pdf_dest: PdfWriterProtocol,
1523 ) -> "ContentStream":
1524 d__ = cast(
1525 "ContentStream",
1526 self._reference_clone(self.__class__(None, None), pdf_dest, False),
1527 )
1528 d__._data = self._data
1529 try:
1530 decoded_self = self.decoded_self
1531 if decoded_self is None:
1532 self.decoded_self = None
1533 else:
1534 self.decoded_self = cast(
1535 "DecodedStreamObject", decoded_self.replicate(pdf_dest)
1536 )
1537 except MemoryError: # pragma: no cover # TODO: BLE001
1538 raise
1539 except Exception:
1540 pass
1541 for k, v in self.items():
1542 d__[k.replicate(pdf_dest)] = (
1543 v.replicate(pdf_dest) if hasattr(v, "replicate") else v
1544 )
1545 d__.pdf = pdf_dest
1546 d__._operations = list(self._operations)
1547 d__.forced_encoding = self.forced_encoding
1548 return d__
1549
1550 def clone(
1551 self,
1552 pdf_dest: Any,
1553 force_duplicate: bool = False,
1554 ignore_fields: Sequence[str | int] | None = (),
1555 ) -> "ContentStream":
1556 """
1557 Clone object into pdf_dest.
1558
1559 Args:
1560 pdf_dest:
1561 force_duplicate:
1562 ignore_fields:
1563
1564 Returns:
1565 The cloned ContentStream
1566
1567 """
1568 try:
1569 if self.indirect_reference.pdf == pdf_dest and not force_duplicate: # type: ignore[union-attr]
1570 return self
1571 except MemoryError: # pragma: no cover # TODO: BLE001
1572 raise
1573 except Exception:
1574 pass
1575
1576 visited: set[tuple[int, int]] = set()
1577 d__ = cast(
1578 "ContentStream",
1579 self._reference_clone(
1580 self.__class__(None, None), pdf_dest, force_duplicate
1581 ),
1582 )
1583 if ignore_fields is None:
1584 ignore_fields = []
1585 d__._clone(self, pdf_dest, force_duplicate, ignore_fields, visited)
1586 return d__
1587
1588 def _clone(
1589 self,
1590 src: DictionaryObject,
1591 pdf_dest: PdfWriterProtocol,
1592 force_duplicate: bool,
1593 ignore_fields: Sequence[str | int] | None,
1594 visited: set[tuple[int, int]],
1595 ) -> None:
1596 """
1597 Update the object from src.
1598
1599 Args:
1600 src:
1601 pdf_dest:
1602 force_duplicate:
1603 ignore_fields:
1604
1605 """
1606 src_cs = cast("ContentStream", src)
1607 super().set_data(src_cs._data)
1608 self.pdf = pdf_dest
1609 self._operations = list(src_cs._operations)
1610 self.forced_encoding = src_cs.forced_encoding
1611 # no need to call DictionaryObjection or anything
1612 # like super(DictionaryObject,self)._clone(src, pdf_dest, force_duplicate, ignore_fields, visited)
1613
1614 @staticmethod
1615 def _check_limits(
1616 *,
1617 remaining_elements: int | None = None,
1618 parsing_budget: StreamParsingBudget,
1619 token_decrement: int
1620 ) -> int | None:
1621 if remaining_elements is not None:
1622 remaining_elements -= 1
1623 if remaining_elements < 0:
1624 raise LimitReachedError("Reached maximum number of tokens.")
1625 parsing_budget.remaining_budget -= token_decrement
1626 if parsing_budget.remaining_budget < 0:
1627 raise LimitReachedError("Reached maximum number of tokens per stream.")
1628 return remaining_elements
1629
1630 def _parse_content_stream(self, stream: StreamType) -> None:
1631 # 7.8.2 Content Streams
1632 stream.seek(0, 0)
1633 data = stream.read()
1634 position = 0
1635 operands: list[int | str | PdfObject] = []
1636 parsing_budget = StreamParsingBudget(remaining_budget=get_configuration().stream_parsing_work_maximum_count)
1637 while True:
1638 match = _CONTENT_STREAM_SIMPLE_TOKEN.match(data, position)
1639 if match is not None:
1640 self._check_limits(parsing_budget=parsing_budget, token_decrement=1)
1641 position = match.end()
1642 float_value, int_value, name, operator = match.groups()
1643 if operator is not None:
1644 self._operations.append((operands, operator))
1645 operands = []
1646 # Only valid numbers are matched, thus skip the error handling
1647 # of the constructors, which is costly for millions of numbers.
1648 elif float_value is not None:
1649 operands.append(float.__new__(FloatObject, float_value))
1650 elif int_value is not None:
1651 operands.append(int.__new__(NumberObject, int_value))
1652 else:
1653 operands.append(NameObject(name.decode()))
1654 continue
1655
1656 stream.seek(position, 0)
1657 peek = read_non_whitespace(stream)
1658 if peek in (b"", 0):
1659 break
1660 stream.seek(-1, 1)
1661 if peek.isalpha() or peek in (b"'", b'"'):
1662 operator = read_until_regex(
1663 stream=stream, regex=NameObject.delimiter_pattern, length=self._OPERATOR_LENGTH_LIMIT
1664 )
1665 if operator == b"BI":
1666 # begin inline image - a completely different parsing
1667 # mechanism is required, of course... thanks buddy...
1668 assert operands == []
1669 self._check_limits(parsing_budget=parsing_budget, token_decrement=2)
1670
1671 from ._image_inline import read_inline_image # noqa: PLC0415
1672 ii = read_inline_image(content_stream=self, stream=stream, parsing_budget=parsing_budget)
1673 self._operations.append((ii, b"INLINE IMAGE"))
1674 else:
1675 self._check_limits(parsing_budget=parsing_budget, token_decrement=1)
1676 self._operations.append((operands, operator))
1677 operands = []
1678 elif peek == b"%":
1679 # If we encounter a comment in the content stream, we have to
1680 # handle it here. Typically, read_object will handle
1681 # encountering a comment -- but read_object assumes that
1682 # following the comment must be the object we're trying to
1683 # read. In this case, it could be an operator instead.
1684 while peek not in (b"\r", b"\n", b""):
1685 peek = stream.read(1)
1686 else:
1687 self._check_limits(parsing_budget=parsing_budget, token_decrement=1)
1688 operands.append(read_object(stream, None, self.forced_encoding, parsing_budget=parsing_budget))
1689 position = stream.tell()
1690
1691 # This overrides the parent method
1692 def get_data(self) -> bytes:
1693 if not self._data:
1694 new_data = BytesIO()
1695 for operands, operator in self._operations:
1696 if operator == b"INLINE IMAGE":
1697 new_data.write(b"BI")
1698 dict_text = BytesIO()
1699 operands["settings"].write_to_stream(dict_text)
1700 new_data.write(dict_text.getvalue()[2:-2])
1701 new_data.write(b"ID ")
1702 new_data.write(operands["data"])
1703 new_data.write(b"EI")
1704 else:
1705 for op in operands:
1706 op.write_to_stream(new_data)
1707 new_data.write(b" ")
1708 new_data.write(operator)
1709 new_data.write(b"\n")
1710 self._data = new_data.getvalue()
1711 return self._data
1712
1713 # This overrides the parent method
1714 def set_data(self, data: bytes) -> None:
1715 super().set_data(data)
1716 self._operations = []
1717
1718 @property
1719 def operations(self) -> list[tuple[Any, bytes]]:
1720 if not self._operations and self._data:
1721 self._parse_content_stream(BytesIO(self._data))
1722 self._data = b""
1723 return self._operations
1724
1725 @operations.setter
1726 def operations(self, operations: list[tuple[Any, bytes]]) -> None:
1727 self._operations = operations
1728 self._data = b""
1729
1730 def isolate_graphics_state(self) -> None:
1731 if self._operations:
1732 self._operations.insert(0, ([], b"q"))
1733 self._operations.append(([], b"Q"))
1734 elif self._data:
1735 self._data = b"q\n" + self._data + b"\nQ\n"
1736
1737 # This overrides the parent method
1738 def write_to_stream(
1739 self, stream: StreamType, encryption_key: str | bytes | None = None
1740 ) -> None:
1741 """
1742 Write the content stream to the stream.
1743
1744 Args:
1745 stream: The stream to write to.
1746 encryption_key: Ignored. The writer encrypts the objects before it
1747 writes them.
1748
1749 .. deprecated:: 7.2.0
1750 The ``encryption_key`` parameter is deprecated and will be removed
1751 in pypdf 8.0.0. It has no effect.
1752
1753 """
1754 if encryption_key is not None:
1755 deprecate_no_replacement("The encryption_key parameter of ContentStream.write_to_stream()", "8.0.0")
1756 if not self._data and self._operations:
1757 self.get_data() # this ensures ._data is rebuilt
1758 super().write_to_stream(stream)
1759
1760
1761# Bound comment scanning without consuming Python recursion depth.
1762_MAX_LEADING_COMMENTS = 1000
1763
1764
1765def read_object( # noqa: PLR0911
1766 stream: StreamType,
1767 pdf: PdfReaderProtocol | None,
1768 forced_encoding: str | list[str] | dict[int, str] | None = None,
1769 *,
1770 parsing_budget: StreamParsingBudget | None = None,
1771) -> PdfObject:
1772 """
1773 Read the next object from the stream.
1774
1775 Args:
1776 stream: The stream to read from.
1777 pdf: The corresponding PDF file.
1778 forced_encoding: The encoding to enforce, if any.
1779 parsing_budget: The allowed parsing budget, optional. If set, only applies to dictionaries,
1780 arrays and content streams.
1781
1782 Returns:
1783 The parsed object.
1784 """
1785 tok = stream.read(1)
1786 stream.seek(-1, 1) # reset to start
1787 if tok == b"%":
1788 # Skip consecutive comments in a loop instead of recursing per comment.
1789 skip_over_comments(stream, limit=_MAX_LEADING_COMMENTS)
1790 tok = stream.read(1)
1791 stream.seek(-1, 1) # reset to start
1792 if tok == b"/":
1793 return NameObject.read_from_stream(stream, pdf)
1794 if tok == b"<":
1795 # hexadecimal string OR dictionary
1796 peek = stream.read(2)
1797 stream.seek(-2, 1) # reset to start
1798 if peek == b"<<":
1799 return DictionaryObject.read_from_stream(stream, pdf, forced_encoding, parsing_budget=parsing_budget)
1800 return read_hex_string_from_stream(stream, forced_encoding)
1801 if tok == b"[":
1802 return ArrayObject.read_from_stream(stream, pdf, forced_encoding, parsing_budget=parsing_budget)
1803 if tok in (b"t", b"f"):
1804 return BooleanObject.read_from_stream(stream)
1805 if tok == b"(":
1806 return read_string_from_stream(stream, forced_encoding)
1807 if tok == b"e" and stream.read(6) == b"endobj":
1808 return NullObject()
1809 if tok == b"n":
1810 return NullObject.read_from_stream(stream)
1811 if tok in b"0123456789+-.":
1812 # number object OR indirect reference
1813 peek = stream.read(20)
1814 match = IndirectPattern.match(peek)
1815 if match is not None:
1816 assert pdf is not None, "mypy"
1817 # Continue after the "R", the match includes the character following it
1818 stream.seek(match.end() - 1 - len(peek), 1)
1819 # The object number includes an optional sign
1820 return IndirectObject(int(peek[: match.end(1)]), int(match[2]), pdf)
1821 number_end = NumberObject.NumberPattern.search(peek)
1822 if number_end is not None:
1823 # The whole number is in the peek, there is no need to read it again
1824 num = peek[: number_end.start()]
1825 stream.seek(len(num) - len(peek), 1)
1826 if b"." in num:
1827 return FloatObject(num)
1828 return NumberObject(num)
1829 stream.seek(-len(peek), 1) # reset to start
1830 return NumberObject.read_from_stream(stream)
1831 pos = stream.tell()
1832 stream.seek(-20, 1)
1833 stream_extract = stream.read(80)
1834 stream.seek(pos)
1835 read_until_whitespace(stream)
1836 raise PdfReadError(
1837 f"Invalid Elementary Object starting with {tok!r} @{pos}: {stream_extract!r}"
1838 )
1839
1840
1841class Field(TreeObject):
1842 """
1843 A class representing a field dictionary.
1844
1845 This class is accessed through
1846 :meth:`get_fields()<pypdf.PdfReader.get_fields>`
1847 """
1848
1849 def __init__(self, data: DictionaryObject) -> None:
1850 DictionaryObject.__init__(self)
1851 field_attributes = (
1852 FieldDictionaryAttributes.attributes()
1853 + CheckboxRadioButtonAttributes.attributes()
1854 )
1855 self.indirect_reference = data.indirect_reference
1856 for attr in field_attributes:
1857 with contextlib.suppress(KeyError):
1858 self[NameObject(attr)] = data[attr]
1859 if isinstance(self.get("/V"), EncodedStreamObject):
1860 value = cast(EncodedStreamObject, self[NameObject("/V")]).get_data()
1861 self[NameObject("/V")] = TextStringObject(value.decode())
1862
1863 # TABLE 8.69 Entries common to all field dictionaries
1864 @property
1865 def field_type(self) -> NameObject | None:
1866 """Read-only property accessing the type of this field."""
1867 return self.get(FieldDictionaryAttributes.FT)
1868
1869 @property
1870 def parent(self) -> DictionaryObject | None:
1871 """Read-only property accessing the parent of this field."""
1872 return self.get(FieldDictionaryAttributes.Parent)
1873
1874 @property
1875 def kids(self) -> Optional["ArrayObject"]:
1876 """Read-only property accessing the kids of this field."""
1877 return self.get(FieldDictionaryAttributes.Kids)
1878
1879 @property
1880 def name(self) -> str | None:
1881 """Read-only property accessing the name of this field."""
1882 return self.get(FieldDictionaryAttributes.T)
1883
1884 @property
1885 def alternate_name(self) -> str | None:
1886 """Read-only property accessing the alternate name of this field."""
1887 return self.get(FieldDictionaryAttributes.TU)
1888
1889 @property
1890 def mapping_name(self) -> str | None:
1891 """
1892 Read-only property accessing the mapping name of this field.
1893
1894 This name is used by pypdf as a key in the dictionary returned by
1895 :meth:`get_fields()<pypdf.PdfReader.get_fields>`
1896 """
1897 return self.get(FieldDictionaryAttributes.TM)
1898
1899 @property
1900 def flags(self) -> int | None:
1901 """
1902 Read-only property accessing the field flags, specifying various
1903 characteristics of the field (see Table 8.70 of the PDF 1.7 reference).
1904 """
1905 return self.get(FieldDictionaryAttributes.Ff)
1906
1907 @property
1908 def value(self) -> Any | None:
1909 """
1910 Read-only property accessing the value of this field.
1911
1912 Format varies based on field type.
1913 """
1914 return self.get(FieldDictionaryAttributes.V)
1915
1916 @property
1917 def default_value(self) -> Any | None:
1918 """Read-only property accessing the default value of this field."""
1919 return self.get(FieldDictionaryAttributes.DV)
1920
1921 @property
1922 def additional_actions(self) -> DictionaryObject | None:
1923 """
1924 Read-only property accessing the additional actions dictionary.
1925
1926 This dictionary defines the field's behavior in response to trigger
1927 events. See Section 8.5.2 of the PDF 1.7 reference.
1928 """
1929 return self.get(FieldDictionaryAttributes.AA)
1930
1931
1932class Destination(TreeObject):
1933 """
1934 A class representing a destination within a PDF file.
1935
1936 See section 12.3.2 of the PDF 2.0 reference.
1937
1938 Args:
1939 title: Title of this destination.
1940 page: Reference to the page of this destination. Should
1941 be an instance of :class:`IndirectObject<pypdf.generic.IndirectObject>`.
1942 fit: How the destination is displayed.
1943
1944 Raises:
1945 PdfReadError: If destination type is invalid.
1946
1947 """
1948
1949 node: DictionaryObject | None = None # node provide access to the original Object
1950
1951 def remove_from_tree(self) -> None:
1952 """
1953 Remove the outline item this destination was built from.
1954
1955 `reader.outline` and `writer.outline` yield detached copies rather than
1956 the nodes themselves, so the copy never has a `/Parent` and removing it
1957 would be a no-op. `node` is the dictionary in the document.
1958 """
1959 if self.node is None:
1960 super().remove_from_tree()
1961 elif "/Parent" not in self.node:
1962 raise ValueError("Removed child does not appear to be a tree item")
1963 else:
1964 TreeObject.remove_child(
1965 cast("TreeObject", self.node["/Parent"]), self.node
1966 )
1967
1968 def __init__(
1969 self,
1970 title: str | bytes,
1971 page: NumberObject | IndirectObject | NullObject | DictionaryObject,
1972 fit: Fit,
1973 ) -> None:
1974 self._filtered_children: list[Any] = [] # used in PdfWriter
1975
1976 typ = fit.fit_type
1977 args = fit.fit_args
1978
1979 DictionaryObject.__init__(self)
1980 self[NameObject("/Title")] = TextStringObject(title)
1981 self[NameObject("/Page")] = page
1982 self[NameObject("/Type")] = typ
1983
1984 # from table 8.2 of the PDF 1.7 reference.
1985 if typ == "/XYZ":
1986 if len(args) < 1: # left is missing : should never occur
1987 args.append(NumberObject(0.0))
1988 if len(args) < 2: # top is missing
1989 args.append(NumberObject(0.0))
1990 if len(args) < 3: # zoom is missing
1991 args.append(NumberObject(0.0))
1992 # surplus arguments are ignored rather than failing the unpacking
1993 (
1994 self[NameObject(TypArguments.LEFT)],
1995 self[NameObject(TypArguments.TOP)],
1996 self[NameObject("/Zoom")],
1997 ) = args[:3]
1998 elif len(args) == 0:
1999 pass
2000 elif typ == TypFitArguments.FIT_R:
2001 if len(args) == 4: # a wrong number of arguments degrades to null
2002 (
2003 self[NameObject(TypArguments.LEFT)],
2004 self[NameObject(TypArguments.BOTTOM)],
2005 self[NameObject(TypArguments.RIGHT)],
2006 self[NameObject(TypArguments.TOP)],
2007 ) = args
2008 else:
2009 (
2010 self[NameObject(TypArguments.LEFT)],
2011 self[NameObject(TypArguments.BOTTOM)],
2012 self[NameObject(TypArguments.RIGHT)],
2013 self[NameObject(TypArguments.TOP)],
2014 ) = (NullObject(), NullObject(), NullObject(), NullObject())
2015 elif typ in [TypFitArguments.FIT_H, TypFitArguments.FIT_BH]:
2016 try: # Prefer to be more robust not only to null parameters
2017 (self[NameObject(TypArguments.TOP)],) = args
2018 except MemoryError: # pragma: no cover # TODO: BLE001
2019 raise
2020 except Exception:
2021 (self[NameObject(TypArguments.TOP)],) = (NullObject(),)
2022 elif typ in [TypFitArguments.FIT_V, TypFitArguments.FIT_BV]:
2023 try: # Prefer to be more robust not only to null parameters
2024 (self[NameObject(TypArguments.LEFT)],) = args
2025 except MemoryError: # pragma: no cover # TODO: BLE001
2026 raise
2027 except Exception:
2028 (self[NameObject(TypArguments.LEFT)],) = (NullObject(),)
2029 elif typ in [TypFitArguments.FIT, TypFitArguments.FIT_B]:
2030 pass
2031 else:
2032 raise PdfReadError(f"Unknown Destination Type: {typ!r}")
2033
2034 @property
2035 def dest_array(self) -> "ArrayObject":
2036 return ArrayObject(
2037 [self.raw_get("/Page"), self["/Type"]]
2038 + [
2039 self[x]
2040 for x in ["/Left", "/Bottom", "/Right", "/Top", "/Zoom"]
2041 if x in self
2042 ]
2043 )
2044
2045 def write_to_stream(self, stream: StreamType) -> None:
2046 stream.write(b"<<\n")
2047 key = NameObject("/D")
2048 key.write_to_stream(stream)
2049 stream.write(b" ")
2050 value = self.dest_array
2051 value.write_to_stream(stream)
2052
2053 key = NameObject("/S")
2054 key.write_to_stream(stream)
2055 stream.write(b" ")
2056 value_s = NameObject("/GoTo")
2057 value_s.write_to_stream(stream)
2058
2059 stream.write(b"\n")
2060 stream.write(b">>")
2061
2062 @property
2063 def title(self) -> str | None:
2064 """Read-only property accessing the destination title."""
2065 return self.get("/Title")
2066
2067 @property
2068 def page(self) -> IndirectObject | None:
2069 """Read-only property accessing the IndirectObject of the destination page."""
2070 return self.get("/Page")
2071
2072 @property
2073 def typ(self) -> str | None:
2074 """Read-only property accessing the destination type."""
2075 return self.get("/Type")
2076
2077 @property
2078 def zoom(self) -> int | None:
2079 """Read-only property accessing the zoom factor."""
2080 return self.get("/Zoom", None)
2081
2082 @property
2083 def left(self) -> FloatObject | None:
2084 """Read-only property accessing the left horizontal coordinate."""
2085 return self.get("/Left", None)
2086
2087 @property
2088 def right(self) -> FloatObject | None:
2089 """Read-only property accessing the right horizontal coordinate."""
2090 return self.get("/Right", None)
2091
2092 @property
2093 def top(self) -> FloatObject | None:
2094 """Read-only property accessing the top vertical coordinate."""
2095 return self.get("/Top", None)
2096
2097 @property
2098 def bottom(self) -> FloatObject | None:
2099 """Read-only property accessing the bottom vertical coordinate."""
2100 return self.get("/Bottom", None)
2101
2102 @property
2103 def color(self) -> Optional["ArrayObject"]:
2104 """Read-only property accessing the color in (R, G, B) with values 0.0-1.0."""
2105 return cast(
2106 "ArrayObject",
2107 self.get("/C", ArrayObject([FloatObject(0), FloatObject(0), FloatObject(0)])),
2108 )
2109
2110 @property
2111 def font_format(self) -> OutlineFontFlag | None:
2112 """
2113 Read-only property accessing the font type.
2114
2115 1=italic, 2=bold, 3=both
2116 """
2117 return OutlineFontFlag(self.get("/F", 0))
2118
2119 @property
2120 def outline_count(self) -> int | None:
2121 """
2122 Read-only property accessing the outline count.
2123
2124 positive = expanded
2125 negative = collapsed
2126 absolute value = number of visible descendants at all levels
2127 """
2128 return self.get("/Count", None)