Skip to content

Instantly share code, notes, and snippets.

@edykim
Created August 20, 2020 22:17
Show Gist options
  • Select an option

  • Save edykim/ca0d1f59c5299e139c1a6a152e9295df to your computer and use it in GitHub Desktop.

Select an option

Save edykim/ca0d1f59c5299e139c1a6a152e9295df to your computer and use it in GitHub Desktop.
#!/usr/bin/python
import sys
from PyPDF2 import PdfFileWriter, PdfFileReader
filename = sys.argv[1]
newFilename = filename.replace(".pdf", ".cropped.pdf")
trimWidth = 65
trimHeight = 35
with open(filename, "rb") as in_f:
input1 = PdfFileReader(in_f)
output = PdfFileWriter()
numPages = input1.getNumPages()
print('document has {} pages.'.format(numPages))
for i in range(numPages):
page = input1.getPage(i)
width = page.mediaBox.getUpperRight_x()
height = page.mediaBox.getUpperRight_y()
page.trimBox.lowerLeft = (trimWidth, trimHeight)
page.trimBox.upperRight = (width - trimWidth, height - trimHeight)
page.cropBox.lowerLeft = (trimWidth, trimHeight)
page.cropBox.upperRight = (width - trimWidth, height - trimHeight)
output.addPage(page)
print('Cropped and saved as {}'.format(newFilename))
with open(newFilename, "wb") as out_f:
output.write(out_f)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment