8000 Move rotating and cropping solutions to a new file · MHHamdan/python-basics-exercises@35c2cfc · GitHub
[go: up one dir, main page]

Skip to content
8000

Commit 35c2cfc

Browse files
committed
Move rotating and cropping solutions to a new file
1 parent 14240e2 commit 35c2cfc

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# 13.2 - Extract Pages From a PDF
2+
# Solutions to review exercises
3+
4+
import os
5+
import copy
6+
from pyPDF2 import PdfFileReader, PdfFileWriter
7+
8+
9+
# Exercise 1
10+
path = "C:/python-basics-exercises/ch13-interact-with-pdf-files/\
11+
practice_files"
12+
13+
input_file_path = os.path.join(path, "Walrus.pdf")
14+
input_file = PdfFileReader(input_file_path)
15+
output_PDF = PdfFileWriter()
16+
17+
input_file.decrypt("IamtheWalrus") # decrypt the input file
18+
19+
20+
# Exercise 2
21+
for page_num in range(0, input_file.getNumPages()):
22+
# rotate pages (call everything page_left for now; will make a copy)
23+
page_left = input_file.getPage(page_num)
24+
page_left.rotateCounterClockwise(90)
25+
26+
page_right = copy.copy(page_left) # split each page in half
27+
upper_right = page_left.mediaBox.upperRight # get original page corner
28+
29+
# crop and add left-side page
30+
page_left.mediaBox.upperRight = (upper_right[0] / 2, upper_right[1])
31+
output_PDF.addPage(page_left)
32+
# crop and add right-side page
33+
page_right.mediaBox.upperLeft = (upper_right[0] / 2, upper_right[1])
34+
output_PDF.addPage(page_right)
35+
36+
37+
# Exercise 3
38+
# save new pages to an output file
39+
output_file_path = os.path.join(path, "Output/Updated Walrus.pdf")
40+
with open(output_file_path, "wb") as output_file:
41+
output_PDF.write(output_file)

0 commit comments

Comments
 (0)
0