-
Notifications
You must be signed in to change notification settings - Fork 0
/
generic.py
3019 lines (2739 loc) · 73.4 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
# Original Copyright 2006, Mathieu Fenniak
# Further changes by Chris Johnson and Martin Thoma 2000 onwards
# All rights reserved.
#
# much changed to handle Python 3 - CJ 2019 onwards
# fixed to handle comment at end of object - CJ December 2021
# fix Name object to allow x00 delimiter
#
# 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, and so on)
postscript objects are one of the following types
integer sign, digits (also radix notation )
real allow exponent and decimal point 1
boolean 'true' or 'false'
array, packed array [ ... ]
string (... ) also hex <...> and
name a word - perhaps with /
dictionary << >>
operator just another word
mark stores a position on the operand stack
null 'null'
"""
__author__ = "Mathieu Fenniak"
__author_email__ = "[email protected]"
import codecs
import decimal
import logging
import re
import sys
import warnings
from io import BytesIO
from PyPDF2._security import RC4_encrypt
from PyPDF2.constants import FilterTypes as FT
from PyPDF2.constants import StreamAttributes as SA
from PyPDF2.errors import (
STREAM_TRUNCATED_PREMATURELY,
PdfReadError,
PdfReadWarning,
PdfStreamError,
)
from . import filters, _utils
from ._utils import (
b_,
chr_,
ord_,
readNonWhitespace,
skipOverComment,
u_,
)
debug = False
logger = logging.getLogger(__name__)
NumberSigns = b"+-"
NUMBER_CHARS = b"+-.0123456789"
OCTAL_DIGITS = b"01234567"
IndirectPattern = re.compile(b_(r"(\d+)\s+(\d+)\s+R[^a-zA-Z]"))
WHITESPACES = [b" ", b"\n", b"\r", b"\t", b"\x00", b""] # or end of string
SEPS = [b"<", b"["]
DICTIONARYSTART = b"<<"
DICTIONARYEND = b">>"
ARRAYSTART = b"["
ARRAYEND = b"]"
HEXSTART = b"<"
HEXEND = b">"
ASCII85START = b"<~"
ASCII85END = b"~>"
STRINGSTART = b"("
STRINGEND = b")"
DICTIONARYSTART = b"<<"
DICTIONARYEND = b">>"
ARRAYSTART = b"["
ARRAYEND = b"]"
NAMESTART = b"/"
COMMENT = b"%"
CR = b"\r"
LF = b"\n"
FF = b"\f"
BACKSLASH = b"\\"
TAB = b"\t"
CRLF = CR + LF
EOLS = [CR, LF, CRLF]
EOL_CHARS = CR + LF
EOF = b"" # as returned by stream.read()
def readWord(stream):
result = b""
tok = stream.read(1)
while tok not in WHITESPACES and tok not in SEPS:
result += tok # appalingly slow
tok = stream.read(1)
stream.seek(-1, 1)
return result
def readObject(stream, pdf):
"""interpret the passed pdf source bytes calling the appropriate read routine to return the apropriate
pdf object creation code
the routine
- reads ahead 20 bytes
- examines the first one or more bytes which determine the object works by examining the first few bytes
- calls the appropriate read routine and returns the object
- checks for comments and indirect references
"""
def hprint(stream, message):
"""debugging print"""
here = stream.tell()
stream.seek(here - 40)
sample = stream.read(60)
marker = "-" * 40 + "/"
stream.seek(here)
print(here, sample, message)
print(here, marker)
here = stream.tell()
stuff = stream.read(20)
stream.seek(here)
if False and stuff[:1] in WHITESPACES:
hprint(stream, "whitespace when not expected")
import pdb
pdb.set_trace()
assert stuff[:1] not in WHITESPACES
while stuff[:1] == COMMENT:
# consume the percent and the subsequent comment upto
# and including the eol. Then skip leading whitespace
# (not certain that the leading whitespace is always to
# be dropped but it seems to work
tok = stream.read(1)
while tok not in EOL_CHARS:
if len(tok) <= 0:
raise PdfStreamError("File ended unexpectedly.")
tok = stream.read(1)
while tok in WHITESPACES:
if len(tok) <= 0:
break
tok = stream.read(1)
stream.seek(-1, 1)
here = stream.tell()
stuff = stream.read(20)
stream.seek(here)
# name like objects true, false, null
if stuff[:4] == b"true":
return BooleanObject.readFromStream(stream)
elif stuff[:5] == b"false":
return BooleanObject.readFromStream(stream)
elif stuff[:4] == b"null":
return NullObject.readFromStream(stream)
elif stuff[:2] == DICTIONARYSTART:
return DictionaryObject.readFromStream(stream, pdf)
elif stuff[:2] == ASCII85START:
raise PdfStreamError("PyPDF2 cannot handle ascii85 encoded strings")
elif stuff[:1] == HEXSTART:
return readHexStringFromStream(stream)
elif stuff[:1] == STRINGSTART:
return readStringFromStream(stream)
elif stuff[:1] == ARRAYSTART:
# parse all items in the list - this is recursive
return ArrayObject.readFromStream(stream, pdf)
elif stuff[:1] in NUMBER_CHARS:
if IndirectPattern.match(stuff) is not None:
return IndirectObject.readFromStream(stream, pdf)
else:
return NumberObject.readFromStream(stream)
elif stuff[:1] == NAMESTART:
return NameObject.readFromStream(stream, pdf)
else:
return readWord(stream)
class PdfObject(object):
def getObject(self):
"""Resolves indirect references."""
return self
class NullObject(PdfObject):
def writeToStream(self, stream, encryption_key):
stream.write(b_("null"))
def readFromStream(stream):
nulltxt = stream.read(4)
if nulltxt != b_("null"):
raise PdfReadError("Could not read Null object")
return NullObject()
readFromStream = staticmethod(readFromStream)
class BooleanObject(PdfObject):
def __init__(self, value):
self.value = value
def __str__(self):
return "PyPDF2 generic boolean {}".format(self.value)
def __repr__(self):
return "PyPDF2 generic boolean {}".format(self.value)
def writeToStream(self, stream, encryption_key):
if self.value:
stream.write(b_("true"))
else:
stream.write(b_("false"))
def readFromStream(stream):
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")
readFromStream = staticmethod(readFromStream)
class ArrayObject(list, PdfObject):
def writeToStream(self, stream, encryption_key):
stream.write(ARRAYSTART)
for data in self:
stream.write(b_(" "))
data.writeToStream(stream, encryption_key)
stream.write(b" " + ARRAYEND)
def readFromStream(stream, pdf):
# now skips any whitespace rather than use tok.isspace
# prevents blowing up on x00 sep but may not handle
# comments correctly CJ April 2022
arr = ArrayObject()
tok = stream.read(1)
assert tok == ARRAYSTART
tok = stream.read(1)
# position on first element
# and then loop through objects and following whitespace
while tok in WHITESPACES:
if len(tok) == 0:
break
if tok == ARRAYEND:
break
tok = stream.read(1)
while True:
# process element and subsequent
# whitespace
if tok == ARRAYEND:
break
# token should now be the first char of the first
# object. back up as read_object will do its own read
stream.seek(-1, 1)
arr.append(readObject(stream, pdf))
tok = stream.read(1)
while tok in WHITESPACES:
if len(tok) == 0:
break
if tok == ARRAYEND:
break
tok = stream.read(1)
return arr
readFromStream = staticmethod(readFromStream)
class IndirectObject(PdfObject):
def __init__(self, idnum, generation, pdf):
self.idnum = idnum
self.generation = generation
self.pdf = pdf
def getObject(self):
return self.pdf.getObject(self).getObject()
def __repr__(self):
return "IndirectObject(%r, %r)" % (self.idnum, self.generation)
def __eq__(self, other):
return isinstance(other, IndirectObject) and (
self.idnum,
self.generation,
self.pdf,
) == (other.idnum, other.generation, other.pdf)
def __ne__(self, other):
return not self.__eq__(other)
def writeToStream(self, stream, encryption_key):
stream.write(b_("%s %s R" % (self.idnum, self.generation)))
def readFromStream(stream, pdf):
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 = readNonWhitespace(stream)
if r != b_("R"):
raise PdfReadError(
"Error reading indirect object reference at byte %s"
% _utils.hexStr(stream.tell())
)
return IndirectObject(int(idnum), int(generation), pdf)
readFromStream = staticmethod(readFromStream)
class FloatObject(decimal.Decimal, PdfObject):
def __new__(cls, value="0", context=None):
try:
return decimal.Decimal.__new__(cls, _utils.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("Invalid FloatObject {}".format(value))
return decimal.Decimal.__new__(cls, "0")
def __repr__(self):
if self == self.to_integral():
return str(self.quantize(decimal.Decimal(1)))
else:
# Standard formatting adds useless extraneous zeros.
o = "%.5f" % self
# Remove the zeros.
while o and o[-1] == "0":
o = o[:-1]
return o
def as_numeric(self):
return float(b_(repr(self)))
def writeToStream(self, stream, encryption_key):
stream.write(b_(repr(self)))
class NumberObject(int, PdfObject):
NumberPattern = re.compile(b_("[^+-.0-9]"))
ByteDot = b_(".")
def __new__(cls, value):
val = int(value)
try:
return int.__new__(cls, val)
except OverflowError:
return int.__new__(cls, 0)
def as_numeric(self):
return int(b_(repr(self)))
def writeToStream(self, stream, encryption_key):
stream.write(b_(repr(self)))
def readFromStream(stream):
num = _utils.readUntilRegex(stream, NumberObject.NumberPattern)
if num.find(NumberObject.ByteDot) != -1:
return FloatObject(num)
else:
return NumberObject(num)
readFromStream = staticmethod(readFromStream)
def createStringObject(string):
# see createStringObjectOrig -
#
# now everything is a byte stream unless it is specifically indicated
# by a byte order mark or it is already a (unicode) string.
#
# unfortunatly there are streams starting with bom
# which cannot be round tripped back to bytes
#
if isinstance(string, _utils.string_type):
return TextStringObject(string)
elif string.startswith(codecs.BOM_UTF16_BE):
retval = TextStringObject(string.decode("utf-16"))
retval.autodetect_utf16 = True
return retval
else:
return ByteStringObject(string)
def createStringObjectOrig(string):
if isinstance(string, _utils.string_type):
return TextStringObject(string)
elif isinstance(string, _utils.bytes_type):
try:
if string.startswith(codecs.BOM_UTF16_BE):
retval = TextStringObject(string.decode("utf-16"))
retval.autodetect_utf16 = True
return retval
else:
# This is probably a big performance hit here, but we need to
# convert string objects into the text/unicode-aware version if
# possible... and the only way to check if that's possible is
# to try. Some strings are strings, some are just byte arrays.
retval = TextStringObject(decode_pdfdocencoding(string))
retval.autodetect_pdfdocencoding = True
return retval
except UnicodeDecodeError:
return ByteStringObject(string)
else:
raise TypeError("createStringObject should have str or unicode arg")
def skipWhitespace(stream):
WHITESPACES = [b" ", b"\n", b"\r", b"\t", b"\x00", b"%"]
tok = WHITESPACES[0]
while tok in WHITESPACES:
if tok == b"%": # comment is whitespace
tok = stream.readline()
tok = stream.read(1)
else:
tok = stream.read(1)
stream.seek(-1, 1)
def readHexStringFromStream(stream):
import codecs
HEX_CODEC = "HEX"
HEXSTART = b"<"
HEXEND = b">"
HEXCHARS = b"0123456789ABCDEFabcdef"
WHITESPACE = b" \00\t\n\r\f"
EOF = b""
tok = stream.read(1)
assert tok == HEXSTART
tok = stream.read(1)
run = b""
while tok not in (HEXEND, EOF):
if tok in WHITESPACE:
pass
elif tok in HEXCHARS:
run += tok
else:
error_message = "Bad character {} in hex stream".format(tok)
raise PdfReadError(error_message)
tok = stream.read(1)
if tok == EOF: #
raise PdfReadError("Stream has ended unexpectedly in hex string")
if len(run) % 2 == 1:
run += b"0"
return ByteStringObject(codecs.decode(run, HEX_CODEC))
def readStringFromStream(stream):
"""
parse representation of byte stream (which may or may not represent
text)
starts and ends with STRINGSTART and STRINGEND parenthesis
may include parenthesis if nested
may include BACKSLASH escape sequences for
special characters
or for octal defined bytes
or for EOLs to be ignored
may include EOLs which become LFs unless escaped
other chanracters
"""
tok = stream.read(1)
assert tok == STRINGSTART
parens = 0 # nesting level
txt = b""
while True:
tok = stream.read(1)
if not tok:
raise PdfStreamError(STREAM_TRUNCATED_PREMATURELY)
elif tok == STRINGEND and parens == 0:
break
elif tok == STRINGSTART:
parens += 1
elif tok == STRINGEND:
parens -= 1
elif tok == BACKSLASH:
# we have an escape sequence
tok = stream.read(1)
if tok == b_("n"):
tok = b_("\n")
elif tok == b_("r"):
tok = b_("\r")
elif tok == b_("t"):
tok = b_("\t")
elif tok == b_("b"):
tok = b_("\b")
elif tok == b_("f"):
tok = b_("\f")
elif tok == b_("("):
tok = b_("(")
elif tok == b_(")"):
tok = b_(")")
elif tok == b_("/"):
tok = b_("/")
elif tok == b_("\\"):
tok = b_("\\")
elif tok in (
b_(" "),
b_("/"),
b_("%"),
b_("<"),
b_(">"),
b_("["),
b_("]"),
b_("#"),
b_("_"),
b_("&"),
b_("$"),
):
# odd/unnessecary escape sequences we have encountered
tok = b_(tok)
elif tok in OCTAL_DIGITS:
# "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)
# we have one digit - add the next
for _i in range(2):
ntok = stream.read(1)
if ntok == EOF:
break
if ntok not in OCTAL_DIGITS:
stream.seek(-1, 1)
break
tok += ntok
ordinal = int(tok, base=8) % 256
tok = bytearray(
[
ordinal,
]
) # should work on Py2.7 and Py 3
elif tok in EOL_CHARS:
# escaped LF, CR and CRLF are dropped by setting tok to null
if tok == CR:
tok = stream.read(1)
if tok == EOF:
raise PdfReadError("Stream ended in a string")
elif tok == LF:
pass
else:
stream.seek(-1, 1)
tok = b""
else:
raise PdfReadError(r"Unexpected escaped string: %s" % tok)
txt += tok
return createStringObject(txt)
class ByteStringObject(_utils.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):
"""For compatibility with TextStringObject.original_bytes."""
return self
def writeToStream(self, stream, encryption_key):
bytearr = self
if encryption_key:
bytearr = RC4_encrypt(encryption_key, bytearr)
stream.write(b_("<"))
stream.write(_utils.hexencode(bytearr))
stream.write(b_(">"))
class TextStringObject(_utils.string_type, PdfObject): # type: ignore
"""
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):
"""
It is 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. This will
not always work
"""
return self.get_original_bytes()
def get_original_bytes(self):
# 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 writeToStream(self, stream, encryption_key):
# 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:
bytearr = RC4_encrypt(encryption_key, bytearr)
obj = ByteStringObject(bytearr)
obj.writeToStream(stream, None)
else:
stream.write(b_("("))
for c in bytearr:
if not chr_(c).isalnum() and c != b_(" "):
stream.write(b_("\\%03o" % ord_(c)))
else:
stream.write(b_(chr_(c)))
stream.write(b_(")"))
class NameObject(str, PdfObject):
# hex00 added as delimiter as it is not included in \s
# but should allow a run of space bytes including x00
delimiterPattern = re.compile(b"\\s+|[\\(\\)<>\\[\\]{}/%\x00]")
surfix = b"/"
def writeToStream(self, stream, encryption_key):
stream.write(b_(self))
def readFromStream(stream, pdf):
debug = False
if debug:
print((stream.tell()))
name = stream.read(1)
if name != NameObject.surfix:
raise PdfReadError("name read error")
name += _utils.readUntilRegex(
stream, NameObject.delimiterPattern, ignore_eof=True
)
if debug:
print(name)
try:
return NameObject(name.decode("utf-8"))
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:
e = e
raise PdfReadError("Illegal character in Name Object")
readFromStream = staticmethod(readFromStream)
class DictionaryObject(dict, PdfObject):
def raw_get(self, key):
return dict.__getitem__(self, key)
def __setitem__(self, key, value):
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, value=None):
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)
def __getitem__(self, key):
try:
return dict.__getitem__(self, key).getObject()
except KeyError:
return None
def getXmpMetadata(self):
metadata = self.get("/Metadata", None)
if metadata is None:
return None
metadata = metadata.getObject()
from . import xmp
if not isinstance(metadata, xmp.XmpInformation):
metadata = xmp.XmpInformation(metadata)
self[NameObject("/Metadata")] = metadata
return metadata
##
# Read-only property that accesses the {@link
# #DictionaryObject.getXmpData getXmpData} function.
# <p>
# Stability: Added in v1.12, will exist for all future v1.x releases.
xmpMetadata = property(lambda self: self.getXmpMetadata(), None, None)
def writeToStream(self, stream, encryption_key):
stream.write(b_("<<\n"))
for key, value in list(self.items()):
key.writeToStream(stream, encryption_key)
stream.write(b_(" "))
value.writeToStream(stream, encryption_key)
stream.write(b_("\n"))
stream.write(b_(">>"))
def readFromStream(stream, pdf):
db_here = stream.tell()
# Dictionary starts with line <<
tmp = stream.read(2)
if tmp != b_("<<"):
raise PdfReadError(
"Dictionary read error at byte %s: stream must begin with '<<'"
% _utils.hexStr(stream.tell())
)
# now bump past any white space or <eol>
data = {}
# deal with the dict portion
while True:
tok = readNonWhitespace(stream)
# cj2019 line below read if not tok
if tok is None:
raise PdfStreamError(STREAM_TRUNCATED_PREMATURELY)
if tok == b_(">"):
stream.read(1)
break
if tok == b_("\x00"):
continue
elif tok == b_("%"):
stream.seek(-1, 1)
skipOverComment(stream)
continue
stream.seek(-1, 1)
key = readObject(stream, pdf)
tok = readNonWhitespace(stream)
stream.seek(-1, 1)
value = readObject(stream, pdf)
try:
_ = not data.get(key)
except Exception:
print("problem with key ", type(key), key)
print("value ", value)
print("data ", data)
if not data.get(key):
data[key] = value
elif pdf.strict:
# multiple definitions of key not permitted
raise PdfReadError(
"Multiple definitions in dictionary at byte %s for key %s"
% (_utils.hexStr(stream.tell()), key)
)
else:
warnings.warn(
"Multiple definitions in dictionary at byte %s for key %s"
% (_utils.hexStr(stream.tell()), key),
PdfReadWarning,
)
db_here = stream.tell() # noqa F841
pos = stream.tell()
s = readNonWhitespace(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)
assert eol in (b_("\n"), b_("\r"))
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
assert SA.LENGTH in data
length = data[SA.LENGTH]
if debug:
print(data)
if isinstance(length, IndirectObject):
t = stream.tell()
length = pdf.getObject(length)
stream.seek(t, 0)
#
#
if True:
data_pos = stream.tell()
term_pos = data_pos + length
stream.seek(term_pos)
terminator = stream.readline(200)
# print("Data followed by ", terminator)
# print("Data length ", length)
# print(data)
if b"endstream" in terminator:
print("OK")
else:
more_stuff = stream.read(50) # noqa
# print("More stuff", more_stuff)
stream.seek(term_pos - 30)
# less_stuff = stream.read(50)
# print("Less stuff", less_stuff)
stream.seek(data_pos)
data["__streamdata__"] = stream.read(length) # cj 17 June
e = readNonWhitespace(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.
print("Logic error - expecting endstream ", e + ndstream)
print(pos - 10)
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 "/Filter" in data:
print("ignoring endstream mismatch ")
else:
stream.seek(pos, 0)
raise PdfReadError(
"Unable to find 'endstream' marker after stream at byte %s."
% _utils.hexStr(stream.tell())
)
else:
stream.seek(pos, 0)
if "__streamdata__" in data:
return StreamObject.initializeFromDictionary(data)
else:
retval = DictionaryObject()
retval.update(data)
return retval
readFromStream = staticmethod(readFromStream)
class TreeObject(DictionaryObject):
def __init__(self):
DictionaryObject.__init__(self)
def hasChildren(self):
return "/First" in self
def __iter__(self):
return self.children()
def children(self):
if not self.hasChildren():
if sys.version_info >= (3, 5): # PEP 479
return
else:
raise StopIteration
child = self["/First"]
while True:
yield child
if child == self["/Last"]:
if sys.version_info >= (3, 5): # PEP 479
return
else:
raise StopIteration
child = child["/Next"]
def addChild(self, child, pdf):
child_obj = child.getObject()
child = pdf.getReference(child_obj)
assert isinstance(child, IndirectObject)
if "/First" not in self:
self[NameObject("/First")] = child
self[NameObject("/Count")] = NumberObject(0)
prev = None
else:
prev = self["/Last"]
self[NameObject("/Last")] = child
self[NameObject("/Count")] = NumberObject(self[NameObject("/Count")] + 1)
if prev: