Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit6330153

Browse files
committed
Add ch13 section 4 exercise 2 solution
1 parent6ccaa87 commit6330153

File tree

1 file changed

+41
-2
lines changed

1 file changed

+41
-2
lines changed

‎ch13-interact-with-pdf-files/4-rotating-and-cropping-pdf-pages.py

Lines changed: 41 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,12 @@
1010
# counter-clockwise 90 degrees.
1111
# ***********
1212

13-
frompathlibimportPath
13+
frompathlibimportPath
1414

1515
fromPyPDF2importPdfFileReader,PdfFileWriter
1616

1717

18-
pdf_path=Path.home()/"github/realpython/python-basics-exercises/" \
18+
pdf_path=Path.home()/"python-basics-exercises/" \
1919
"ch13-interact-with-pdf-files/practice_files/split_and_rotate.pdf"
2020

2121
pdf_reader=PdfFileReader(str(pdf_path))
@@ -28,3 +28,42 @@
2828
output_path=Path.home()/"rotated.pdf"
2929
withoutput_path.open(mode="wb")asoutput_file:
3030
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+
importcopy
44+
45+
pdf_path=Path.home()/"rotated.pdf"
46+
47+
pdf_reader=PdfFileReader(str(pdf_path))
48+
pdf_writer=PdfFileWriter()
49+
50+
forpageinpdf_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+
withoutput_path.open(mode="wb")asoutput_file:
69+
pdf_writer.write(output_file)

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp