0

I've read that PyPDF can have issues while cropping PDF's with python. Anyone able to help me understand why my script crops and leaves the files blank?

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()
Mark Cook
  • 179
  • 1
  • 11
  • As an aside: *"Margin's to be trimmed in pixels"* - you are using those values as points, not as pixels. – mkl Jul 13 '18 at 13:51

1 Answers1

1

The problem could be that you are cropping a small area of your document that may or may not be blank.

There has been a similar question and it should have your answer

#!/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