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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With