简体   繁体   中英

Cropping does not change page size using PyPDF2

I am trying to crop 8.5"x11" pdfs down to a postcard size of 4.25"x6" then upload the cropped pdf to an online printing company.

I was able to use PyPDF2 to crop the pdf. When I open the cropped pdf it looks like the right size, and in the page properties the page size has the correct dimensions. When I try to upload the cropped pdf to the printer, however, I get an error that the page size is 8.5"x11".

I created a test document in Word with the correct page dimensions, then exported that as a pdf, and it was able to be uploaded to the printer web portal correctly.

What is it about the original page size that remains in the cropped document and how can it be changed to match the cropped area?

My code follows:

import PyPDF2
from PyPDF2 import PdfFileReader, PdfFileWriter

# Create a pdf object
pdfFileObj = open('document.pdf', 'rb')
# read the pdf object
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
# create pdf writer object
writerObj = PdfFileWriter()

page = pdfReader.getPage(1)
page.cropBox.setLowerLeft((0, 0))
page.cropBox.setLowerRight((306, 0))
page.cropBox.setUpperLeft((0, 432))
page.cropBox.setUpperRight((306, 432))
# Write the new page
writerObj.addPage(page)
# Create an output pdf
outstream = open('postcardsCropped.pdf', 'wb')
writerObj.write(outstream)
outstream.close()

If you use the scaleTo() method of the page object, it handles changing the size of the mediaBox, cropBox, artBox, and bleedBox for you. You just have to pass in a new width, height parameters in the points dimensions. In your case, it would be

page.scaleTo(4.25*72, 6*72) #1 inch = 72 points. 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM