Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python PIL/Pillow - Pad image to desired size (eg. A4)

I have a JPG/PNG/PDF image, and I'd like to get it on a A4 page, centered, as PDF (FYI: so that it's easy for my end-users to display/print it).

In either order:

  • pad the image to fill an A4 (with white)
  • transform to PDF

I can do im.save('filename.pdf', 'PDF', resolution=100.0) to save an Image object to PDF, but I don't know how to do the other task.

I'd really prefer using Pillow, but other answers are welcome.

like image 332
lajarre Avatar asked Dec 03 '14 11:12

lajarre


1 Answers

from PIL import Image

im = Image.open(my_image_file)
a4im = Image.new('RGB',
                 (595, 842),   # A4 at 72dpi
                 (255, 255, 255))  # White
a4im.paste(im, im.getbbox())  # Not centered, top-left corner
a4im.save(outputfile, 'PDF', quality=100)

This is taking as hypothesis that my_image_file has the same resolution, 72dpi.

like image 65
lajarre Avatar answered Sep 18 '22 12:09

lajarre