/
pdf.py
2471 lines (2231 loc) · 105 KB
/
pdf.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 -*-
#
# vim: sw=4:expandtab:foldmethod=marker
#
# Copyright (c) 2006, Mathieu Fenniak
# Copyright (c) 2007, Ashish Kulkarni <kulkarni.ashish@gmail.com>
#
# 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 string
"""
A pure-Python PDF library with very minimal capabilities. It was designed to
be able to split and merge PDF files by page, and that's about all it can do.
It may be a solid base for future PDF file work in Python.
"""
__author__ = "Mathieu Fenniak"
__author_email__ = "biziqe@mathieu.fenniak.net"
import math
import struct
import sys
from sys import version_info
if version_info < ( 3, 0 ):
from cStringIO import StringIO
else:
from io import StringIO
if version_info < ( 3, 0 ):
BytesIO = StringIO
else:
from io import BytesIO
from . import filters
from . import utils
import warnings
import codecs
from .generic import *
from .utils import readNonWhitespace, readUntilWhitespace, ConvertFunctionsToVirtualList
from .utils import b_, u_, ord_, chr_, str_
if version_info < ( 2, 4 ):
from sets import ImmutableSet as frozenset
if version_info < ( 2, 5 ):
from md5 import md5
else:
from hashlib import md5
##
# This class supports writing PDF files out, given pages produced by another
# class (typically {@link #PdfFileReader PdfFileReader}).
class PdfFileWriter(object):
def __init__(self):
self._header = b_("%PDF-1.3")
self._objects = [] # array of indirect objects
# The root of our page tree node.
pages = DictionaryObject()
pages.update({
NameObject("/Type"): NameObject("/Pages"),
NameObject("/Count"): NumberObject(0),
NameObject("/Kids"): ArrayObject(),
})
self._pages = self._addObject(pages)
# info object
info = DictionaryObject()
info.update({
NameObject("/Producer"): createStringObject(codecs.BOM_UTF16_BE + u_("PyPDF2").encode('utf-16be'))
})
self._info = self._addObject(info)
# root object
root = DictionaryObject()
root.update({
NameObject("/Type"): NameObject("/Catalog"),
NameObject("/Pages"): self._pages,
})
self._root = self._addObject(root)
def _addObject(self, obj):
self._objects.append(obj)
return IndirectObject(len(self._objects), 0, self)
def getObject(self, ido):
if ido.pdf != self:
raise ValueError("pdf must be self")
return self._objects[ido.idnum - 1]
##
# Common method for inserting or adding a page to this PDF file.
#
# @param page The page to add to the document. This argument should be
# an instance of {@link #PageObject PageObject}.
# @param action The function which will insert the page in the dictionnary.
# Takes: page list, page to add.
def _addPage(self, page, action):
assert page["/Type"] == "/Page"
page[NameObject("/Parent")] = self._pages
page = self._addObject(page)
pages = self.getObject(self._pages)
action(pages["/Kids"], page)
pages[NameObject("/Count")] = NumberObject(pages["/Count"] + 1)
##
# Adds a page to this PDF file. The page is usually acquired from a
# {@link #PdfFileReader PdfFileReader} instance.
# <p>
# Stability: Added in v1.0, will exist for all v1.x releases.
#
# @param page The page to add to the document. This argument should be
# an instance of {@link #PageObject PageObject}.
def addPage(self, page):
self._addPage(page, list.append)
##
# Insert a page in this PDF file. The page is usually acquired from a
# {@link #PdfFileReader PdfFileReader} instance.
#
# @param page The page to add to the document. This argument should be
# an instance of {@link #PageObject PageObject}.
# @param index Position at which the page will be inserted.
def insertPage(self, page, index=0):
self._addPage(page, lambda l, p: l.insert(index, p))
##
# Retrieves a page by number from this PDF file.
# @return Returns a {@link #PageObject PageObject} instance.
def getPage(self, pageNumber):
pages = self.getObject(self._pages)
# XXX: crude hack
return pages["/Kids"][pageNumber].getObject()
##
# Return the number of pages.
# @return The number of pages.
def getNumPages(self):
pages = self.getObject(self._pages)
return int(pages[NameObject("/Count")])
##
# Append a blank page to this PDF file and returns it. If no page size
# is specified, use the size of the last page; throw
# PageSizeNotDefinedError if it doesn't exist.
# @param width The width of the new page expressed in default user
# space units.
# @param height The height of the new page expressed in default user
# space units.
def addBlankPage(self, width=None, height=None):
page = PageObject.createBlankPage(self, width, height)
self.addPage(page)
return page
##
# Insert a blank page to this PDF file and returns it. If no page size
# is specified, use the size of the page in the given index; throw
# PageSizeNotDefinedError if it doesn't exist.
# @param width The width of the new page expressed in default user
# space units.
# @param height The height of the new page expressed in default user
# space units.
# @param index Position to add the page.
def insertBlankPage(self, width=None, height=None, index=0):
if width is None or height is None and \
(self.getNumPages() - 1) >= index:
oldpage = self.getPage(index)
width = oldpage.mediaBox.getWidth()
height = oldpage.mediaBox.getHeight()
page = PageObject.createBlankPage(self, width, height)
self.insertPage(page, index)
return page
##
# Encrypt this PDF file with the PDF Standard encryption handler.
# @param user_pwd The "user password", which allows for opening and reading
# the PDF file with the restrictions provided.
# @param owner_pwd The "owner password", which allows for opening the PDF
# files without any restrictions. By default, the owner password is the
# same as the user password.
# @param use_128bit Boolean argument as to whether to use 128bit
# encryption. When false, 40bit encryption will be used. By default, this
# flag is on.
def encrypt(self, user_pwd, owner_pwd = None, use_128bit = True):
import time, random
if owner_pwd == None:
owner_pwd = user_pwd
if use_128bit:
V = 2
rev = 3
keylen = int(128 / 8)
else:
V = 1
rev = 2
keylen = int(40 / 8)
# permit everything:
P = -1
O = ByteStringObject(_alg33(owner_pwd, user_pwd, rev, keylen))
ID_1 = ByteStringObject(md5(b_(repr(time.time()))).digest())
ID_2 = ByteStringObject(md5(b_(repr(random.random()))).digest())
self._ID = ArrayObject((ID_1, ID_2))
if rev == 2:
U, key = _alg34(user_pwd, O, P, ID_1)
else:
assert rev == 3
U, key = _alg35(user_pwd, rev, keylen, O, P, ID_1, False)
encrypt = DictionaryObject()
encrypt[NameObject("/Filter")] = NameObject("/Standard")
encrypt[NameObject("/V")] = NumberObject(V)
if V == 2:
encrypt[NameObject("/Length")] = NumberObject(keylen * 8)
encrypt[NameObject("/R")] = NumberObject(rev)
encrypt[NameObject("/O")] = ByteStringObject(O)
encrypt[NameObject("/U")] = ByteStringObject(U)
encrypt[NameObject("/P")] = NumberObject(P)
self._encrypt = self._addObject(encrypt)
self._encrypt_key = key
##
# Writes the collection of pages added to this object out as a PDF file.
# <p>
# Stability: Added in v1.0, will exist for all v1.x releases.
# @param stream An object to write the file to. The object must support
# the write method, and the tell method, similar to a file object.
def write(self, stream):
if hasattr(stream, 'mode') and 'b' not in stream.mode:
warnings.warn("File <%s> to write to is not in binary mode. It may not be written to correctly." % stream.name)
debug = False
import struct
externalReferenceMap = {}
# PDF objects sometimes have circular references to their /Page objects
# inside their object tree (for example, annotations). Those will be
# indirect references to objects that we've recreated in this PDF. To
# address this problem, PageObject's store their original object
# reference number, and we add it to the external reference map before
# we sweep for indirect references. This forces self-page-referencing
# trees to reference the correct new object location, rather than
# copying in a new copy of the page object.
for objIndex in range(len(self._objects)):
obj = self._objects[objIndex]
if isinstance(obj, PageObject) and obj.indirectRef != None:
data = obj.indirectRef
if data.pdf not in externalReferenceMap:
externalReferenceMap[data.pdf] = {}
if data.generation not in externalReferenceMap[data.pdf]:
externalReferenceMap[data.pdf][data.generation] = {}
externalReferenceMap[data.pdf][data.generation][data.idnum] = IndirectObject(objIndex + 1, 0, self)
self.stack = []
if debug: print(("ERM:", externalReferenceMap, "root:", self._root))
self._sweepIndirectReferences(externalReferenceMap, self._root)
del self.stack
# Begin writing:
object_positions = []
stream.write(self._header + b_("\n"))
for i in range(len(self._objects)):
idnum = (i + 1)
obj = self._objects[i]
object_positions.append(stream.tell())
stream.write(b_(str(idnum) + " 0 obj\n"))
key = None
if hasattr(self, "_encrypt") and idnum != self._encrypt.idnum:
pack1 = struct.pack("<i", i + 1)[:3]
pack2 = struct.pack("<i", 0)[:2]
key = self._encrypt_key + pack1 + pack2
assert len(key) == (len(self._encrypt_key) + 5)
md5_hash = md5(key).digest()
key = md5_hash[:min(16, len(self._encrypt_key) + 5)]
obj.writeToStream(stream, key)
stream.write(b_("\nendobj\n"))
# xref table
xref_location = stream.tell()
stream.write(b_("xref\n"))
stream.write(b_("0 %s\n" % (len(self._objects) + 1)))
stream.write(b_("%010d %05d f \n" % (0, 65535)))
for offset in object_positions:
stream.write(b_("%010d %05d n \n" % (offset, 0)))
# trailer
stream.write(b_("trailer\n"))
trailer = DictionaryObject()
trailer.update({
NameObject("/Size"): NumberObject(len(self._objects) + 1),
NameObject("/Root"): self._root,
NameObject("/Info"): self._info,
})
if hasattr(self, "_ID"):
trailer[NameObject("/ID")] = self._ID
if hasattr(self, "_encrypt"):
trailer[NameObject("/Encrypt")] = self._encrypt
trailer.writeToStream(stream, None)
# eof
stream.write(b_("\nstartxref\n%s\n%%%%EOF\n" % (xref_location)))
def addMetadata(self, infos):
"""
'infos' argument is a python dictionary where each key is a field
and each value is your new metadata.
Example: {u'/Title': u'My title'}
"""
args = {}
for key, value in list(infos.items()):
args[NameObject(key)] = createStringObject(value)
self.getObject(self._info).update(args)
def _sweepIndirectReferences(self, externMap, data):
debug = False
if debug: print((data, "TYPE", data.__class__.__name__))
if isinstance(data, DictionaryObject):
for key, value in list(data.items()):
origvalue = value
value = self._sweepIndirectReferences(externMap, value)
if isinstance(value, StreamObject):
# a dictionary value is a stream. streams must be indirect
# objects, so we need to change this value.
value = self._addObject(value)
data[key] = value
return data
elif isinstance(data, ArrayObject):
for i in range(len(data)):
value = self._sweepIndirectReferences(externMap, data[i])
if isinstance(value, StreamObject):
# an array value is a stream. streams must be indirect
# objects, so we need to change this value
value = self._addObject(value)
data[i] = value
return data
elif isinstance(data, IndirectObject):
# internal indirect references are fine
if data.pdf == self:
if data.idnum in self.stack:
return data
else:
self.stack.append(data.idnum)
realdata = self.getObject(data)
self._sweepIndirectReferences(externMap, realdata)
return data
else:
newobj = externMap.get(data.pdf, {}).get(data.generation, {}).get(data.idnum, None)
if newobj == None:
newobj = data.pdf.getObject(data)
self._objects.append(None) # placeholder
idnum = len(self._objects)
newobj_ido = IndirectObject(idnum, 0, self)
if data.pdf not in externMap:
externMap[data.pdf] = {}
if data.generation not in externMap[data.pdf]:
externMap[data.pdf][data.generation] = {}
externMap[data.pdf][data.generation][data.idnum] = newobj_ido
newobj = self._sweepIndirectReferences(externMap, newobj)
self._objects[idnum-1] = newobj
return newobj_ido
return newobj
else:
return data
def getReference(self, obj):
idnum = self._objects.index(obj) + 1
ref = IndirectObject(idnum, 0, self)
assert ref.getObject() == obj
return ref
def getOutlineRoot(self):
root = self.getObject(self._root)
if '/Outlines' in root:
outline = root['/Outlines']
idnum = self._objects.index(outline) + 1
outlineRef = IndirectObject(idnum, 0, self)
assert outlineRef.getObject() == outline
else:
outline = TreeObject()
outline.update({ })
outlineRef = self._addObject(outline)
root[NameObject('/Outlines')] = outlineRef
return outline
def getNamedDestRoot(self):
root = self.getObject(self._root)
if '/Names' in root and isinstance(root['/Names'], DictionaryObject):
names = root['/Names']
idnum = self._objects.index(names) + 1
namesRef = IndirectObject(idnum, 0, self)
assert namesRef.getObject() == names
if '/Dests' in names and isinstance(names['/Dests'], DictionaryObject):
dests = names['/Dests']
idnum = self._objects.index(dests) + 1
destsRef = IndirectObject(idnum, 0, self)
assert destsRef.getObject() == dests
if '/Names' in dests:
nd = dests['/Names']
else:
nd = ArrayObject()
dests[NameObject('/Names')] = nd
else:
dests = DictionaryObject()
destsRef = self._addObject(dests)
names[NameObject('/Dests')] = destsRef
nd = ArrayObject()
dests[NameObject('/Names')] = nd
else:
names = DictionaryObject()
namesRef = self._addObject(names)
root[NameObject('/Names')] = namesRef
dests = DictionaryObject()
destsRef = self._addObject(dests)
names[NameObject('/Dests')] = destsRef
nd = ArrayObject()
dests[NameObject('/Names')] = nd
return nd
def addBookmarkDestination(self, dest, parent=None):
destRef = self._addObject(dest)
outlineRef = self.getOutlineRoot()
if parent == None:
parent = outlineRef
parent = parent.getObject()
#print parent.__class__.__name__
parent.addChild(destRef, self)
return destRef
def addBookmarkDict(self, bookmark, parent=None):
bookmarkObj = TreeObject()
for k, v in list(bookmark.items()):
bookmarkObj[NameObject(str(k))] = v
bookmarkObj.update(bookmark)
if '/A' in bookmark:
action = DictionaryObject()
for k, v in list(bookmark['/A'].items()):
action[NameObject(str(k))] = v
actionRef = self._addObject(action)
bookmarkObj[NameObject('/A')] = actionRef
bookmarkRef = self._addObject(bookmarkObj)
outlineRef = self.getOutlineRoot()
if parent == None:
parent = outlineRef
parent = parent.getObject()
parent.addChild(bookmarkRef, self)
return bookmarkRef
def addBookmark(self, title, pagenum, parent=None):
"""
Add a bookmark to the pdf, using the specified title and pointing at
the specified page number. A parent can be specified to make this a
nested bookmark below the parent.
"""
pageRef = self.getObject(self._pages)['/Kids'][pagenum]
action = DictionaryObject()
action.update({
NameObject('/D') : ArrayObject([pageRef, NameObject('/FitH'), NumberObject(826)]),
NameObject('/S') : NameObject('/GoTo')
})
actionRef = self._addObject(action)
outlineRef = self.getOutlineRoot()
if parent == None:
parent = outlineRef
bookmark = TreeObject()
bookmark.update({
NameObject('/A'): actionRef,
NameObject('/Title'): createStringObject(title),
})
bookmarkRef = self._addObject(bookmark)
parent = parent.getObject()
parent.addChild(bookmarkRef, self)
return bookmarkRef
def addNamedDestinationObject(self, dest):
destRef = self._addObject(dest)
nd = self.getNamedDestRoot()
nd.extend([dest['/Title'], destRef])
return destRef
def addNamedDestination(self, title, pagenum):
pageRef = self.getObject(self._pages)['/Kids'][pagenum]
dest = DictionaryObject()
dest.update({
NameObject('/D') : ArrayObject([pageRef, NameObject('/FitH'), NumberObject(826)]),
NameObject('/S') : NameObject('/GoTo')
})
destRef = self._addObject(dest)
nd = self.getNamedDestRoot()
nd.extend([title, destRef])
return destRef
def removeLinks(self):
'''
Removes links and annotations.
'''
pages = self.getObject(self._pages)['/Kids']
for page in pages:
pageRef = self.getObject(page)
if "/Annots" in pageRef:
del pageRef['/Annots']
def removeImages(self, ignoreByteStringObject=False):
'''
Removes images.
in Python2 operator is type str.
in Python3 operator is type bytes.
@param ignoreByteStringObject (Bool) : for ByteStringObject.
'''
pages = self.getObject(self._pages)['/Kids']
for j in range(len(pages)):
page = pages[j]
pageRef = self.getObject(page)
content = pageRef['/Contents'].getObject()
if not isinstance(content, ContentStream):
content = ContentStream(content, pageRef)
_operations = []
seq_graphics = False
for operands, operator in content.operations:
if operator == b_('Tj'):
text = operands[0]
if ignoreByteStringObject:
if not isinstance(text, TextStringObject):
operands[0] = TextStringObject()
elif operator == b_("'"):
text = operands[0]
if ignoreByteStringObject:
if not isinstance(text, TextStringObject):
operands[0] = TextStringObject()
elif operator == b_('"'):
text = operands[2]
if ignoreByteStringObject:
if not isinstance(text, TextStringObject):
operands[2] = TextStringObject()
elif operator == b_("TJ"):
for i in range(len(operands[0])):
if ignoreByteStringObject:
if not isinstance(operands[0][i], TextStringObject):
operands[0][i] = TextStringObject()
if operator == b_('q'):
seq_graphics = True
if operator == b_('Q'):
seq_graphics = False
if seq_graphics:
if operator in [b_('cm'), b_('w'), b_('J'), b_('j'), b_('M'), b_('d'), b_('ri'), b_('i'),
b_('gs'), b_('W'), b_('b'), b_('s'), b_('S'), b_('f'), b_('F'), b_('n'), b_('m'), b_('l'),
b_('c'), b_('v'), b_('y'), b_('h'), b_('B'), b_('Do'), b_('sh')]:
continue
if operator == b_('re'):
continue
_operations.append((operands, operator))
content.operations = _operations
pageRef.__setitem__(NameObject('/Contents'), content)
def removeText(self, ignoreByteStringObject=False):
'''
Removes text.
in Python2 operator is type str.
in Python3 operator is type bytes.
@param ignoreByteStringObject (Bool) : for ByteStringObject.
'''
pages = self.getObject(self._pages)['/Kids']
for j in range(len(pages)):
page = pages[j]
pageRef = self.getObject(page)
content = pageRef['/Contents'].getObject()
if not isinstance(content, ContentStream):
content = ContentStream(content, pageRef)
for operands,operator in content.operations:
if operator == b_('Tj'):
text = operands[0]
if not ignoreByteStringObject:
if isinstance(text, TextStringObject):
operands[0] = TextStringObject()
else:
if isinstance(text, TextStringObject) or \
isinstance(text, ByteStringObject):
operands[0] = TextStringObject()
elif operator == b_("'"):
text = operands[0]
if not ignoreByteStringObject:
if isinstance(text, TextStringObject):
operands[0] = TextStringObject()
else:
if isinstance(text, TextStringObject) or \
isinstance(text, ByteStringObject):
operands[0] = TextStringObject()
elif operator == b_('"'):
text = operands[2]
if not ignoreByteStringObject:
if isinstance(text, TextStringObject):
operands[2] = TextStringObject()
else:
if isinstance(text, TextStringObject) or \
isinstance(text, ByteStringObject):
operands[2] = TextStringObject()
elif operator == b_("TJ"):
for i in range(len(operands[0])):
if not ignoreByteStringObject:
if isinstance(operands[0][i], TextStringObject):
operands[0][i] = TextStringObject()
else:
if isinstance(operands[0][i], TextStringObject) or \
isinstance(operands[0][i], ByteStringObject):
operands[0][i] = TextStringObject()
pageRef.__setitem__(NameObject('/Contents'), content)
def addLink(self, pagenum, pagedest, rect, zoom='/FitV'):
"""
Add a internal link in pdf, from a rectangular area and pointing at
the specified page number.
"""
pageLink = self.getObject(self._pages)['/Kids'][pagenum]
pageDest = self.getObject(self._pages)['/Kids'][pagedest] #TODO: switch for external link
pageRef = self.getObject(pageLink)
lnk = DictionaryObject()
lnk.update({
NameObject('/Rect'): NameObject(rect), # link pposition
NameObject('/Dest'): ArrayObject([pageDest, NameObject(zoom), NumberObject(826)]),
NameObject('/P'): NameObject(pageLink), # 1pt border
NameObject('/Border'): NameObject('[ 0 0 0 ]'), # [0 0 1] 1pt border
NameObject('/Type'): NameObject('/Annot'),
NameObject('/Subtype'): NameObject('/Link'),
})
lnkRef = self._addObject(lnk)
if "/Annots" in pageRef:
pageRef['/Annots'].append(lnkRef)
else:
pageRef[NameObject('/Annots')] = ArrayObject([lnkRef])
_valid_layouts = ['/NoLayout', '/SinglePage', '/OneColumn', '/TwoColumnLeft', '/TwoColumnRight', '/TwoPageLeft', '/TwoPageRight']
def getPageLayout(self):
'''
Get the page layout
See PdfFileWriter.setPageLayout for a description of valid layouts.
Returns None if the layout has not been set.
'''
try:
return self.getObject(self._root)['/PageLayout']
except KeyError:
return None
def setPageLayout(self, layout):
'''
Set the page layout
Valid layouts are:
/NoLayout Layout explicitly not specified
/SinglePage Show one page at a time
/OneColumn Show one column at a time
/TwoColumnLeft Show pages in two columns, odd-numbered pages on the left
/TwoColumnRight Show pages in two columns, odd-numbered pages on the right
/TwoPageLeft Show two pages at a time, odd-numbered pages on the left
/TwoPageRight Show two pages at a time, odd-numbered pages on the right
'''
if not isinstance(layout, NameObject):
if layout not in self._valid_layouts:
warnings.warn("Layout should be one of: {}".format(', '.join(self._valid_layouts)))
layout = NameObject(layout)
root = self.getObject(self._root)
root.update({NameObject('/PageLayout'): layout})
pageLayout = property(getPageLayout, setPageLayout)
_valid_modes = ['/UseNone', '/UseOutlines', '/UseThumbs', '/UseFullscreen', '/UseOC', '/UseAttach']
def getPageMode(self):
'''
Get the page mode
See PdfFileWriter.setPageMode for a description of valid modes.
Returns None if the mode has not been set.
'''
try:
return self.getObject(self._root)['/PageMode']
except KeyError:
return None
def setPageMode(self, mode):
'''
Set the page mode
Valid modes are:
/UseNone Do not show outlines or thumbnails panels
/UseOutlines Show outlines (aka bookmarks) panel
/UseThumbs Show page thumbnails panel
/UseFullscreen Fullscreen view
/UseOC Show Optional Content Group (OCG) panel
/UseAttach Show attachments panel
'''
if not isinstance(mode, NameObject):
if mode not in self._valid_modes:
warnings.warn("Mode should be one of: {}".format(', '.join(self._valid_modes)))
mode = NameObject(mode)
root = self.getObject(self._root)
root.update({NameObject('/PageMode'): mode})
pageMode = property(getPageMode, setPageMode)
##
# Initializes a PdfFileReader object. This operation can take some time, as
# the PDF stream's cross-reference tables are read into memory.
# <p>
# Stability: Added in v1.0, will exist for all v1.x releases.
#
# @param stream An object that supports the standard read and seek methods
# similar to a file object.
# @param strict Determines whether user should be warned of all problems and
# also causes some correctable problems to be fatal. Defaults
# to True.
class PdfFileReader(object):
def __init__(self, stream, strict=True):
self.strict = strict
self.flattenedPages = None
self.resolvedObjects = {}
self.xrefIndex = 0
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.", utils.PdfReadWarning)
if type(stream) in (str, str):
fileobj = open(stream, 'rb')
stream = BytesIO(b_(fileobj.read()))
fileobj.close()
self.read(stream)
self.stream = stream
self._override_encryption = False
##
# Retrieves 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.
# <p>
# Stability: Added in v1.6, will exist for all future v1.x releases.
# @return Returns a {@link #DocumentInformation DocumentInformation}
# instance, or None if none exists.
def getDocumentInfo(self):
if "/Info" not in self.trailer:
return None
obj = self.trailer['/Info']
retval = DocumentInformation()
retval.update(obj)
return retval
##
# Read-only property that accesses the {@link
# #PdfFileReader.getDocumentInfo getDocumentInfo} function.
# <p>
# Stability: Added in v1.7, will exist for all future v1.x releases.
documentInfo = property(lambda self: self.getDocumentInfo(), None, None)
##
# Retrieves XMP (Extensible Metadata Platform) data from the PDF document
# root.
# <p>
# Stability: Added in v1.12, will exist for all future v1.x releases.
# @return Returns a {@link #generic.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.
def getXmpMetadata(self):
try:
self._override_encryption = True
return self.trailer["/Root"].getXmpMetadata()
finally:
self._override_encryption = False
##
# Read-only property that accesses the {@link #PdfFileReader.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)
##
# Calculates the number of pages in this PDF file.
# <p>
# Stability: Added in v1.0, will exist for all v1.x releases.
# @return Returns an integer.
def getNumPages(self):
# 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
return self.trailer["/Root"]["/Pages"]["/Count"]
except:
raise utils.PdfReadError("File has not been decrypted")
finally:
self._override_encryption = False
else:
if self.flattenedPages == None:
self._flatten()
return len(self.flattenedPages)
##
# Read-only property that accesses the {@link #PdfFileReader.getNumPages
# getNumPages} function.
# <p>
# Stability: Added in v1.7, will exist for all future v1.x releases.
numPages = property(lambda self: self.getNumPages(), None, None)
##
# Retrieves a page by number from this PDF file.
# <p>
# Stability: Added in v1.0, will exist for all v1.x releases.
# @return Returns a {@link #PageObject PageObject} instance.
def getPage(self, pageNumber):
## ensure that we're not trying to access an encrypted PDF
#assert not self.trailer.has_key("/Encrypt")
if self.flattenedPages == None:
self._flatten()
return self.flattenedPages[pageNumber]
##
# Read-only property that accesses the
# {@link #PdfFileReader.getNamedDestinations
# getNamedDestinations} function.
# <p>
# Stability: Added in v1.10, will exist for all future v1.x releases.
namedDestinations = property(lambda self:
self.getNamedDestinations(), None, None)
##
# Retrieves the named destinations present in the document.
# <p>
# Stability: Added in v1.10, will exist for all future v1.x releases.
# @return Returns a dict which maps names to {@link #Destination
# destinations}.
def getNamedDestinations(self, tree=None, retval=None):
if retval == None:
retval = {}
catalog = self.trailer["/Root"]
# get the name tree
if "/Dests" in catalog:
tree = catalog["/Dests"]
elif "/Names" in catalog:
names = catalog['/Names']
if "/Dests" in names:
tree = names['/Dests']
if tree == None:
return retval
if "/Kids" in tree:
# recurse down the tree
for kid in tree["/Kids"]:
self.getNamedDestinations(kid.getObject(), retval)
if "/Names" in tree:
names = tree["/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 != None:
retval[key] = dest
return retval
##
# Read-only property that accesses the {@link #PdfFileReader.getOutlines
# getOutlines} function.
# <p>
# Stability: Added in v1.10, will exist for all future v1.x releases.
outlines = property(lambda self: self.getOutlines(), None, None)
##
# Retrieves the document outline present in the document.
# <p>
# Stability: Added in v1.10, will exist for all future v1.x releases.
# @return Returns a nested list of {@link #Destination destinations}.
def getOutlines(self, node=None, outlines=None):
if outlines == None:
outlines = []
catalog = self.trailer["/Root"]
# get the outline dictionary and named destinations
if "/Outlines" in catalog:
lines = catalog["/Outlines"]
if "/First" in lines:
node = lines["/First"]
self._namedDests = self.getNamedDestinations()
if node == 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:
subOutlines = []
self.getOutlines(node["/First"], subOutlines)
if subOutlines:
outlines.append(subOutlines)
if "/Next" not in node:
break
node = node["/Next"]
return outlines
def _buildDestination(self, title, array):
page, typ = array[0:2]
array = array[2:]
return Destination(title, page, typ, *array)
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 isinstance(dest, str) and dest in self._namedDests:
outline = self._namedDests[dest]
outline[NameObject("/Title")] = title
else:
raise utils.PdfReadError("Unexpected destination %r" % dest)