将PDF页面裁剪为内容

时间:2018-11-27 18:14:27

标签: python pdf

使用Python,是否可以将pdf页面裁剪为内容,如下图所示,该内容是在Inkscape中完成任务的?内容的边界区域应自动找到。

A pdf file is cropped to the content here using Inkscape

使用PyPDF2我可以裁剪页面,但是它需要手动找到坐标,这对于大量文件而言是乏味的。在Inkscape中,会自动找到坐标。

我正在使用的代码如下所示,示例输入文件为available here

# Python 3.7.0
import PyPDF2 # version 1.26.0

with open('document-1.pdf','rb') as fin:
    pdf = PyPDF2.PdfFileReader(fin)
    page = pdf.getPage(0)

    # Coordinates found by inspection.
    # Can these coordinates be found automatically?
    page.cropBox.lowerLeft=(88,322)
    page.cropBox.upperRight = (508,602)

    output = PyPDF2.PdfFileWriter()
    output.addPage(page)

    with open('cropped-1.pdf','wb') as fo:
        output.write(fo)

1 个答案:

答案 0 :(得分:0)

我能够使用可点子安装的CLI https://pypi.org/project/pdfCropMargins/

不幸的是,我不认为有一种直接从脚本中调用它的好方法,所以现在我正在使用os.system

$ python -m pip install pdfCropMargins --user
$ pdf-crop-margins document.pdf -o output.pdf -p 0
import os
os.system('pdf-crop-margins document.pdf -o output.pdf -p 0')

enter image description here