|
10 | 10 | # counter-clockwise 90 degrees.
|
11 | 11 | # ***********
|
12 | 12 |
|
13 |
| -from pathlib import Path |
| 13 | +from pathlib import Path |
14 | 14 |
|
15 | 15 | from PyPDF2 import PdfFileReader, PdfFileWriter
|
16 | 16 |
|
17 | 17 |
|
18 |
| -pdf_path = Path.home() / "github/realpython/python-basics-exercises/" \ |
| 18 | +pdf_path = Path.home() / "python-basics-exercises/" \ |
19 | 19 | "ch13-interact-with-pdf-files/practice_files/split_and_rotate.pdf"
|
20 | 20 |
|
21 | 21 | pdf_reader = PdfFileReader(str(pdf_path))
|
|
28 | 28 | output_path = Path.home() / "rotated.pdf"
|
29 | 29 | with output_path.open(mode="wb") as output_file:
|
30 | 30 | pdf_writer.write(output_file)
|
| 31 | + |
| 32 | + |
| 33 | +# *********** |
| 34 | +# Exercise 2 |
| 35 | +# |
| 36 | +# Using the `rotated.pdf` file you created in exercise 1, split each |
| 37 | +# page of the PDF vertically in the middle. Create a new PDF called |
| 38 | +# `split.pdf` in your home directory containing all of the split pages. |
| 39 | +# |
| 40 | +# `split.pdf` should have four pages with the numbers `1`, `2`, `3`, |
| 41 | +# and `4`, in order. |
| 42 | +# *********** |
| 43 | +import copy |
| 44 | + |
| 45 | +pdf_path = Path.home() / "rotated.pdf" |
| 46 | + |
| 47 | +pdf_reader = PdfFileReader(str(pdf_path)) |
| 48 | +pdf_writer = PdfFileWriter() |
| 49 | + |
| 50 | +for page in pdf_reader.pages: |
| 51 | + # Calculate the coordinates at the top center of the page |
| 52 | + upper_right_coords = page.mediaBox.upperRight |
| 53 | + center_coords = (upper_right_coords[0] / 2, upper_right_coords[1]) |
| 54 | + # Create two copies of the page, one for the left side and one for |
| 55 | + # the right side |
| 56 | + left_page = copy.deepcopy(page) |
| 57 | + right_page = copy.deepcopy(page) |
| 58 | + # Crop the pages by setting the upper right corner coordinates |
| 59 | + # of the left hand page and the upper left corner coordinates of |
| 60 | + # the right hand page to the top center coordinates |
| 61 | + left_page.mediaBox.upperRight = center_coords |
| 62 | + right_page.mediaBox.upperLeft = center_coords |
| 63 | + # Add the cropped pages to the PDF writer |
| 64 | + pdf_writer.addPage(left_page) |
| 65 | + pdf_writer.addPage(right_page) |
| 66 | + |
| 67 | +output_path = Path.home() / "split.pdf" |
| 68 | +with output_path.open(mode="wb") as output_file: |
| 69 | + pdf_writer.write(output_file) |
0 commit comments