Join and Convert Multiple Images into a Single PDF File – Python Code with Github Link

This simple python code would turn a bunch of images into a neat PDF. No fuss, no frills—just a straightforward way to bring your pictures together. Whether you’re creating a presentation or organizing memories, this code simplifies the process. It’s like a digital glue that effortlessly sticks your images into a cohesive story, all neatly packed in a PDF. Let’s dive in and check how the code works.

What this code does:

1. Takes a folder containing images that you need joined and converted into a pdf format.

2. This folder can contain any amount of images you need. But they need to be ordered in the order of page numbers. So your page 1 should be an image numbered 1 and so on.

3. Then this code will compute the number of images in the folder. We have used os.listdir in order to do this. Like this:

num=0
for element in os.listdir(folder_dir):
    element_path=os.path.join(folder_dir, element)
    if os.path.isfile(element_path):
        num+=1

4. In order to be converted into a pdf format, each image needs to be in RGB mode. So next we have converted each image into RGB mode. This is done using Pillow.

5. Make a python list of images, and append each RGB converted image in this list.

6. Use :

image_set[0].save(r'C:\Users\location\my_images2.pdf', save_all=True, append_images=image_set[1:])

Where image_set is the list of RGB modified images. Here, the first image of the list is converted to PDF and rest of the images are appended to it.

Final Code :

# import the modules
import os, os.path
from PIL import Image

# get the path/directory
folder_dir = r'C:\\Users\\manas\\Coding Playground\\PythonP\\One Piece Scraper\\chapters\\ch1\\'

# get number of elements in directory
num=0
for element in os.listdir(folder_dir):
    element_path=os.path.join(folder_dir, element)
    if os.path.isfile(element_path):
        num+=1
# print(num)

image_set = []
counter = 1


while(counter <= num):
    image = Image.open(r"C:\\Users\\Location" + str(counter) + ".jpg")
    image_mod = image.convert('RGB')
    image_set.append(image)
    counter += 1


image_set[0].save(r'C:\Users\Location\\my_images2.pdf', save_all=True, append_images=image_set[1:])

folder_dir : This is the folder location of the images

Github Link : https://github.com/ManasiTilak/jpgtopdf

Leave a Comment

Your email address will not be published. Required fields are marked *