Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting png to pdf with PIL save mode error

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
like image 982
user9794893 Avatar asked Jun 08 '18 14:06

user9794893


1 Answers

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)
like image 137
Andriy Makukha Avatar answered Nov 15 '22 10:11

Andriy Makukha