/
generic.py
1989 lines (1713 loc) · 69.1 KB
/
generic.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2006, Mathieu Fenniak
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * The name of the author may not be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""Implementation of generic PDF objects (dictionary, number, string, ...)."""
__author__ = "Mathieu Fenniak"
__author_email__ = "biziqe@mathieu.fenniak.net"
import codecs
import decimal
import hashlib
import logging
import re
import warnings
from io import BytesIO
from typing import Any, Callable, Dict, List, Optional, Tuple, Union, cast
from ._codecs import ( # noqa: rev_encoding
_pdfdoc_encoding,
_pdfdoc_encoding_rev,
rev_encoding,
)
from ._utils import (
WHITESPACES,
StreamType,
b_,
bytes_type,
deprecate_no_replacement,
deprecate_with_replacement,
hex_str,
hexencode,
read_non_whitespace,
read_until_regex,
skip_over_comment,
str_,
)
from .constants import FieldDictionaryAttributes
from .constants import FilterTypes as FT
from .constants import StreamAttributes as SA
from .constants import TypArguments as TA
from .constants import TypFitArguments as TF
from .errors import (
STREAM_TRUNCATED_PREMATURELY,
PdfReadError,
PdfReadWarning,
PdfStreamError,
)
logger = logging.getLogger(__name__)
ObjectPrefix = b"/<[tf(n%"
NumberSigns = b"+-"
IndirectPattern = re.compile(rb"[+-]?(\d+)\s+(\d+)\s+R[^a-zA-Z]")
class PdfObject:
# function for calculating a hash value
hash_func: Callable[..., "hashlib._Hash"] = hashlib.sha1
def hash_value_data(self) -> bytes:
return ("%s" % self).encode()
def hash_value(self) -> bytes:
return (
"%s:%s"
% (
self.__class__.__name__,
self.hash_func(self.hash_value_data()).hexdigest(),
)
).encode()
def get_object(self) -> Optional["PdfObject"]:
"""Resolve indirect references."""
return self
def getObject(self) -> Optional["PdfObject"]: # pragma: no cover
deprecate_with_replacement("getObject", "get_object")
return self.get_object()
def write_to_stream(
self, stream: StreamType, encryption_key: Union[None, str, bytes]
) -> None:
raise NotImplementedError
class NullObject(PdfObject):
def write_to_stream(
self, stream: StreamType, encryption_key: Union[None, str, bytes]
) -> None:
stream.write(b"null")
@staticmethod
def read_from_stream(stream: StreamType) -> "NullObject":
nulltxt = stream.read(4)
if nulltxt != b"null":
raise PdfReadError("Could not read Null object")
return NullObject()
def writeToStream(
self, stream: StreamType, encryption_key: Union[None, str, bytes]
) -> None: # pragma: no cover
deprecate_with_replacement("writeToStream", "write_to_stream")
self.write_to_stream(stream, encryption_key)
@staticmethod
def readFromStream(stream: StreamType) -> "NullObject": # pragma: no cover
deprecate_with_replacement("readFromStream", "read_from_stream")
return NullObject.read_from_stream(stream)
class BooleanObject(PdfObject):
def __init__(self, value: Any) -> None:
self.value = value
def __eq__(self, __o: object) -> bool:
if isinstance(__o, BooleanObject):
return self.value == __o.value
elif isinstance(__o, bool):
return self.value == __o
else:
return False
def __repr__(self) -> str:
return "True" if self.value else "False"
def write_to_stream(
self, stream: StreamType, encryption_key: Union[None, str, bytes]
) -> None:
if self.value:
stream.write(b"true")
else:
stream.write(b"false")
def writeToStream(
self, stream: StreamType, encryption_key: Union[None, str, bytes]
) -> None: # pragma: no cover
deprecate_with_replacement("writeToStream", "write_to_stream")
self.write_to_stream(stream, encryption_key)
@staticmethod
def read_from_stream(stream: StreamType) -> "BooleanObject":
word = stream.read(4)
if word == b"true":
return BooleanObject(True)
elif word == b"fals":
stream.read(1)
return BooleanObject(False)
else:
raise PdfReadError("Could not read Boolean object")
@staticmethod
def readFromStream(stream: StreamType) -> "BooleanObject": # pragma: no cover
deprecate_with_replacement("readFromStream", "read_from_stream")
return BooleanObject.read_from_stream(stream)
class ArrayObject(list, PdfObject):
def write_to_stream(
self, stream: StreamType, encryption_key: Union[None, str, bytes]
) -> None:
stream.write(b"[")
for data in self:
stream.write(b" ")
data.write_to_stream(stream, encryption_key)
stream.write(b" ]")
def writeToStream(
self, stream: StreamType, encryption_key: Union[None, str, bytes]
) -> None: # pragma: no cover
deprecate_with_replacement("writeToStream", "write_to_stream")
self.write_to_stream(stream, encryption_key)
@staticmethod
def read_from_stream(
stream: StreamType,
pdf: Any,
forced_encoding: Union[None, str, List[str], Dict[int, str]] = None,
) -> "ArrayObject": # PdfReader
arr = ArrayObject()
tmp = stream.read(1)
if tmp != b"[":
raise PdfReadError("Could not read array")
while True:
# skip leading whitespace
tok = stream.read(1)
while tok.isspace():
tok = stream.read(1)
stream.seek(-1, 1)
# check for array ending
peekahead = stream.read(1)
if peekahead == b"]":
break
stream.seek(-1, 1)
# read and append obj
arr.append(read_object(stream, pdf, forced_encoding))
return arr
@staticmethod
def readFromStream(
stream: StreamType, pdf: Any # PdfReader
) -> "ArrayObject": # pragma: no cover
deprecate_with_replacement("readFromStream", "read_from_stream")
return ArrayObject.read_from_stream(stream, pdf)
class IndirectObject(PdfObject):
def __init__(self, idnum: int, generation: int, pdf: Any) -> None: # PdfReader
self.idnum = idnum
self.generation = generation
self.pdf = pdf
def get_object(self) -> Optional[PdfObject]:
obj = self.pdf.get_object(self)
if obj is None:
return None
return obj.get_object()
def __repr__(self) -> str:
return f"IndirectObject({self.idnum!r}, {self.generation!r})"
def __eq__(self, other: Any) -> bool:
return (
other is not None
and isinstance(other, IndirectObject)
and self.idnum == other.idnum
and self.generation == other.generation
and self.pdf is other.pdf
)
def __ne__(self, other: Any) -> bool:
return not self.__eq__(other)
def write_to_stream(
self, stream: StreamType, encryption_key: Union[None, str, bytes]
) -> None:
stream.write(b_(f"{self.idnum} {self.generation} R"))
def writeToStream(
self, stream: StreamType, encryption_key: Union[None, str, bytes]
) -> None: # pragma: no cover
deprecate_with_replacement("writeToStream", "write_to_stream")
self.write_to_stream(stream, encryption_key)
@staticmethod
def read_from_stream(stream: StreamType, pdf: Any) -> "IndirectObject": # PdfReader
idnum = b""
while True:
tok = stream.read(1)
if not tok:
raise PdfStreamError(STREAM_TRUNCATED_PREMATURELY)
if tok.isspace():
break
idnum += tok
generation = b""
while True:
tok = stream.read(1)
if not tok:
raise PdfStreamError(STREAM_TRUNCATED_PREMATURELY)
if tok.isspace():
if not generation:
continue
break
generation += tok
r = read_non_whitespace(stream)
if r != b"R":
raise PdfReadError(
f"Error reading indirect object reference at byte {hex_str(stream.tell())}"
)
return IndirectObject(int(idnum), int(generation), pdf)
@staticmethod
def readFromStream(
stream: StreamType, pdf: Any # PdfReader
) -> "IndirectObject": # pragma: no cover
deprecate_with_replacement("readFromStream", "read_from_stream")
return IndirectObject.read_from_stream(stream, pdf)
class FloatObject(decimal.Decimal, PdfObject):
def __new__(
cls, value: Union[str, Any] = "0", context: Optional[Any] = None
) -> "FloatObject":
try:
return decimal.Decimal.__new__(cls, str_(value), context)
except Exception:
try:
return decimal.Decimal.__new__(cls, str(value))
except decimal.InvalidOperation:
# If this isn't a valid decimal (happens in malformed PDFs)
# fallback to 0
logger.warning(f"Invalid FloatObject {value}")
return decimal.Decimal.__new__(cls, "0")
def __repr__(self) -> str:
if self == self.to_integral():
return str(self.quantize(decimal.Decimal(1)))
else:
# Standard formatting adds useless extraneous zeros.
o = f"{self:.5f}"
# Remove the zeros.
while o and o[-1] == "0":
o = o[:-1]
return o
def as_numeric(self) -> float:
return float(b_(repr(self)))
def write_to_stream(
self, stream: StreamType, encryption_key: Union[None, str, bytes]
) -> None:
stream.write(b_(repr(self)))
def writeToStream(
self, stream: StreamType, encryption_key: Union[None, str, bytes]
) -> None: # pragma: no cover
deprecate_with_replacement("writeToStream", "write_to_stream")
self.write_to_stream(stream, encryption_key)
class NumberObject(int, PdfObject):
NumberPattern = re.compile(b"[^+-.0-9]")
def __new__(cls, value: Any) -> "NumberObject":
val = int(value)
try:
return int.__new__(cls, val)
except OverflowError:
return int.__new__(cls, 0)
def as_numeric(self) -> int:
return int(b_(repr(self)))
def write_to_stream(
self, stream: StreamType, encryption_key: Union[None, str, bytes]
) -> None:
stream.write(b_(repr(self)))
def writeToStream(
self, stream: StreamType, encryption_key: Union[None, str, bytes]
) -> None: # pragma: no cover
deprecate_with_replacement("writeToStream", "write_to_stream")
self.write_to_stream(stream, encryption_key)
@staticmethod
def read_from_stream(stream: StreamType) -> Union["NumberObject", FloatObject]:
num = read_until_regex(stream, NumberObject.NumberPattern)
if num.find(b".") != -1:
return FloatObject(num)
return NumberObject(num)
@staticmethod
def readFromStream(
stream: StreamType,
) -> Union["NumberObject", FloatObject]: # pragma: no cover
deprecate_with_replacement("readFromStream", "read_from_stream")
return NumberObject.read_from_stream(stream)
def readHexStringFromStream(
stream: StreamType,
) -> Union["TextStringObject", "ByteStringObject"]: # pragma: no cover
deprecate_with_replacement(
"readHexStringFromStream", "read_hex_string_from_stream", "4.0.0"
)
return read_hex_string_from_stream(stream)
def read_hex_string_from_stream(
stream: StreamType,
forced_encoding: Union[None, str, List[str], Dict[int, str]] = None,
) -> Union["TextStringObject", "ByteStringObject"]:
stream.read(1)
txt = ""
x = b""
while True:
tok = read_non_whitespace(stream)
if not tok:
raise PdfStreamError(STREAM_TRUNCATED_PREMATURELY)
if tok == b">":
break
x += tok
if len(x) == 2:
txt += chr(int(x, base=16))
x = b""
if len(x) == 1:
x += b"0"
if len(x) == 2:
txt += chr(int(x, base=16))
return create_string_object(b_(txt), forced_encoding)
def readStringFromStream(
stream: StreamType,
forced_encoding: Union[None, str, List[str], Dict[int, str]] = None,
) -> Union["TextStringObject", "ByteStringObject"]: # pragma: no cover
deprecate_with_replacement(
"readStringFromStream", "read_string_from_stream", "4.0.0"
)
return read_string_from_stream(stream, forced_encoding)
def read_string_from_stream(
stream: StreamType,
forced_encoding: Union[None, str, List[str], Dict[int, str]] = None,
) -> Union["TextStringObject", "ByteStringObject"]:
tok = stream.read(1)
parens = 1
txt = b""
while True:
tok = stream.read(1)
if not tok:
raise PdfStreamError(STREAM_TRUNCATED_PREMATURELY)
if tok == b"(":
parens += 1
elif tok == b")":
parens -= 1
if parens == 0:
break
elif tok == b"\\":
tok = stream.read(1)
escape_dict = {
b"n": b"\n",
b"r": b"\r",
b"t": b"\t",
b"b": b"\b",
b"f": b"\f",
b"c": rb"\c",
b"(": b"(",
b")": b")",
b"/": b"/",
b"\\": b"\\",
b" ": b" ",
b"%": b"%",
b"<": b"<",
b">": b">",
b"[": b"[",
b"]": b"]",
b"#": b"#",
b"_": b"_",
b"&": b"&",
b"$": b"$",
}
try:
tok = escape_dict[tok]
except KeyError:
if tok.isdigit():
# "The number ddd may consist of one, two, or three
# octal digits; high-order overflow shall be ignored.
# Three octal digits shall be used, with leading zeros
# as needed, if the next character of the string is also
# a digit." (PDF reference 7.3.4.2, p 16)
for _ in range(2):
ntok = stream.read(1)
if ntok.isdigit():
tok += ntok
else:
break
tok = b_(chr(int(tok, base=8)))
elif tok in b"\n\r":
# This case is hit when a backslash followed by a line
# break occurs. If it's a multi-char EOL, consume the
# second character:
tok = stream.read(1)
if tok not in b"\n\r":
stream.seek(-1, 1)
# Then don't add anything to the actual string, since this
# line break was escaped:
tok = b""
else:
msg = rf"Unexpected escaped string: {tok.decode('utf8')}"
logger.warning(msg)
txt += tok
return create_string_object(txt, forced_encoding)
class ByteStringObject(bytes_type, PdfObject): # type: ignore
"""
Represents a string object where the text encoding could not be determined.
This occurs quite often, as the PDF spec doesn't provide an alternate way to
represent strings -- for example, the encryption data stored in files (like
/O) is clearly not text, but is still stored in a "String" object.
"""
@property
def original_bytes(self) -> bytes:
"""For compatibility with TextStringObject.original_bytes."""
return self
def write_to_stream(
self, stream: StreamType, encryption_key: Union[None, str, bytes]
) -> None:
bytearr = self
if encryption_key:
from ._security import RC4_encrypt
bytearr = RC4_encrypt(encryption_key, bytearr) # type: ignore
stream.write(b"<")
stream.write(hexencode(bytearr))
stream.write(b">")
def writeToStream(
self, stream: StreamType, encryption_key: Union[None, str, bytes]
) -> None: # pragma: no cover
deprecate_with_replacement("writeToStream", "write_to_stream")
self.write_to_stream(stream, encryption_key)
class TextStringObject(str, PdfObject):
"""
Represents a string object that has been decoded into a real unicode string.
If read from a PDF document, this string appeared to match the
PDFDocEncoding, or contained a UTF-16BE BOM mark to cause UTF-16 decoding to
occur.
"""
autodetect_pdfdocencoding = False
autodetect_utf16 = False
@property
def original_bytes(self) -> bytes:
"""
It is occasionally possible that a text string object gets created where
a byte string object was expected due to the autodetection mechanism --
if that occurs, this "original_bytes" property can be used to
back-calculate what the original encoded bytes were.
"""
return self.get_original_bytes()
def get_original_bytes(self) -> bytes:
# We're a text string object, but the library is trying to get our raw
# bytes. This can happen if we auto-detected this string as text, but
# we were wrong. It's pretty common. Return the original bytes that
# would have been used to create this object, based upon the autodetect
# method.
if self.autodetect_utf16:
return codecs.BOM_UTF16_BE + self.encode("utf-16be")
elif self.autodetect_pdfdocencoding:
return encode_pdfdocencoding(self)
else:
raise Exception("no information about original bytes")
def write_to_stream(
self, stream: StreamType, encryption_key: Union[None, str, bytes]
) -> None:
# Try to write the string out as a PDFDocEncoding encoded string. It's
# nicer to look at in the PDF file. Sadly, we take a performance hit
# here for trying...
try:
bytearr = encode_pdfdocencoding(self)
except UnicodeEncodeError:
bytearr = codecs.BOM_UTF16_BE + self.encode("utf-16be")
if encryption_key:
from ._security import RC4_encrypt
bytearr = RC4_encrypt(encryption_key, bytearr)
obj = ByteStringObject(bytearr)
obj.write_to_stream(stream, None)
else:
stream.write(b"(")
for c in bytearr:
if not chr(c).isalnum() and c != b" ":
# This:
# stream.write(b_(rf"\{c:0>3o}"))
# gives
# https://github.com/davidhalter/parso/issues/207
stream.write(b_("\\%03o" % c))
else:
stream.write(b_(chr(c)))
stream.write(b")")
def writeToStream(
self, stream: StreamType, encryption_key: Union[None, str, bytes]
) -> None: # pragma: no cover
deprecate_with_replacement("writeToStream", "write_to_stream")
self.write_to_stream(stream, encryption_key)
class NameObject(str, PdfObject):
delimiter_pattern = re.compile(rb"\s+|[\(\)<>\[\]{}/%]")
surfix = b"/"
def write_to_stream(
self, stream: StreamType, encryption_key: Union[None, str, bytes]
) -> None:
stream.write(b_(self))
def writeToStream(
self, stream: StreamType, encryption_key: Union[None, str, bytes]
) -> None: # pragma: no cover
deprecate_with_replacement("writeToStream", "write_to_stream")
self.write_to_stream(stream, encryption_key)
@staticmethod
def read_from_stream(stream: StreamType, pdf: Any) -> "NameObject": # PdfReader
name = stream.read(1)
if name != NameObject.surfix:
raise PdfReadError("name read error")
name += read_until_regex(stream, NameObject.delimiter_pattern, ignore_eof=True)
try:
try:
ret = name.decode("utf-8")
except (UnicodeEncodeError, UnicodeDecodeError):
ret = name.decode("gbk")
return NameObject(ret)
except (UnicodeEncodeError, UnicodeDecodeError) as e:
# Name objects should represent irregular characters
# with a '#' followed by the symbol's hex number
if not pdf.strict:
warnings.warn("Illegal character in Name Object", PdfReadWarning)
return NameObject(name)
else:
raise PdfReadError("Illegal character in Name Object") from e
@staticmethod
def readFromStream(
stream: StreamType, pdf: Any # PdfReader
) -> "NameObject": # pragma: no cover
deprecate_with_replacement("readFromStream", "read_from_stream")
return NameObject.read_from_stream(stream, pdf)
class DictionaryObject(dict, PdfObject):
def raw_get(self, key: Any) -> Any:
return dict.__getitem__(self, key)
def __setitem__(self, key: Any, value: Any) -> Any:
if not isinstance(key, PdfObject):
raise ValueError("key must be PdfObject")
if not isinstance(value, PdfObject):
raise ValueError("value must be PdfObject")
return dict.__setitem__(self, key, value)
def setdefault(self, key: Any, value: Optional[Any] = None) -> Any:
if not isinstance(key, PdfObject):
raise ValueError("key must be PdfObject")
if not isinstance(value, PdfObject):
raise ValueError("value must be PdfObject")
return dict.setdefault(self, key, value) # type: ignore
def __getitem__(self, key: Any) -> PdfObject:
return dict.__getitem__(self, key).get_object()
@property
def xmp_metadata(self) -> Optional[PdfObject]:
"""
Retrieve XMP (Extensible Metadata Platform) data relevant to the
this object, if available.
Stability: Added in v1.12, will exist for all future v1.x releases.
@return Returns a {@link #xmp.XmpInformation XmlInformation} instance
that can be used to access XMP metadata from the document. Can also
return None if no metadata was found on the document root.
"""
from .xmp import XmpInformation
metadata = self.get("/Metadata", None)
if metadata is None:
return None
metadata = metadata.get_object()
if not isinstance(metadata, XmpInformation):
metadata = XmpInformation(metadata)
self[NameObject("/Metadata")] = metadata
return metadata
def getXmpMetadata(
self,
) -> Optional[PdfObject]: # pragma: no cover
"""
.. deprecated:: 1.28.3
Use :meth:`xmp_metadata` instead.
"""
deprecate_with_replacement("getXmpMetadata", "xmp_metadata")
return self.xmp_metadata
@property
def xmpMetadata(self) -> Optional[PdfObject]: # pragma: no cover
"""
.. deprecated:: 1.28.3
Use :meth:`xmp_metadata` instead.
"""
deprecate_with_replacement("xmpMetadata", "xmp_metadata")
return self.xmp_metadata
def write_to_stream(
self, stream: StreamType, encryption_key: Union[None, str, bytes]
) -> None:
stream.write(b"<<\n")
for key, value in list(self.items()):
key.write_to_stream(stream, encryption_key)
stream.write(b" ")
value.write_to_stream(stream, encryption_key)
stream.write(b"\n")
stream.write(b">>")
def writeToStream(
self, stream: StreamType, encryption_key: Union[None, str, bytes]
) -> None: # pragma: no cover
deprecate_with_replacement("writeToStream", "write_to_stream")
self.write_to_stream(stream, encryption_key)
@staticmethod
def read_from_stream(
stream: StreamType,
pdf: Any, # PdfReader
forced_encoding: Union[None, str, List[str], Dict[int, str]] = None,
) -> "DictionaryObject":
def get_next_obj_pos(
p: int, p1: int, rem_gens: List[int], pdf: Any
) -> int: # PdfReader
l = pdf.xref[rem_gens[0]]
for o in l:
if p1 > l[o] and p < l[o]:
p1 = l[o]
if len(rem_gens) == 1:
return p1
else:
return get_next_obj_pos(p, p1, rem_gens[1:], pdf)
def read_unsized_from_steam(stream: StreamType, pdf: Any) -> bytes: # PdfReader
# we are just pointing at beginning of the stream
eon = get_next_obj_pos(stream.tell(), 2**32, list(pdf.xref), pdf) - 1
curr = stream.tell()
rw = stream.read(eon - stream.tell())
p = rw.find(b"endstream")
if p < 0:
raise PdfReadError(
f"Unable to find 'endstream' marker for obj starting at {curr}."
)
stream.seek(curr + p + 9)
return rw[: p - 1]
tmp = stream.read(2)
if tmp != b"<<":
raise PdfReadError(
f"Dictionary read error at byte {hex_str(stream.tell())}: "
"stream must begin with '<<'"
)
data: Dict[Any, Any] = {}
while True:
tok = read_non_whitespace(stream)
if tok == b"\x00":
continue
elif tok == b"%":
stream.seek(-1, 1)
skip_over_comment(stream)
continue
if not tok:
raise PdfStreamError(STREAM_TRUNCATED_PREMATURELY)
if tok == b">":
stream.read(1)
break
stream.seek(-1, 1)
key = read_object(stream, pdf)
tok = read_non_whitespace(stream)
stream.seek(-1, 1)
value = read_object(stream, pdf, forced_encoding)
if not data.get(key):
data[key] = value
else:
# multiple definitions of key not permitted
msg = (
f"Multiple definitions in dictionary at byte "
f"{hex_str(stream.tell())} for key {key}"
)
if pdf.strict:
raise PdfReadError(msg)
else:
warnings.warn(msg, PdfReadWarning)
pos = stream.tell()
s = read_non_whitespace(stream)
if s == b"s" and stream.read(5) == b"tream":
eol = stream.read(1)
# odd PDF file output has spaces after 'stream' keyword but before EOL.
# patch provided by Danial Sandler
while eol == b" ":
eol = stream.read(1)
if eol not in (b"\n", b"\r"):
raise PdfStreamError("Stream data must be followed by a newline")
if eol == b"\r":
# read \n after
if stream.read(1) != b"\n":
stream.seek(-1, 1)
# this is a stream object, not a dictionary
if SA.LENGTH not in data:
raise PdfStreamError("Stream length not defined")
length = data[SA.LENGTH]
if isinstance(length, IndirectObject):
t = stream.tell()
length = pdf.get_object(length)
stream.seek(t, 0)
pstart = stream.tell()
data["__streamdata__"] = stream.read(length)
e = read_non_whitespace(stream)
ndstream = stream.read(8)
if (e + ndstream) != b"endstream":
# (sigh) - the odd PDF file has a length that is too long, so
# we need to read backwards to find the "endstream" ending.
# ReportLab (unknown version) generates files with this bug,
# and Python users into PDF files tend to be our audience.
# we need to do this to correct the streamdata and chop off
# an extra character.
pos = stream.tell()
stream.seek(-10, 1)
end = stream.read(9)
if end == b"endstream":
# we found it by looking back one character further.
data["__streamdata__"] = data["__streamdata__"][:-1]
elif not pdf.strict:
stream.seek(pstart, 0)
data["__streamdata__"] = read_unsized_from_steam(stream, pdf)
pos = stream.tell()
else:
stream.seek(pos, 0)
raise PdfReadError(
"Unable to find 'endstream' marker after stream at byte "
f"{hex_str(stream.tell())}."
)
else:
stream.seek(pos, 0)
if "__streamdata__" in data:
return StreamObject.initialize_from_dictionary(data)
else:
retval = DictionaryObject()
retval.update(data)
return retval
@staticmethod
def readFromStream(
stream: StreamType, pdf: Any # PdfReader
) -> "DictionaryObject": # pragma: no cover
deprecate_with_replacement("readFromStream", "read_from_stream")
return DictionaryObject.read_from_stream(stream, pdf)
class TreeObject(DictionaryObject):
def __init__(self) -> None:
DictionaryObject.__init__(self)
def hasChildren(self) -> bool: # pragma: no cover
deprecate_with_replacement("hasChildren", "has_children", "4.0.0")
return self.has_children()
def has_children(self) -> bool:
return "/First" in self
def __iter__(self) -> Any:
return self.children()
def children(self) -> Optional[Any]:
if not self.has_children():
return
child = self["/First"]
while True:
yield child
if child == self["/Last"]:
return
child = child["/Next"] # type: ignore
def addChild(self, child: Any, pdf: Any) -> None: # pragma: no cover
deprecate_with_replacement("addChild", "add_child")
self.add_child(child, pdf)
def add_child(self, child: Any, pdf: Any) -> None: # PdfReader
child_obj = child.get_object()
child = pdf.get_reference(child_obj)
assert isinstance(child, IndirectObject)
prev: Optional[DictionaryObject]
if "/First" not in self:
self[NameObject("/First")] = child
self[NameObject("/Count")] = NumberObject(0)
prev = None
else:
prev = cast(
DictionaryObject, self["/Last"]
) # TABLE 8.3 Entries in the outline dictionary
self[NameObject("/Last")] = child
self[NameObject("/Count")] = NumberObject(self[NameObject("/Count")] + 1) # type: ignore
if prev:
prev_ref = pdf.get_reference(prev)
assert isinstance(prev_ref, IndirectObject)
child_obj[NameObject("/Prev")] = prev_ref
prev[NameObject("/Next")] = child
parent_ref = pdf.get_reference(self)
assert isinstance(parent_ref, IndirectObject)
child_obj[NameObject("/Parent")] = parent_ref
def removeChild(self, child: Any) -> None: # pragma: no cover
deprecate_with_replacement("removeChild", "remove_child")
self.remove_child(child)
def remove_child(self, child: Any) -> None:
child_obj = child.get_object()
if NameObject("/Parent") not in child_obj:
raise ValueError("Removed child does not appear to be a tree item")
elif child_obj[NameObject("/Parent")] != self:
raise ValueError("Removed child is not a member of this tree")
found = False
prev_ref = None
prev = None
cur_ref: Optional[Any] = self[NameObject("/First")]
cur: Optional[Dict[str, Any]] = cur_ref.get_object() # type: ignore
last_ref = self[NameObject("/Last")]
last = last_ref.get_object()
while cur is not None:
if cur == child_obj:
if prev is None:
if NameObject("/Next") in cur:
# Removing first tree node
next_ref = cur[NameObject("/Next")]
next_obj = next_ref.get_object()
del next_obj[NameObject("/Prev")]
self[NameObject("/First")] = next_ref
self[NameObject("/Count")] -= 1 # type: ignore
else:
# Removing only tree node
assert self[NameObject("/Count")] == 1
del self[NameObject("/Count")]
del self[NameObject("/First")]
if NameObject("/Last") in self:
del self[NameObject("/Last")]
else:
if NameObject("/Next") in cur:
# Removing middle tree node
next_ref = cur[NameObject("/Next")]
next_obj = next_ref.get_object()
next_obj[NameObject("/Prev")] = prev_ref
prev[NameObject("/Next")] = next_ref
self[NameObject("/Count")] -= 1
else:
# Removing last tree node
assert cur == last
del prev[NameObject("/Next")]
self[NameObject("/Last")] = prev_ref
self[NameObject("/Count")] -= 1
found = True
break
prev_ref = cur_ref
prev = cur
if NameObject("/Next") in cur:
cur_ref = cur[NameObject("/Next")]
cur = cur_ref.get_object()
else:
cur_ref = None
cur = None
if not found:
raise ValueError("Removal couldn't find item in tree")
del child_obj[NameObject("/Parent")]
if NameObject("/Next") in child_obj:
del child_obj[NameObject("/Next")]
if NameObject("/Prev") in child_obj:
del child_obj[NameObject("/Prev")]
def emptyTree(self) -> None: # pragma: no cover
deprecate_with_replacement("emptyTree", "empty_tree", "4.0.0")
self.empty_tree()
def empty_tree(self) -> None:
for child in self:
child_obj = child.get_object()
del child_obj[NameObject("/Parent")]
if NameObject("/Next") in child_obj: