Skip to content

Instantly share code, notes, and snippets.

@axelbdt
Created January 19, 2024 17:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save axelbdt/02249d3714cff8cf849941a36021607a to your computer and use it in GitHub Desktop.
Save axelbdt/02249d3714cff8cf849941a36021607a to your computer and use it in GitHub Desktop.
Crop a PDF with Python and PyPDF2
from PyPDF2 import PdfWriter, PdfReader

reader = PdfReader('Elixir in Action.pdf')
writer = PdfWriter()

A4_WIDTH = 7.36
A4_HEIGHT = 9.23

page = reader.pages[0]
pdf_width, pdf_height = page.cropbox.upper_right

remove_top = 0.3
remove_bottom = 0.6
remove_right = (remove_top + remove_bottom) * A4_WIDTH / (2 * A4_HEIGHT)
remove_left = remove_right

upper = pdf_height - (remove_top * pdf_height / A4_HEIGHT)
lower = remove_bottom * pdf_height / A4_HEIGHT
right = pdf_width - (remove_right * pdf_width / A4_WIDTH)
left = remove_left * pdf_width / A4_WIDTH

for page in reader.pages:
    page.cropbox.upper_left = (left, upper)
    page.cropbox.lower_right = (right, lower)
    writer.add_page(page)

with open('result.pdf', 'wb') as fp:
    writer.write(fp)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment