Crop pdf on trimbox and save as jpg in Python?

Viewed 373

I'm trying to create a script in Python that crops the pdf from the timbox in the pdf-file and saves the result as a *.jpg-file.

I manage to crop the pdf file (result.pdf is croped) but when I save as a *.jpg it is not croped (same size as test.pdf). Also, think there should be some better way than what I am trying to do, first crop and save the pdf to a file and then convert croped pdf to jpg. Is ut possible to convert to jpg without first save the croped pdf as a file?

from PyPDF4 import PdfFileWriter, PdfFileReader

input = PdfFileReader(open("test.pdf","rb"))
output = PdfFileWriter() 

page = input.getPage(0)
trimboxUpperLeft = page.trimBox.getUpperLeft()
trimboxLowerRight = page.trimBox.getLowerRight()

n = input.getNumPages()

for i in range(n):
    page = input.getPage(i)
    page.cropBox.upperLeft = (trimboxUpperLeft)
    page.cropBox.lowerRight = (trimboxLowerRight)
    output.addPage(page) 

outputStream = open('result.pdf','wb')
output.write(outputStream)
outputStream.close()

from pdf2image import convert_from_path
images = convert_from_path('result.pdf')
for i in range(len(images)):
    images[i].save('Output_'+ str(i) +'.jpg', 'JPEG')
1 Answers
images = convert_from_path('result.pdf', use_cropbox=True, poppler_path='./poppler/bin')

use_cropbox=True By default library use MediaBox, but page.cropBox.upperLeft = (trimboxUpperLeft) change CropBox only.

poppler_path='./poppler/bin' can save poppler in any folder.

Related