Python Program to Convert Multiple Images into a PDF
A Python utility that converts multiple images into a single PDF file using the Pillow library. Supports all major image formats and preserves the order of images to produce a clean, merged PDF.
Explanation
An Image-to-PDF Converter is a simple Python program that combines multiple images into a single PDF file. This is very useful when creating documents from scanned pages, photos, notes, receipts, assignments, or screenshots.
This program uses the Pillow library (PIL) to open images, convert them into
PDF-compatible RGB format, and merge them into a single PDF. The user can choose
any number of images and arrange them in the order they should appear in the final PDF.
Requirements
-
pip install pillow
Installs the Pillow library (PIL), which is required for handling images.
- Python version 3 or higher.
- Supported image formats: JPG, PNG, JPEG, BMP, TIFF, WEBP.
- User must provide valid paths for images.
- The output is saved as a single merged PDF file.
Code Explanation
Imports the Image class from the Pillow library to open and process images.
Prints the title of the program for better clarity.
Asks the user how many images should be included in the PDF.
for i in range(count):
path = input(f"Enter image {i+1} path: ").strip()
image_files.append(path)
Collects all image paths from the user into a list.
Gets the final output PDF name. Uses a default name if not provided.
Opens each image and converts it into RGB mode to ensure PDF compatibility.
rest_images = images[1:]
The first image becomes the base of the PDF while the rest are appended behind it.
Saves all images into a single PDF file.
Prints a success message once the PDF is created.
Key Points
- Merges multiple images into a single PDF file.
- Keeps image order exactly as entered by the user.
- Uses Pillow (PIL), a powerful image-processing library.
- All images are converted to RGB to avoid PDF compatibility issues.
- Works with most common image formats.
Full Python Program
from PIL import Image
print("=== Multi Image to Single PDF Converter ===")
count = int(input("How many images to merge into PDF? ").strip())
image_files = []
for i in range(count):
path = input(f"Enter image {i+1} path: ").strip()
image_files.append(path)
output_pdf = input("Enter output PDF name: ").strip() or "images.pdf"
images = [Image.open(img).convert("RGB") for img in image_files]
first_image = images[0]
rest_images = images[1:]
first_image.save(output_pdf, save_all=True, append_images=rest_images)
print(f"\nPDF created successfully: {output_pdf}")
Output :
> py imgToPdf.py === Multi Image to Single PDF Converter === How many images to merge into PDF? 3 Enter image 1 path: pic1.jpg Enter image 2 path: pic2.png Enter image 3 path: scan3.jpeg PDF created successfully: images.pdf
