10

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.

1
  • I think you need to get the DPI, then calculate desired resolution for that size using the DPI
    – Kroltan
    Dec 3, 2014 at 11:56

1 Answer 1

21
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.

3
  • 1
    What happens when my_image_file is a different resolution? Do I need to transform im? Jan 3, 2022 at 15:34
  • 1
    You can get DPI of the picture with x_dpi, y_dpi = im.info['dpi'], and use it to compute the expected size of the new picture, basically: int(<size in mm> * <dpi> / 25.4). Oct 30, 2022 at 14:54
  • ... note that sometimes the header with DPI information is not stored with the picture. Oct 31, 2022 at 3:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.