Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resize pdf pages in Python

Tags:

python

pdf

pypdf

I am using python to crop pdf pages. Everything works fine, but how do I change the page size(width)?

This is my crop code:

input = PdfFileReader(file('my.pdf', 'rb'))
p = input.getPage(1)
(w, h) = p.mediaBox.upperRight
p.mediaBox.upperRight = (w/4, h)
output.addPage(p)

When I crop pages, I need to resize them as well, how can I do this?

like image 459
user319854 Avatar asked Oct 25 '25 15:10

user319854


1 Answers

This answer is really long overdue, and maybe the older versions of PyPDF2 didn't have this functionality, but its actually quite simple with version 1.26.0

import PyPDF2

pdf = "YOUR PDF FILE PATH.pdf"

pdf = PyPDF2.PdfFileReader(pdf)
page0 = pdf.getPage(0)
page0.scaleBy(0.5)  # float representing scale factor - this happens in-place
writer = PyPDF2.PdfFileWriter()  # create a writer to save the updated results
writer.addPage(page0)
with open("YOUR OUTPUT PDF FILE PATH.pdf", "wb+") as f:
    writer.write(f)
like image 165
Ahsin Shabbir Avatar answered Oct 27 '25 05:10

Ahsin Shabbir