I will walk you through a practical project where we will convert multiple images into a single PDF file using Python. If you have ever needed to compile images into a PDF for documentation, sharing, or storage, this guide will provide you with an efficient and enhanced solution.
Project Overview
This project allows us to take multiple image files and convert them into a single PDF file. We will also ensure that images are dynamically resized while maintaining their aspect ratio. Additionally, the script will handle errors such as missing files and allow users to specify a custom output filename.
Enhancements in This Project
Here are some key enhancements that make this script more practical and robust:
Handles multiple images: Convert multiple images into a single PDF effortlessly. Dynamic image placement: Automatically resizes images while maintaining aspect ratio. Custom output filename: Users can define the output filename for better flexibility. Automatic page addition: Each image gets its own page in the PDF. Error handling: Prevents crashes by handling missing or invalid image files.
Requirements
Before we dive into coding, ensure you have the required Python libraries installed:
pip install fpdf pillow
- fpdf: A lightweight library to generate PDFs.
- pillow (PIL): A powerful library for image processing in Python.
Python Script to Convert Images to PDF
Here is the complete Python script that performs the conversion:
from fpdf import FPDF
import os
from PIL import Image
def add_image_to_pdf(pdf, image_path, max_width=180, max_height=250):
""" Adds an image to the PDF while maintaining aspect ratio """
if not os.path.exists(image_path):
print(f"Error: File {image_path} not found!")
return
# Open image to get dimensions
with Image.open(image_path) as img:
img_width, img_height = img.size
# Calculate new dimensions while maintaining aspect ratio
aspect_ratio = img_width / img_height
if img_width > img_height:
width = min(max_width, img_width)
height = width / aspect_ratio
else:
height = min(max_height, img_height)
width = height * aspect_ratio
# Add image to the PDF
pdf.add_page()
pdf.image(image_path, x=10, y=10, w=width, h=height)
# Add text below the image
pdf.set_font("Arial", size=12)
pdf.ln(height + 10) # Move cursor below image
pdf.cell(200, 10, txt=f"Image: {os.path.basename(image_path)}", ln=True)
def images_to_pdf(image_list, output_filename="output.pdf"):
""" Converts multiple images to a PDF """
if not image_list:
print("Error: No images provided!")
return
pdf = FPDF()
for image in image_list:
add_image_to_pdf(pdf, image)
# Save PDF
pdf.output(output_filename)
print(f"PDF created successfully: {output_filename}")
# Example usage: Convert multiple images to a PDF
image_files = ["image1.png", "image2.jpg", "image3.jpeg"] # Replace with actual image paths
images_to_pdf(image_files, "final_document.pdf")
How This Improved Version Works
- The script takes multiple image files and adds them to a PDF.
- It automatically resizes images to fit the PDF while preserving their aspect ratio.
- The script handles missing files gracefully without crashing.
- Users can specify a custom filename for the generated PDF.
- Each image gets its own separate page in the PDF.
How to Use This Script
- Save the script in a Python file, e.g.,
convert_images_to_pdf.py
. - Replace
image1.png
,image2.jpg
, etc., with your actual image file paths. - Run the script:
python convert_images_to_pdf.py
- A new PDF file (
final_document.pdf
) will be generated containing all images.
Final Thoughts
This project provides a practical solution for converting multiple images into a well-structured PDF document. Whether you need it for documentation, presentations, or personal organization, this script offers flexibility and automation.