-
Notifications
You must be signed in to change notification settings - Fork 0
/
_merger.py
644 lines (541 loc) · 22.9 KB
/
_merger.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
# Original Copyright 2006, Mathieu Fenniak
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * The name of the author may not be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
from io import BytesIO
from io import FileIO as file
from PyPDF2._reader import PdfFileReader
from PyPDF2._utils import isString, str_
from PyPDF2._writer import PdfFileWriter
from PyPDF2.constants import PagesAttributes as PA
from PyPDF2.generic import *
from PyPDF2.pagerange import PageRange
ERR_CLOSED_WRITER = "close() was called and thus the writer cannot be used anymore"
class _MergedPage(object):
"""
_MergedPage is used internally by PdfFileMerger to collect necessary
information on each page that is being merged.
"""
def __init__(self, pagedata, src, id):
self.src = src
self.pagedata = pagedata
self.out_pagedata = None
self.id = id
class PdfFileMerger(object):
"""
Initializes a PdfFileMerger object. PdfFileMerger merges multiple PDFs
into a single PDF. It can concatenate, slice, insert, or any combination
of the above.
See the functions :meth:`merge()<merge>` (or :meth:`append()<append>`)
and :meth:`write()<write>` for usage information.
: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 bool overwriteWarnings: Determines whether to override Python's
``warnings.py`` module with a custom implementation (defaults to
``True``).
"""
def __init__(self, strict=True, overwriteWarnings=True):
self.inputs = []
self.pages = []
self.output = PdfFileWriter()
self.bookmarks = []
self.named_dests = []
self.id_count = 0
self.strict = strict
self.overwriteWarnings = overwriteWarnings
def merge(
self, position, fileobj, bookmark=None, pages=None, import_bookmarks=True
):
"""
Merges the pages from the given file into the output file at the
specified page number.
:param int position: The *page number* to insert this file. File will
be inserted after the given number.
:param fileobj: 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 str bookmark: Optionally, you may specify a bookmark to be applied at
the beginning of the included file by supplying the text of the bookmark.
:param pages: can be a :class:`PageRange<PyPDF2.pagerange.PageRange>` or a ``(start, stop[, step])`` tuple
to merge only the specified range of pages from the source
document into the output document.
:param bool import_bookmarks: You may prevent the source document's bookmarks
from being imported by specifying this as ``False``.
"""
# This parameter is passed to self.inputs.append and means
# that the stream used was created in this method.
my_file = False
# If the fileobj parameter is a string, assume it is a path
# and create a file object at that location. If it is a file,
# copy the file's contents into a BytesIO stream object; if
# it is a PdfFileReader, copy that reader's stream into a
# BytesIO stream.
# If fileobj is none of the above types, it is not modified
decryption_key = None
if isString(fileobj):
fileobj = file(fileobj, "rb")
my_file = True
elif hasattr(fileobj, "seek") and hasattr(fileobj, "read"):
fileobj.seek(0)
filecontent = fileobj.read()
fileobj = BytesIO(filecontent)
my_file = True
elif isinstance(fileobj, PdfFileReader):
if hasattr(fileobj, "_decryption_key"):
decryption_key = fileobj._decryption_key
orig_tell = fileobj.stream.tell()
fileobj.stream.seek(0)
filecontent = StreamIO(fileobj.stream.read())
fileobj.stream.seek(orig_tell) # reset the stream to its original location
fileobj = filecontent
my_file = True
# Create a new PdfFileReader instance using the stream
# (either file or BytesIO) created above
pdfr = PdfFileReader(
fileobj, strict=self.strict, overwriteWarnings=self.overwriteWarnings
)
if decryption_key is not None:
pdfr._decryption_key = decryption_key
# Find the range of pages to merge.
if pages is None:
pages = (0, pdfr.getNumPages())
elif isinstance(pages, PageRange):
pages = pages.indices(pdfr.getNumPages())
elif not isinstance(pages, tuple):
raise TypeError('"pages" must be a tuple of (start, stop[, step])')
srcpages = []
if bookmark:
bookmark = Bookmark(
TextStringObject(bookmark),
NumberObject(self.id_count),
NameObject("/Fit"),
)
outline = []
if import_bookmarks:
outline = pdfr.getOutlines()
outline = self._trim_outline(pdfr, outline, pages)
if bookmark:
self.bookmarks += [bookmark, outline]
else:
self.bookmarks += outline
dests = pdfr.namedDestinations
dests = self._trim_dests(pdfr, dests, pages)
self.named_dests += dests
# Gather all the pages that are going to be merged
for i in range(*pages):
pg = pdfr.getPage(i)
id = self.id_count
self.id_count += 1
mp = _MergedPage(pg, pdfr, id)
srcpages.append(mp)
self._associate_dests_to_pages(srcpages)
self._associate_bookmarks_to_pages(srcpages)
# Slice to insert the pages at the specified position
self.pages[position:position] = srcpages
# Keep track of our input files so we can close them later
self.inputs.append((fileobj, pdfr, my_file))
def append(self, fileobj, bookmark=None, pages=None, import_bookmarks=True):
"""
Identical to the :meth:`merge()<merge>` method, but assumes you want to concatenate
all pages onto the end of the file instead of specifying a position.
:param fileobj: 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 str bookmark: Optionally, you may specify a bookmark to be applied at
the beginning of the included file by supplying the text of the bookmark.
:param pages: can be a :class:`PageRange<PyPDF2.pagerange.PageRange>` or a ``(start, stop[, step])`` tuple
to merge only the specified range of pages from the source
document into the output document.
:param bool import_bookmarks: You may prevent the source document's bookmarks
from being imported by specifying this as ``False``.
"""
self.merge(len(self.pages), fileobj, bookmark, pages, import_bookmarks)
def write(self, fileobj):
"""
Writes all data that has been merged to the given output file.
:param fileobj: Output file. Can be a filename or any kind of
file-like object.
"""
my_file = False
if isString(fileobj):
fileobj = file(fileobj, "wb")
my_file = True
# Add pages to the PdfFileWriter
# The commented out line below was replaced with the two lines below it to allow PdfFileMerger to work with PyPdf 1.13
for page in self.pages:
self.output.addPage(page.pagedata)
page.out_pagedata = self.output.getReference(
self.output._pages.getObject()[PA.KIDS][-1].getObject()
)
# idnum = self.output._objects.index(self.output._pages.getObject()[PA.KIDS][-1].getObject()) + 1
# page.out_pagedata = IndirectObject(idnum, 0, self.output)
# Once all pages are added, create bookmarks to point at those pages
self._write_dests()
self._write_bookmarks()
# Write the output to the file
self.output.write(fileobj)
if my_file:
fileobj.close()
def close(self):
"""
Shuts all file descriptors (input and output) and clears all memory
usage.
"""
self.pages = []
for fo, _pdfr, mine in self.inputs:
if mine:
fo.close()
self.inputs = []
self.output = None
def addMetadata(self, infos):
"""
Add custom metadata to the output.
:param dict infos: a Python dictionary where each key is a field
and each value is your new metadata.
Example: ``{u'/Title': u'My title'}``
"""
if self.output is None:
raise RuntimeError(ERR_CLOSED_WRITER)
self.output.addMetadata(infos)
def setPageLayout(self, layout):
"""
Set the page layout
:param str layout: The page layout to be used
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
"""
self.output.setPageLayout(layout)
def setPageMode(self, mode):
"""
Set the page mode.
:param str mode: The page mode to use.
Valid modes are:
/UseNone Do not show outlines or thumbnails panels
/UseOutlines Show outlines (aka bookmarks) panel
/UseThumbs Show page thumbnails panel
/FullScreen Fullscreen view
/UseOC Show Optional Content Group (OCG) panel
/UseAttachments Show attachments panel
"""
self.output.setPageMode(mode)
def _trim_dests(self, pdf, dests, pages):
"""
Removes any named destinations that are not a part of the specified
page set.
"""
new_dests = []
for k, o in list(dests.items()):
for j in range(*pages):
if pdf.getPage(j).getObject() == o["/Page"].getObject():
o[NameObject("/Page")] = o["/Page"].getObject()
assert str_(k) == str_(o["/Title"])
new_dests.append(o)
break
return new_dests
def _trim_outline(self, pdf, outline, pages):
"""
Removes any outline/bookmark entries that are not a part of the
specified page set.
"""
new_outline = []
prev_header_added = True
for i, o in enumerate(outline):
if isinstance(o, list):
sub = self._trim_outline(pdf, o, pages)
if sub:
if not prev_header_added:
new_outline.append(outline[i - 1])
new_outline.append(sub)
else:
prev_header_added = False
for j in range(*pages):
if pdf.getPage(j).getObject() == o["/Page"].getObject():
o[NameObject("/Page")] = o["/Page"].getObject()
new_outline.append(o)
prev_header_added = True
break
return new_outline
def _write_dests(self):
dests = self.named_dests
for v in dests:
pageno = None
pdf = None
if "/Page" in v:
for i, p in enumerate(self.pages):
if p.id == v["/Page"]:
v[NameObject("/Page")] = p.out_pagedata
pageno = i
pdf = p.src # noqa: F841
break
if pageno is not None:
self.output.addNamedDestinationObject(v)
def _write_bookmarks(self, bookmarks=None, parent=None):
if bookmarks is None:
bookmarks = self.bookmarks
last_added = None
for bookmark in bookmarks:
if isinstance(bookmark, list):
self._write_bookmarks(bookmark, last_added)
continue
page_no = None
if "/Page" in bookmark:
for page_no, page in enumerate(self.pages): # noqa: B007
if page.id == bookmark["/Page"]:
self._write_bookmark_on_page(bookmark, page)
break
if page_no is not None:
del bookmark["/Page"], bookmark["/Type"]
last_added = self.output.addBookmarkDict(bookmark, parent)
def _write_bookmark_on_page(self, bookmark, page):
# b[NameObject('/Page')] = p.out_pagedata
args = [NumberObject(page.id), NameObject(bookmark["/Type"])]
# nothing more to add
# if b['/Type'] == '/Fit' or b['/Type'] == '/FitB'
if bookmark["/Type"] == "/FitH" or bookmark["/Type"] == "/FitBH":
if "/Top" in bookmark and not isinstance(bookmark["/Top"], NullObject):
args.append(FloatObject(bookmark["/Top"]))
else:
args.append(FloatObject(0))
del bookmark["/Top"]
elif bookmark["/Type"] == "/FitV" or bookmark["/Type"] == "/FitBV":
if "/Left" in bookmark and not isinstance(bookmark["/Left"], NullObject):
args.append(FloatObject(bookmark["/Left"]))
else:
args.append(FloatObject(0))
del bookmark["/Left"]
elif bookmark["/Type"] == "/XYZ":
if "/Left" in bookmark and not isinstance(bookmark["/Left"], NullObject):
args.append(FloatObject(bookmark["/Left"]))
else:
args.append(FloatObject(0))
if "/Top" in bookmark and not isinstance(bookmark["/Top"], NullObject):
args.append(FloatObject(bookmark["/Top"]))
else:
args.append(FloatObject(0))
if "/Zoom" in bookmark and not isinstance(bookmark["/Zoom"], NullObject):
args.append(FloatObject(bookmark["/Zoom"]))
else:
args.append(FloatObject(0))
del bookmark["/Top"], bookmark["/Zoom"], bookmark["/Left"]
elif bookmark["/Type"] == "/FitR":
if "/Left" in bookmark and not isinstance(bookmark["/Left"], NullObject):
args.append(FloatObject(bookmark["/Left"]))
else:
args.append(FloatObject(0))
if "/Bottom" in bookmark and not isinstance(
bookmark["/Bottom"], NullObject
):
args.append(FloatObject(bookmark["/Bottom"]))
else:
args.append(FloatObject(0))
if "/Right" in bookmark and not isinstance(bookmark["/Right"], NullObject):
args.append(FloatObject(bookmark["/Right"]))
else:
args.append(FloatObject(0))
if "/Top" in bookmark and not isinstance(bookmark["/Top"], NullObject):
args.append(FloatObject(bookmark["/Top"]))
else:
args.append(FloatObject(0))
del (
bookmark["/Left"],
bookmark["/Right"],
bookmark["/Bottom"],
bookmark["/Top"],
)
bookmark[NameObject("/A")] = DictionaryObject(
{NameObject("/S"): NameObject("/GoTo"), NameObject("/D"): ArrayObject(args)}
)
# not certain what the returned values mean
# or if they are correct cj
page_no = i
pdf = p.src # noqa: F841
return (page_no, pdf)
def _associate_dests_to_pages(self, pages):
for nd in self.named_dests:
pageno = None
np = nd["/Page"]
if isinstance(np, NumberObject):
continue
for p in pages:
if np.getObject() == p.pagedata.getObject():
pageno = p.id
if pageno is not None:
nd[NameObject("/Page")] = NumberObject(pageno)
else:
raise ValueError("Unresolved named destination '%s'" % (nd["/Title"],))
def _associate_bookmarks_to_pages(self, pages, bookmarks=None):
if bookmarks is None:
bookmarks = self.bookmarks
for b in bookmarks:
if isinstance(b, list):
self._associate_bookmarks_to_pages(pages, b)
continue
pageno = None
bp = b["/Page"]
if isinstance(bp, NumberObject):
continue
for p in pages:
if bp.getObject() == p.pagedata.getObject():
pageno = p.id
if pageno is not None:
b[NameObject("/Page")] = NumberObject(pageno)
else:
raise ValueError("Unresolved bookmark '%s'" % (b["/Title"],))
def findBookmark(self, bookmark, root=None):
if root is None:
root = self.bookmarks
for i, b in enumerate(root):
if isinstance(b, list):
res = self.findBookmark(bookmark, b)
if res:
return [i] + res
elif b == bookmark or b["/Title"] == bookmark:
return [i]
return None
def addBookmark(
self,
title,
pagenum,
parent=None,
color=None,
bold=False,
italic=False,
fit="/Fit",
*args
):
"""
Add a bookmark to this PDF file.
:param str title: Title to use for this bookmark.
:param int pagenum: Page number this bookmark will point to.
:param parent: A reference to a parent bookmark to create nested
bookmarks.
:param tuple color: Color of the bookmark as a red, green, blue tuple
from 0.0 to 1.0
:param bool bold: Bookmark is bold
:param bool italic: Bookmark is italic
:param str fit: The fit of the destination page. See
:meth:`addLink()<addLin>` for details.
"""
if self.output is None:
raise RuntimeError(ERR_CLOSED_WRITER)
if len(self.output.getObject(self.output._pages)["/Kids"]) > 0:
page_ref = self.output.getObject(self.output._pages)["/Kids"][pagenum]
else:
page_ref = self.output.getObject(self.output._pages)
action = DictionaryObject()
zoom_args = []
for a in args:
if a is not None:
zoom_args.append(NumberObject(a))
else:
zoom_args.append(NullObject())
dest = Destination(
NameObject("/" + title + " bookmark"), page_ref, NameObject(fit), *zoom_args
)
dest_array = dest.getDestArray()
action.update(
{NameObject("/D"): dest_array, NameObject("/S"): NameObject("/GoTo")}
)
action_ref = self.output._addObject(action)
outline_ref = self.output.getOutlineRoot()
if parent is None:
parent = outline_ref
bookmark = TreeObject()
bookmark.update(
{
NameObject("/A"): action_ref,
NameObject("/Title"): createStringObject(title),
}
)
if color is not None:
bookmark.update(
{NameObject("/C"): ArrayObject([FloatObject(c) for c in color])}
)
format = 0
if italic:
format += 1
if bold:
format += 2
if format:
bookmark.update({NameObject("/F"): NumberObject(format)})
bookmark_ref = self.output._addObject(bookmark)
parent = parent.getObject()
parent.addChild(bookmark_ref, self.output)
return bookmark_ref
def addNamedDestination(self, title, pagenum):
"""
Add a destination to the output.
:param str title: Title to use
:param int pagenum: Page number this destination points at.
"""
dest = Destination(
TextStringObject(title),
NumberObject(pagenum),
NameObject("/FitH"),
NumberObject(826),
)
self.named_dests.append(dest)
class OutlinesObject(list):
def __init__(self, pdf, tree, parent=None):
list.__init__(self)
self.tree = tree
self.pdf = pdf
self.parent = parent
def remove(self, index):
obj = self[index]
del self[index]
self.tree.removeChild(obj)
def add(self, title, pagenum):
page_ref = self.pdf.getObject(self.pdf._pages)[PA.KIDS][pagenum]
action = DictionaryObject()
action.update(
{
NameObject("/D"): ArrayObject(
[page_ref, NameObject("/FitH"), NumberObject(826)]
),
NameObject("/S"): NameObject("/GoTo"),
}
)
action_ref = self.pdf._addObject(action)
bookmark = TreeObject()
bookmark.update(
{
NameObject("/A"): action_ref,
NameObject("/Title"): createStringObject(title),
}
)
self.pdf._addObject(bookmark)
self.tree.addChild(bookmark)
def removeAll(self):
for child in self.tree.children():
self.tree.removeChild(child)
self.pop()