Image to PDF converter in Python
About the project: This is a single-file Python script that converts one or more images into a single PDF document.
This project uses the Pillow library, which is a powerful tool for image processing in Python.
Prerequisites
Before you run the code, you'll need to install the Pillow library. You can do this easily using pip from your terminal or command prompt:
pip install Pillow
This script is simple to use. Just save it, make sure your images (JPEG, PNG, etc.) are in the same folder as the script, and run it from your terminal.
Project Level: Intermediate
You can directly copy the below snippet code with the help of green copy button, paste it and run it in any Python editor you have.
Steps: Follow these stepsStep 1: Copy below code using green 'copy' button.
Step 2: Paste the code on your chosen editor.
Step 3: Save the code with filename and .py extention.
Step 4: Run (Press F5 if using python IDLE).
# image_to_pdf.py
import os
from PIL import Image
def convert_images_to_pdf():
"""
Converts multiple image files into a single PDF document.
It prompts the user for the list of image files and the output filename.
"""
print("Image to PDF Converter")
print("----------------------")
# Get the list of image files from the user.
# The files should be in the same directory as this script.
input_files_str = input("Enter the names of the image files to convert (e.g., image1.jpg image2.png): ")
input_files = input_files_str.split()
# Get the desired name for the output PDF file.
output_filename = input("Enter the name for the output PDF file (e.g., output.pdf): ")
if not output_filename.lower().endswith(".pdf"):
output_filename += ".pdf"
if not input_files:
print("Error: No image files specified. Exiting.")
return
# A list to store the valid image objects.
images_to_save = []
# Process the first image to use as the base for the PDF.
first_image_path = input_files[0]
if os.path.exists(first_image_path):
try:
# Open the first image.
first_image = Image.open(first_image_path)
# Convert to RGB mode if it's not already (necessary for some image types to save correctly as PDF).
if first_image.mode != 'RGB':
first_image = first_image.convert('RGB')
print(f"Successfully added '{first_image_path}'.")
except Exception as e:
print(f"Error opening '{first_image_path}': {e}. Please ensure it's a valid image file.")
return
else:
print(f"Error: '{first_image_path}' not found. Exiting.")
return
# Process the remaining images.
for filename in input_files[1:]:
if os.path.exists(filename):
try:
img = Image.open(filename)
# Convert to RGB mode for consistency.
if img.mode != 'RGB':
img = img.convert('RGB')
images_to_save.append(img)
print(f"Successfully added '{filename}'.")
except Exception as e:
print(f"Error opening '{filename}': {e}. Skipping this file.")
else:
print(f"Error: '{filename}' not found. Skipping.")
try:
# Save all images into a single PDF file.
# The 'save_all=True' argument tells Pillow to save all the frames.
# The 'append_images' argument provides the list of additional images.
first_image.save(output_filename, save_all=True, append_images=images_to_save)
print("\n----------------")
print(f"Success! All images have been converted into '{output_filename}'.")
print("----------------")
except Exception as e:
print(f"An error occurred while writing the output file: {e}")
finally:
# Close all opened images to free up resources.
first_image.close()
for img in images_to_save:
img.close()
if __name__ == "__main__":
convert_images_to_pdf()
← Back to Projects