Wednesday, April 28, 2021

Merge images to PDF Using 'Python Imaging Library' (PIL)

 This script will merge any given amount of images into a single PDF file.



from PIL import Image


# List of images... 4 images in this case, so we should get a pdf with 4 pages.
image_files = [r"C:\Users\Yusuf_08039508010\Desktop\L1.jpeg", r"C:\Users\Yusuf_08039508010\Desktop\L2.jpeg", r"C:\Users\Yusuf_08039508010\Desktop\L3.jpeg", r"C:\Users\Yusuf_08039508010\Desktop\L4.jpeg"]

imagelist = []
for img in image_files:
    print('Processing...', img)
    # read in image
    img1 = Image.open(img)
    
    # convert to RGP
    img2 = img1.convert('RGB')
    
    imagelist.append(img2)
    
    print('Done for...', img.split('\\')[-1])
    
# To prevent appending last image to the beginning...
start_img = Image.open(image_files[0])
start_img = start_img.convert('RGB')

# Delete first image from list 'imagelist'...
del imagelist[0] # imagelist.pop(0) or imagelist[1:]

# merge images to pdf...
start_img.save(r'merged_L1-4.pdf', save_all=True, append_images=imagelist)




That is it!

No comments:

Post a Comment