-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_reader.py
1417 lines (1283 loc) · 54.3 KB
/
_reader.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
# -*- coding: utf-8 -*-
#
# Copyright (c) 2006, Mathieu Fenniak
# Copyright (c) 2007, Ashish Kulkarni <[email protected]>
#
# 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.
import struct
import sys
import warnings
from hashlib import md5
from sys import version_info
from PyPDF2 import _utils
from PyPDF2._page import PageObject
from PyPDF2._security import RC4_encrypt, _alg33_1, _alg34, _alg35
from PyPDF2._utils import (
ConvertFunctionsToVirtualList,
b_,
formatWarning,
isString,
readUntilWhitespace,
)
from PyPDF2.constants import CatalogAttributes as CA
from PyPDF2.constants import Core as CO
from PyPDF2.constants import DocumentInformationAttributes as DI
from PyPDF2.constants import EncryptionDictAttributes as ED
from PyPDF2.constants import PageAttributes as PG
from PyPDF2.constants import PagesAttributes as PA
from PyPDF2.constants import StreamAttributes as SA
from PyPDF2.constants import TrailerKeys as TK
from PyPDF2.errors import PdfReadError, PdfReadWarning, PdfStreamError
from PyPDF2.generic import (
ArrayObject,
BooleanObject,
ByteStringObject,
Destination,
DictionaryObject,
Field,
IndirectObject,
NameObject,
NullObject,
NumberObject,
StreamObject,
TextStringObject,
createStringObject,
readNonWhitespace,
readObject,
)
if version_info < (3, 0):
from cStringIO import StringIO
BytesIO = StringIO
else:
from io import BytesIO, StringIO
def convertToInt(d, size):
if size > 8:
raise PdfReadError("invalid size in convertToInt")
d = b_("\x00\x00\x00\x00\x00\x00\x00\x00") + b_(d)
d = d[-8:]
return struct.unpack(">q", d)[0]
class DocumentInformation(DictionaryObject):
"""
A class representing the basic document metadata provided in a PDF File.
This class is accessible through
:meth:`.getDocumentInfo()`
All text properties of the document metadata have
*two* properties, eg. author and author_raw. The non-raw property will
always return a ``TextStringObject``, making it ideal for a case where
the metadata is being displayed. The raw property can sometimes return
a ``ByteStringObject``, if PyPDF2 was unable to decode the string's
text encoding; this requires additional safety in the caller and
therefore is not as commonly accessed.
"""
def __init__(self):
DictionaryObject.__init__(self)
def getText(self, key):
retval = self.get(key, None)
if isinstance(retval, TextStringObject):
return retval
return None
@property
def title(self):
"""Read-only property accessing the document's **title**.
Returns a unicode string (``TextStringObject``) or ``None``
if the title is not specified."""
return (
self.getText(DI.TITLE) or self.get(DI.TITLE).getObject()
if self.get(DI.TITLE)
else None
)
@property
def title_raw(self):
"""The "raw" version of title; can return a ``ByteStringObject``."""
return self.get(DI.TITLE)
@property
def author(self):
"""Read-only property accessing the document's **author**.
Returns a unicode string (``TextStringObject``) or ``None``
if the author is not specified."""
return self.getText(DI.AUTHOR)
@property
def author_raw(self):
"""The "raw" version of author; can return a ``ByteStringObject``."""
return self.get(DI.AUTHOR)
@property
def subject(self):
"""Read-only property accessing the document's **subject**.
Returns a unicode string (``TextStringObject``) or ``None``
if the subject is not specified."""
return self.getText(DI.SUBJECT)
@property
def subject_raw(self):
"""The "raw" version of subject; can return a ``ByteStringObject``."""
return self.get(DI.SUBJECT)
@property
def creator(self):
"""Read-only property accessing the document's **creator**. If the
document was converted to PDF from another format, this is the name of the
application (e.g. OpenOffice) that created the original document from
which it was converted. Returns a unicode string (``TextStringObject``)
or ``None`` if the creator is not specified."""
return self.getText(DI.CREATOR)
@property
def creator_raw(self):
"""The "raw" version of creator; can return a ``ByteStringObject``."""
return self.get(DI.CREATOR)
@property
def producer(self):
"""Read-only property accessing the document's **producer**.
If the document was converted to PDF from another format, this is
the name of the application (for example, OSX Quartz) that converted
it to PDF. Returns a unicode string (``TextStringObject``)
or ``None`` if the producer is not specified."""
return self.getText(DI.PRODUCER)
@property
def producer_raw(self):
"""The "raw" version of producer; can return a ``ByteStringObject``."""
return self.get(DI.PRODUCER)
class PdfFileReader(object):
"""
Initialize a PdfFileReader object.
This operation can take some time, as the PDF stream's cross-reference
tables are read into memory.
:param stream: A File object or an object that supports the standard read
and seek methods similar to a File object. Could also be a
string representing a path to a PDF file.
:param bool strict: Determines whether user should be warned of all
problems and also causes some correctable problems to be fatal.
Defaults to ``True``.
:param warndest: Destination for logging warnings (defaults to
``sys.stderr``).
:param bool overwriteWarnings: Determines whether to override Python's
``warnings.py`` module with a custom implementation (defaults to
``True``).
"""
def __init__(self, stream, strict=True, warndest=None, overwriteWarnings=True):
if overwriteWarnings:
# Have to dynamically override the default showwarning since there
# are no public methods that specify the 'file' parameter
def _showwarning(
message, category, filename, lineno, file=warndest, line=None
):
if file is None:
file = sys.stderr
try:
# It is possible for sys.stderr to be defined as None, most commonly in the case that the script
# is being run vida pythonw.exe on Windows. In this case, just swallow the warning.
# See also https://docs.python.org/3/library/sys.html# sys.__stderr__
if file is not None:
file.write(
formatWarning(message, category, filename, lineno, line)
)
except IOError:
pass
warnings.showwarning = _showwarning
self.strict = strict
self.flattenedPages = None
self.resolvedObjects = {}
self.xrefIndex = 0
self._pageId2Num = None # map page IndirectRef number to Page Number
if hasattr(stream, "mode") and "b" not in stream.mode:
warnings.warn(
"PdfFileReader stream/file object is not in binary mode. "
"It may not be read correctly.",
PdfReadWarning,
)
if isString(stream):
with open(stream, "rb") as fileobj:
stream = BytesIO(b_(fileobj.read()))
self.read(stream)
self.stream = stream
self._override_encryption = False
def getDocumentInfo(self):
"""
Retrieve the PDF file's document information dictionary, if it exists.
Note that some PDF files use metadata streams instead of docinfo
dictionaries, and these metadata streams will not be accessed by this
function.
:return: the document information of this PDF file
:rtype: :class:`DocumentInformation<pdf.DocumentInformation>` or
``None`` if none exists.
"""
if TK.INFO not in self.trailer:
return None
obj = self.trailer[TK.INFO]
retval = DocumentInformation()
retval.update(obj)
return retval
@property
def documentInfo(self):
"""
Read-only property that accesses the
:meth:`getDocumentInfo()<PdfFileReader.getDocumentInfo>` function.
"""
return self.getDocumentInfo()
def getXmpMetadata(self):
"""
Retrieve XMP (Extensible Metadata Platform) data from the PDF document
root.
:return: a :class:`XmpInformation<xmp.XmpInformation>`
instance that can be used to access XMP metadata from the document.
:rtype: :class:`XmpInformation<xmp.XmpInformation>` or
``None`` if no metadata was found on the document root.
"""
try:
self._override_encryption = True
return self.trailer[TK.ROOT].getXmpMetadata()
finally:
self._override_encryption = False
@property
def xmpMetadata(self):
"""
Read-only property that accesses the
:meth:`getXmpMetadata()<PdfFileReader.getXmpMetadata>` function.
"""
return self.getXmpMetadata()
def getNumPages(self):
"""
Calculates the number of pages in this PDF file.
:return: number of pages
:rtype: int
:raises PdfReadError: if file is encrypted and restrictions prevent
this action.
"""
# Flattened pages will not work on an Encrypted PDF;
# the PDF file's page count is used in this case. Otherwise,
# the original method (flattened page count) is used.
if self.isEncrypted:
try:
self._override_encryption = True
self.decrypt("")
return self.trailer[TK.ROOT]["/Pages"]["/Count"]
except Exception:
raise PdfReadError("File has not been decrypted")
finally:
self._override_encryption = False
else:
if self.flattenedPages is None:
self._flatten()
return len(self.flattenedPages)
@property
def numPages(self):
"""
Read-only property that accesses the
:meth:`getNumPages()<PdfFileReader.getNumPages>` function.
"""
return self.getNumPages()
def getPage(self, pageNumber):
"""
Retrieves a page by number from this PDF file.
:param int pageNumber: The page number to retrieve
(pages begin at zero)
:return: a :class:`PageObject<pdf.PageObject>` instance.
:rtype: :class:`PageObject<pdf.PageObject>`
"""
# ensure that we're not trying to access an encrypted PDF
# assert not self.trailer.has_key(TK.ENCRYPT)
if self.flattenedPages is None:
self._flatten()
return self.flattenedPages[pageNumber]
@property
def namedDestinations(self):
"""
Read-only property that accesses the
:meth:`getNamedDestinations()<PdfFileReader.getNamedDestinations>` function.
"""
return self.getNamedDestinations()
# A select group of relevant field attributes. For the complete list,
# see section 8.6.2 of the PDF 1.7 reference.
def getFields(self, tree=None, retval=None, fileobj=None):
"""
Extracts field data if this PDF contains interactive form fields.
The *tree* and *retval* parameters are for recursive use.
:param fileobj: A file object (usually a text file) to write
a report to on all interactive form fields found.
:return: A dictionary where each key is a field name, and each
value is a :class:`Field<PyPDF2.generic.Field>` object. By
default, the mapping name is used for keys.
:rtype: dict, or ``None`` if form data could not be located.
"""
field_attributes = {
"/FT": "Field Type",
PA.PARENT: "Parent",
"/T": "Field Name",
"/TU": "Alternate Field Name",
"/TM": "Mapping Name",
"/Ff": "Field Flags",
"/V": "Value",
"/DV": "Default Value",
}
if retval is None:
retval = {}
catalog = self.trailer[TK.ROOT]
# get the AcroForm tree
if "/AcroForm" in catalog:
tree = catalog["/AcroForm"]
else:
return None
if tree is None:
return retval
self._checkKids(tree, retval, fileobj)
for attr in field_attributes:
if attr in tree:
# Tree is a field
self._buildField(tree, retval, fileobj, field_attributes)
break
if "/Fields" in tree:
fields = tree["/Fields"]
for f in fields:
field = f.getObject()
self._buildField(field, retval, fileobj, field_attributes)
return retval
def _buildField(self, field, retval, fileobj, fieldAttributes):
self._checkKids(field, retval, fileobj)
try:
key = field["/TM"]
except KeyError:
try:
key = field["/T"]
except KeyError:
# Ignore no-name field for now
return
if fileobj:
self._writeField(fileobj, field, fieldAttributes)
fileobj.write("\n")
retval[key] = Field(field)
def _checkKids(self, tree, retval, fileobj):
if PA.KIDS in tree:
# recurse down the tree
for kid in tree[PA.KIDS]:
self.getFields(kid.getObject(), retval, fileobj)
def _writeField(self, fileobj, field, fieldAttributes):
order = ["/TM", "/T", "/FT", PA.PARENT, "/TU", "/Ff", "/V", "/DV"]
for attr in order:
attr_name = fieldAttributes[attr]
try:
if attr == "/FT":
# Make the field type value more clear
types = {
"/Btn": "Button",
"/Tx": "Text",
"/Ch": "Choice",
"/Sig": "Signature",
}
if field[attr] in types:
fileobj.write(attr_name + ": " + types[field[attr]] + "\n")
elif attr == PA.PARENT:
# Let's just write the name of the parent
try:
name = field[PA.PARENT]["/TM"]
except KeyError:
name = field[PA.PARENT]["/T"]
fileobj.write(attr_name + ": " + name + "\n")
else:
fileobj.write(attr_name + ": " + str(field[attr]) + "\n")
except KeyError:
# Field attribute is N/A or unknown, so don't write anything
pass
def getFormTextFields(self):
"""Retrieves form fields from the document with textual data (inputs, dropdowns)"""
# Retrieve document form fields
formfields = self.getFields()
if formfields is None:
return {}
return {
formfields[field]["/T"]: formfields[field].get("/V")
for field in formfields
if formfields[field].get("/FT") == "/Tx"
}
def getNamedDestinations(self, tree=None, retval=None):
"""
Retrieves the named destinations present in the document.
:return: a dictionary which maps names to
:class:`Destinations<PyPDF2.generic.Destination>`.
:rtype: dict
"""
if retval is None:
retval = {}
catalog = self.trailer[TK.ROOT]
# get the name tree
if CA.DESTS in catalog:
tree = catalog[CA.DESTS]
elif CA.NAMES in catalog:
names = catalog[CA.NAMES]
if CA.DESTS in names:
tree = names[CA.DESTS]
if tree is None:
return retval
if PA.KIDS in tree:
# recurse down the tree
for kid in tree[PA.KIDS]:
self.getNamedDestinations(kid.getObject(), retval)
if CA.NAMES in tree:
names = tree[CA.NAMES]
for i in range(0, len(names), 2):
key = names[i].getObject()
val = names[i + 1].getObject()
if isinstance(val, DictionaryObject) and "/D" in val:
val = val["/D"]
dest = self._buildDestination(key, val)
if dest is not None:
retval[key] = dest
return retval
@property
def outlines(self):
"""
Read-only property that accesses the
:meth:`getOutlines()<PdfFileReader.getOutlines>` function.
"""
return self.getOutlines()
def getOutlines(self, node=None, outlines=None):
"""
Retrieve the document outline present in the document.
:return: a nested list of :class:`Destinations<PyPDF2.generic.Destination>`.
"""
if outlines is None:
outlines = []
catalog = self.trailer[TK.ROOT]
# get the outline dictionary and named destinations
if CO.OUTLINES in catalog:
try:
lines = catalog[CO.OUTLINES]
except PdfReadError:
# this occurs if the /Outlines object reference is incorrect
# for an example of such a file, see https://unglueit-files.s3.amazonaws.com/ebf/7552c42e9280b4476e59e77acc0bc812.pdf
# so continue to load the file without the Bookmarks
return outlines
# TABLE 8.3 Entries in the outline dictionary
if "/First" in lines:
node = lines["/First"]
self._namedDests = self.getNamedDestinations()
if node is None:
return outlines
# see if there are any more outlines
while True:
outline = self._buildOutline(node)
if outline:
outlines.append(outline)
# check for sub-outlines
if "/First" in node:
sub_outlines = []
self.getOutlines(node["/First"], sub_outlines)
if sub_outlines:
outlines.append(sub_outlines)
if "/Next" not in node:
break
node = node["/Next"]
return outlines
def _getPageNumberByIndirect(self, indirectRef):
"""Generate _pageId2Num"""
if self._pageId2Num is None:
id2num = {}
for i, x in enumerate(self.pages):
id2num[x.indirectRef.idnum] = i
self._pageId2Num = id2num
if isinstance(indirectRef, NullObject):
return -1
if isinstance(indirectRef, int):
idnum = indirectRef
else:
idnum = indirectRef.idnum
ret = self._pageId2Num.get(idnum, -1)
return ret
def getPageNumber(self, page):
"""
Retrieve page number of a given PageObject
:param PageObject page: The page to get page number. Should be
an instance of :class:`PageObject<PyPDF2.pdf.PageObject>`
:return: the page number or -1 if page not found
:rtype: int
"""
indirect_ref = page.indirectRef
ret = self._getPageNumberByIndirect(indirect_ref)
return ret
def getDestinationPageNumber(self, destination):
"""
Retrieve page number of a given Destination object
:param Destination destination: The destination to get page number.
Should be an instance of
:class:`Destination<PyPDF2.pdf.Destination>`
:return: the page number or -1 if page not found
:rtype: int
"""
indirect_ref = destination.page
ret = self._getPageNumberByIndirect(indirect_ref)
return ret
def _buildDestination(self, title, array):
page, typ = array[0:2]
array = array[2:]
try:
return Destination(title, page, typ, *array)
except PdfReadError:
warnings.warn("Unknown destination : " + title + " " + str(array))
if self.strict:
raise
else:
# create a link to first Page
return Destination(
title, self.getPage(0).indirectRef, TextStringObject("/Fit")
)
def _buildOutline(self, node):
dest, title, outline = None, None, None
if "/A" in node and "/Title" in node:
# Action, section 8.5 (only type GoTo supported)
title = node["/Title"]
action = node["/A"]
if action["/S"] == "/GoTo":
dest = action["/D"]
elif "/Dest" in node and "/Title" in node:
# Destination, section 8.2.1
title = node["/Title"]
dest = node["/Dest"]
# if destination found, then create outline
if dest:
if isinstance(dest, ArrayObject):
outline = self._buildDestination(title, dest)
elif isString(dest) and dest in self._namedDests:
outline = self._namedDests[dest]
outline[NameObject("/Title")] = title
else:
raise PdfReadError("Unexpected destination %r" % dest)
return outline
@property
def pages(self):
"""
Read-only property that emulates a list based upon the
:meth:`getNumPages()<PdfFileReader.getNumPages>` and
:meth:`getPage()<PdfFileReader.getPage>` methods.
"""
return ConvertFunctionsToVirtualList(self.getNumPages, self.getPage)
def getPageLayout(self):
"""
Get the page layout.
See :meth:`setPageLayout()<PdfFileWriter.setPageLayout>`
for a description of valid layouts.
:return: Page layout currently being used.
:rtype: ``str``, ``None`` if not specified
"""
try:
return self.trailer[TK.ROOT]["/PageLayout"]
except KeyError:
return None
@property
def pageLayout(self):
"""Read-only property accessing the
:meth:`getPageLayout()<PdfFileReader.getPageLayout>` method."""
return self.getPageLayout()
def getPageMode(self):
"""
Get the page mode.
See :meth:`setPageMode()<PdfFileWriter.setPageMode>`
for a description of valid modes.
:return: Page mode currently being used.
:rtype: ``str``, ``None`` if not specified
"""
try:
return self.trailer[TK.ROOT]["/PageMode"]
except KeyError:
return None
@property
def pageMode(self):
"""Read-only property accessing the
:meth:`getPageMode()<PdfFileReader.getPageMode>` method."""
return self.getPageMode()
def _flatten(self, pages=None, inherit=None, indirectRef=None):
inheritablePageAttributes = (
NameObject(PG.RESOURCES),
NameObject(PG.MEDIABOX),
NameObject(PG.CROPBOX),
NameObject(PG.ROTATE),
)
if inherit is None:
inherit = {}
if pages is None:
# Fix issue 327: set flattenedPages attribute only for
# decrypted file
catalog = self.trailer[TK.ROOT].getObject()
pages = catalog["/Pages"].getObject()
self.flattenedPages = []
t = "/Pages"
if PA.TYPE in pages:
t = pages[PA.TYPE]
if t == "/Pages":
for attr in inheritablePageAttributes:
if attr in pages:
inherit[attr] = pages[attr]
for page in pages[PA.KIDS]:
addt = {}
if isinstance(page, IndirectObject):
addt["indirectRef"] = page
self._flatten(page.getObject(), inherit, **addt)
elif t == "/Page":
for attr, value in list(inherit.items()):
# if the page has it's own value, it does not inherit the
# parent's value:
if attr not in pages:
pages[attr] = value
page_obj = PageObject(self, indirectRef)
page_obj.update(pages)
self.flattenedPages.append(page_obj)
def _getObjectFromStream(self, indirectReference):
# indirect reference to object in object stream
# read the entire object stream into memory
stmnum, idx = self.xref_objStm[indirectReference.idnum]
obj_stm = IndirectObject(stmnum, 0, self).getObject()
# This is an xref to a stream, so its type better be a stream
assert obj_stm["/Type"] == "/ObjStm"
# /N is the number of indirect objects in the stream
assert idx < obj_stm["/N"]
stream_data = BytesIO(b_(obj_stm.getData()))
for i in range(obj_stm["/N"]):
readNonWhitespace(stream_data)
stream_data.seek(-1, 1)
objnum = NumberObject.readFromStream(stream_data)
readNonWhitespace(stream_data)
stream_data.seek(-1, 1)
offset = NumberObject.readFromStream(stream_data)
readNonWhitespace(stream_data)
stream_data.seek(-1, 1)
if objnum != indirectReference.idnum:
# We're only interested in one object
continue
if self.strict and idx != i:
raise PdfReadError("Object is in wrong index.")
stream_data.seek(obj_stm["/First"] + offset, 0)
try:
obj = readObject(stream_data, self)
except PdfStreamError as exc:
# Stream object cannot be read. Normally, a critical error, but
# Adobe Reader doesn't complain, so continue (in strict mode?)
warnings.warn(
"Invalid stream (index %d) within object %d %d: %s"
% (i, indirectReference.idnum, indirectReference.generation, exc),
PdfReadWarning,
)
if self.strict:
raise PdfReadError("Can't read object stream: %s" % exc)
# Replace with null. Hopefully it's nothing important.
obj = NullObject()
return obj
if self.strict:
raise PdfReadError("This is a fatal error in strict mode.")
return NullObject()
def getObject(self, indirectReference):
retval = self.cacheGetIndirectObject(
indirectReference.generation, indirectReference.idnum
)
if retval is not None:
return retval
if (
indirectReference.generation == 0
and indirectReference.idnum in self.xref_objStm
):
retval = self._getObjectFromStream(indirectReference)
elif (
indirectReference.generation in self.xref
and indirectReference.idnum in self.xref[indirectReference.generation]
):
start = self.xref[indirectReference.generation][indirectReference.idnum]
self.stream.seek(start, 0)
idnum, generation = self.readObjectHeader(self.stream)
if idnum != indirectReference.idnum and self.xrefIndex:
# Xref table probably had bad indexes due to not being zero-indexed
if self.strict:
raise PdfReadError(
"Expected object ID (%d %d) does not match actual (%d %d); xref table not zero-indexed."
% (
indirectReference.idnum,
indirectReference.generation,
idnum,
generation,
)
)
else:
pass # xref table is corrected in non-strict mode
elif idnum != indirectReference.idnum and self.strict:
# some other problem
raise PdfReadError(
"Expected object ID (%d %d) does not match actual (%d %d)."
% (
indirectReference.idnum,
indirectReference.generation,
idnum,
generation,
)
)
if self.strict:
assert generation == indirectReference.generation
retval = readObject(self.stream, self)
# override encryption is used for the /Encrypt dictionary
if not self._override_encryption and self.isEncrypted:
# if we don't have the encryption key:
if not hasattr(self, "_decryption_key"):
raise PdfReadError("file has not been decrypted")
# otherwise, decrypt here...
pack1 = struct.pack("<i", indirectReference.idnum)[:3]
pack2 = struct.pack("<i", indirectReference.generation)[:2]
key = self._decryption_key + pack1 + pack2
assert len(key) == (len(self._decryption_key) + 5)
md5_hash = md5(key).digest()
key = md5_hash[: min(16, len(self._decryption_key) + 5)]
retval = self._decryptObject(retval, key)
else:
warnings.warn(
"Object %d %d not defined."
% (indirectReference.idnum, indirectReference.generation),
PdfReadWarning,
)
if self.strict:
raise PdfReadError("Could not find object.")
self.cacheIndirectObject(
indirectReference.generation, indirectReference.idnum, retval
)
return retval
def _decryptObject(self, obj, key):
if isinstance(obj, (ByteStringObject, TextStringObject)):
obj = createStringObject(RC4_encrypt(key, obj.original_bytes))
elif isinstance(obj, StreamObject):
obj._data = RC4_encrypt(key, obj._data)
elif isinstance(obj, DictionaryObject):
for dictkey, value in list(obj.items()):
obj[dictkey] = self._decryptObject(value, key)
elif isinstance(obj, ArrayObject):
for i in range(len(obj)):
obj[i] = self._decryptObject(obj[i], key)
return obj
def readObjectHeader(self, stream):
# Should never be necessary to read out whitespace, since the
# cross-reference table should put us in the right spot to read the
# object header. In reality... some files have stupid cross reference
# tables that are off by whitespace bytes.
extra = False
_utils.skipOverComment(stream)
extra |= _utils.skipOverWhitespace(stream)
stream.seek(-1, 1)
idnum = readUntilWhitespace(stream)
extra |= _utils.skipOverWhitespace(stream)
stream.seek(-1, 1)
generation = readUntilWhitespace(stream)
extra |= _utils.skipOverWhitespace(stream)
stream.seek(-1, 1)
# although it's not used, it might still be necessary to read
_obj = stream.read(3) # noqa: F841
readNonWhitespace(stream)
stream.seek(-1, 1)
if extra and self.strict:
warnings.warn(
"Superfluous whitespace found in object header %s %s"
% (idnum, generation),
PdfReadWarning,
)
return int(idnum), int(generation)
def cacheGetIndirectObject(self, generation, idnum):
out = self.resolvedObjects.get((generation, idnum))
return out
def cacheIndirectObject(self, generation, idnum, obj):
if (generation, idnum) in self.resolvedObjects:
msg = "Overwriting cache for %s %s" % (generation, idnum)
if self.strict:
raise PdfReadError(msg)
else:
warnings.warn(msg)
self.resolvedObjects[(generation, idnum)] = obj
return obj
def read(self, stream):
# start at the end:
stream.seek(-1, 2)
if not stream.tell():
raise PdfReadError("Cannot read an empty file")
if self.strict:
stream.seek(0, 0)
header_byte = stream.read(5)
if header_byte != b"%PDF-":
raise PdfReadError(
"PDF starts with '{}', but '%PDF-' expected".format(
header_byte.decode("utf8")
)
)
stream.seek(-1, 2)
last1M = stream.tell() - 1024 * 1024 + 1 # offset of last MB of stream
line = b_("")
while line[:5] != b_("%%EOF"):
if stream.tell() < last1M:
raise PdfReadError("EOF marker not found")
line = self.readNextEndLine(stream)
startxref = self._find_startxref_pos(stream)
# check and eventually correct the startxref only in not strict
xref_issue_nr = self._get_xref_issues(stream, startxref)
if xref_issue_nr != 0:
if self.strict and xref_issue_nr:
raise PdfReadError("Broken xref table")
else:
warnings.warn(
"incorrect startxref pointer({})".format(xref_issue_nr),
PdfReadWarning,
)
# read all cross reference tables and their trailers
self.xref = {}
self.xref_objStm = {}
self.trailer = DictionaryObject()
while True:
# load the xref table
stream.seek(startxref, 0)
x = stream.read(1)
if x == b_("x"):
self._read_standard_xref_table(stream)
readNonWhitespace(stream)
stream.seek(-1, 1)
new_trailer = readObject(stream, self)
for key, value in list(new_trailer.items()):
if key not in self.trailer:
self.trailer[key] = value
if "/Prev" in new_trailer:
startxref = new_trailer["/Prev"]
else:
break
elif xref_issue_nr:
try:
self._rebuild_xref_table(stream)
break
except Exception:
xref_issue_nr = 0
elif x.isdigit():
xrefstream = self._read_pdf15_xref_stream(stream)
trailer_keys = TK.ROOT, TK.ENCRYPT, TK.INFO, TK.ID
for key in trailer_keys:
if key in xrefstream and key not in self.trailer:
self.trailer[NameObject(key)] = xrefstream.raw_get(key)
if "/Prev" in xrefstream:
startxref = xrefstream["/Prev"]
else:
break
else:
# some PDFs have /Prev=0 in the trailer, instead of no /Prev
if startxref == 0:
if self.strict:
raise PdfReadError(
"/Prev=0 in the trailer (try opening with strict=False)"
)
else:
warnings.warn(
"/Prev=0 in the trailer - assuming there"
" is no previous xref table"
)
break
# bad xref character at startxref. Let's see if we can find
# the xref table nearby, as we've observed this error with an
# off-by-one before.
stream.seek(-11, 1)
tmp = stream.read(20)
xref_loc = tmp.find(b_("xref"))
if xref_loc != -1: