python 裁剪后的 pdf 空白

python pdf blank after crop

我了解到 PyPDF 在使用 python 裁剪 PDF 时可能会出现问题。任何人都可以帮助我理解为什么我的脚本会裁剪并使文件留空?

def cropPDF(filenamePDF):
    top = 57      ###############################
    right = 26    #   Margin's to be trimmed    #
    bottom = 75   #          in pixels          #
    left = 26     ###############################
    pdfIn = PdfFileReader(open(filenamePDF,'rb'))
    pdfOut = PdfFileWriter()
    for page in pdfIn.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)
        pdfOut.addPage(page)
        ous = open(filenamePDF, 'wb')
        pdfOut.write(ous)
        ous.close()

问题可能是您正在裁剪文档的一小部分区域,该区域可能是空白的,也可能不是空白的。

有一个similar question应该有你的答案

#!/usr/bin/python
#

from pyPdf import PdfFileWriter, PdfFileReader

with open("in.pdf", "rb") as in_f:
    input1 = PdfFileReader(in_f)
    output = PdfFileWriter()

    numPages = input1.getNumPages()
    print "document has %s pages." % numPages

    for i in range(numPages):
        page = input1.getPage(i)
        print page.mediaBox.getUpperRight_x(), page.mediaBox.getUpperRight_y()
        page.trimBox.lowerLeft = (25, 25)
        page.trimBox.upperRight = (225, 225)
        page.cropBox.lowerLeft = (50, 50)
        page.cropBox.upperRight = (200, 200)
        output.addPage(page)

    with open("out.pdf", "wb") as out_f:
        output.write(out_f)

Question answered by: danio