6

Im trying to convert png files into pdf's. PIL seems to be the way to do it but Im getting an error (cannot save mode RGBA) when running it

Code:

import os
import PIL
from PIL import Image

path = 'E:\path_to_file'
filename = '15868799_1.png'
fullpath_filename = os.path.join(path, filename)
im = PIL.Image.open(fullpath_filename)
newfilename = '15868799.pdf'
newfilename_fullpath = os.path.join(path, newfilename)
PIL.Image.Image.save(im, newfilename_fullpath, "PDF", resoultion=100.0)

Error:

 File "C:\Python\lib\site-packages\PIL\PdfImagePlugin.py", line 148, in _save
 raise ValueError("cannot save mode %s" % im.mode)
 ValueError: cannot save mode RGBA
shahaf
  • 4,750
  • 2
  • 29
  • 32
user9794893
  • 133
  • 3
  • 11

2 Answers2

14

You need to convert your PNG from RGBA to RGB first.

Sample code:

from PIL import Image

PNG_FILE = 'E:\path_to_file\15868799_1.png'
PDF_FILE = 'E:\path_to_file\15868799.pdf'

rgba = Image.open(PNG_FILE)
rgb = Image.new('RGB', rgba.size, (255, 255, 255))  # white background
rgb.paste(rgba, mask=rgba.split()[3])               # paste using alpha channel as mask
rgb.save(PDF_FILE, 'PDF', resoultion=100.0)
Andriy Makukha
  • 7,580
  • 1
  • 38
  • 49
0

To convert multiple RGBA png images, I opted for this code piece,

from PIL import Image

_source = "/mnt/ssd/presentations"

_files = [] # List of image path populated using glob

def conv_rgba_to_rgb(_rgba):
  _rgba = Image.open(_rgba)
  _rgb = Image.new('RGB', _rgba.size, (255, 255, 255))
  _rgb.paste(_rgba, mask=_rgba.split()[3])
  return _rgb

_images = [conv_rgba_to_rgb(_f) for _f in _files]
_pdf_path = f"{_source}/phd-presentation.pdf"
_images[0].save(_pdf_path, "PDF", resolution=72.0, save_all=True, append_images=_images[1:])
Vishal Kumar Sahu
  • 1,232
  • 3
  • 15
  • 27