Skip to content

Instantly share code, notes, and snippets.

@laogao
Created July 30, 2011 10:46
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save laogao/1115406 to your computer and use it in GitHub Desktop.
Save laogao/1115406 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'
@vfatelinux
Copy link

我的ubuntu系统,第一句要修改成:“#!/usr/bin/python” 后才能正确运行
为啥!

@laogao
Copy link
Author

laogao commented Dec 2, 2011

报什么错?我在debian和ubuntu server上用env python都能正常启动python啊。

@vfatelinux
Copy link

找到原因了 你直接
git clone git://gist.github.com/1115406.git
$chmod +x pdfcrop.py
然后运行,不行的。 提示“ : 没有那个文件或目录”
vim打开后,:set ff=unix就行了, 刚开始我还以为是“#!/usr/bin/env python”的问题。。。

@vfatelinux
Copy link

嘿嘿

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