8000 Add ch 13 second challenge practice file and solution · tejussm/python-basics-exercises@1bac150 · GitHub
[go: up one dir, main page]

Skip to content

Commit 1bac150

Browse files
committed
Add ch 13 second challenge practice file and solution
1 parent 2c6d799 commit 1bac150

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# 13.7 - Challenge: Unscramble a PDF
2+
# Solution to challenge
3+
4+
from pathlib import Path
5+
6+
from PyPDF2 import PdfFileReader, PdfFileWriter
7+
8+
9+
def get_page_text(page):
10+
return page.extractText()
11+
12+
13+
pdf_path = Path.home() / "github/realpython/python-basics-exercises/" \
14+
"ch13-interact-with-pdf-files/practice_files/scrambled.pdf"
15+
16+
pdf_reader = PdfFileReader(str(pdf_path))
17+
pdf_writer = PdfFileWriter()
18+
19+
pages = list(pdf_reader.pages)
20+
pages.sort(key=get_page_text)
21+
22+
for page in pages:
23+
rotation_degrees = page["/Rotate"]
24+
if rotation_degrees < 0:
25+
page.rotateClockwise(-rotation_degrees)
26+
elif rotation_degrees > 0:
27+
page.rotateCounterClockwise(rotation_degrees)
28+
pdf_writer.addPage(page)
29+
30+
output_path = Path.home() / "unscrambled.pdf"
31+
with output_path.open(mode="wb") as output_file:
32+
pdf_writer.write(output_file)
Binary file not shown.

0 commit comments

Comments
 (0)
0