File tree 2 files changed +32
-0
lines changed
ch13-interact-with-pdf-files 2 files changed +32
-0
lines changed Original file line number Diff line number Diff line change
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 )
You can’t perform that action at this time.
0 commit comments