forked from realpython/python-basics-exercises
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path4-concatenating-and-merging-pdfs.py
52 lines (39 loc) · 1.41 KB
/
4-concatenating-and-merging-pdfs.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
# 14.4 - Concatenating and Merging PDFs
# Solutions to review exercises
# ***********
# Exercise 1
#
# In the Chapter 13 Practice Files directory there are three PDFs called
# `merge1.pdf`, `merge2.pdf`, and `merge3.pdf`. Using a `PdfFileMerger`
# instance, concatenate the two files `merge1.pdf` and `merge2.pdf`
# using`.append()`.
# ***********
from pathlib import Path
from PyPDF2 import PdfFileMerger
BASE_PATH = Path.home() / "python-basics-exercises/" \
"ch14-interact-with-pdf-files/practice_files"
pdf_paths = [BASE_PATH / "merge1.pdf", BASE_PATH / "merge2.pdf"]
pdf_merger = PdfFileMerger()
for path in pdf_paths:
pdf_merger.append(str(path))
output_path = Path.home() / "concatenated.pdf"
with output_path.open(mode="wb") as output_file:
pdf_merger.write(output_file)
# ***********
# Exercise 2
#
# Using the same `PdfFileMerger` instance from exercise 1, merge the
# file `merge3.pdf` in-between the pages from `merge1.pdf` and
# `merge2.pdf` using `.merge()`.
#
# The final result should be a PDF with three pages. The first page
# should have the number `1` on it, the second should have `2`, and the
# third should have `3`.
# ***********
pdf_merger = PdfFileMerger()
pdf_merger.append(str(output_path))
pdf_path = BASE_PATH / "merge3.pdf"
pdf_merger.merge(1, str(pdf_path))
output_path = Path.home() / "merged.pdf"
with output_path.open(mode="wb") as output_file:
pdf_merger.write(output_file)