forked from py-pdf/pypdf
-
Notifications
You must be signed in to change notification settings - Fork 60
Expand file tree
/
Copy pathbasic_merging.py
More file actions
79 lines (58 loc) · 1.98 KB
/
basic_merging.py
File metadata and controls
79 lines (58 loc) · 1.98 KB
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
#!/usr/bin/env python
"""
Sample code that demonstrates merging together three PDFs into one, picking and choosing which pages appear in which order.
Selected pages can be added to the end of the output PDF being built, or inserted in the middle.
This example takes input from the command line.
"""
from __future__ import print_function
from os import pardir
from os.path import abspath, dirname, join
from sys import argv, path
from pypdf import PdfFileMerger, PdfFileReader
SAMPLE_CODE_ROOT = dirname(__file__)
SAMPLE_PDF_ROOT = join(SAMPLE_CODE_ROOT, "pdfsamples")
path.append(abspath(join(SAMPLE_CODE_ROOT, pardir)))
FLAG_HELP = {"-h", "--help"}
USAGE = """\
Merges three PDF documents input from the command line.
%(progname)s: <PDF 1> <PDF 2> <PDF 3> [output filename]
%(progname)s: [-h | --help]
""" % {
"progname": argv[0]
}
def main():
requiredPages = 3
output = "PyPDF-Merging-Output.pdf"
if set(argv) & FLAG_HELP:
print(USAGE)
exit(0)
elif len(argv) < 4:
print(USAGE)
exit(1)
else:
files = [f.strip() for f in argv[1:4]]
if len(argv) > 4:
output = argv[4].strip()
reader1 = PdfFileReader(files[0])
merger = PdfFileMerger(open(output, "wb"))
if reader1.numPages < requiredPages:
print(
"File 1 requires %d pages, but it has just %d"
% (requiredPages, reader1.numPages)
)
exit(1)
input1 = open(files[0], "rb")
input2 = open(files[1], "rb")
input3 = open(files[2], "rb")
# Add the first 3 pages of input1 to output
merger.append(fileobj=input1, pages=(0, 3))
# Insert the first page of input2 into the output beginning after the
# second page
merger.merge(position=2, fileobj=input2, pages=(0, 1))
# Append entire input3 document to the end of the output document
merger.append(input3)
merger.write()
print("Output successfully written to", output)
merger.close()
if __name__ == "__main__":
main()