Skip to content

Instantly share code, notes, and snippets.

@alexzhan
Forked from laogao/pdfcrop.py
Created October 7, 2011 12:53
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save alexzhan/1270222 to your computer and use it in GitHub Desktop.
Save alexzhan/1270222 to your computer and use it in GitHub Desktop.
Use pyPdf to crop a pdf file according to user inputs
#!/usr/bin/env python
import sys
if __name__ == '__main__' and len(sys.argv) > 5 and sys.argv[1][-3:].upper() == 'PDF':
original = sys.argv[1]
target = original[:-4] + '.cropped.pdf'
left = int(sys.argv[2])
top = int(sys.argv[3])
right = int(sys.argv[4])
bottom = int(sys.argv[5])
from pyPdf import PdfFileWriter, PdfFileReader
pdf = PdfFileReader(file(original, 'rb'))
out = PdfFileWriter()
for page in pdf.pages:
page.mediaBox.upperRight = (page.mediaBox.getUpperRight_x() - right, page.mediaBox.getUpperRight_y() - top)
page.mediaBox.lowerLeft = (page.mediaBox.getLowerLeft_x() + left, page.mediaBox.getLowerLeft_y() + bottom)
out.addPage(page)
ous = file(target, 'wb')
out.write(ous)
ous.close()
else:
print 'EXAMPLE: pdfcrop.py original.pdf 20 30 20 40'
@MayankDe
Copy link

MayankDe commented Mar 8, 2022

Hi, Mayank Dehariya here, I have a query like I want to crop a pdf using coordinates and save it django server.How could be it paoossible.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment