Created
March 30, 2020 15:10
-
-
Save rbpatt2019/ee8c03b446028c9e63f34ef2024afbb5 to your computer and use it in GitHub Desktop.
Save multiple images to one pdf using Pillow
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from glob import glob | |
import os.path as path | |
from PIL import Image | |
def convert(img): | |
'''Convert an RGBA image to an RGB image | |
If the passed image has: | |
img.mode == 'RGBA' | |
then it will be converted to RGB. | |
Else, the image itself will be returned. | |
:PARAM: img - an object of type PIL.Image | |
:RETURNS: img as RGBA | |
''' | |
if img.mode == 'RGBA': | |
rgb = Image.new('RGB', img.size, (255,255,255)) | |
rgb.paste(img, mask=img.split()[3]) | |
return(rgb) | |
else: | |
return(img) | |
def save_as_pdf(files=None, out='images.pdf'): | |
'''Save a list ofimage files as a concatenated pdf | |
Take a list of images and save them to a pdf. | |
One image per page, with no image compression | |
:PARAM: files: list | |
List of paths to images. | |
Tip: use glob to get these `glob(*.png)` | |
If not passed, this fucntion will operate on all pngs in the current directory | |
:PARAM: out: str | |
Name of pdf to be saved | |
:RETURNS: bool | |
True if successful | |
''' | |
if files is None: | |
files = glob('*.png') | |
else: | |
for i in files: | |
if not path.isfile(i): | |
raise FileNotFoundError(f'{i} does not exist') | |
if path.isfile(out): | |
raise FileExistsError(f'{out} already exists.') | |
images = [Image.open(i) for i in files] | |
images = [convert(i) for i in images] | |
images[0].save( | |
out, | |
'PDF', | |
resolution=100.00, | |
save_all=True, | |
append_images=images[1:] | |
) | |
return(True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment