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