Combine JPG Images into a PDF with Python

If you’ve ever needed to merge multiple JPG images into a single PDF (for scans, documents, or notes), you can do it easily with Python using the Pillow library.

This guide walks you through a simple script that does exactly that.

Prerequisites

Make sure you have Python installed. Then install Pillow:

pip install pillow

The Script

Here’s a minimal working script where you define the images and output file directly:

from PIL import Image
import os

# === CONFIG ===
output_pdf = "output.pdf"

image_files = [
    "img1.jpg",
    "img2.jpg",
    "img3.jpg",
]
# ==============


def jpgs_to_pdf(image_files, output_pdf):
    images = []

    for file in image_files:
        if not os.path.exists(file):
            print(f"File not found: {file}")
            continue

        try:
            img = Image.open(file)

            # Convert to RGB (required for PDF)
            if img.mode != 'RGB':
                img = img.convert('RGB')

            images.append(img)

        except Exception as e:
            print(f"Error processing {file}: {e}")

    if not images:
        print("No valid images to process.")
        return

    first_image = images[0]
    rest_images = images[1:]

    first_image.save(
        output_pdf,
        save_all=True,
        append_images=rest_images
    )

    print(f"PDF created successfully: {output_pdf}")


if __name__ == "__main__":
    jpgs_to_pdf(image_files, output_pdf)

How It Works

  • You define:
  • image_files: a list of JPG files in the order you want them in the PDF
  • output_pdf: the name of the resulting file
  • Each image is:
  • Opened using Pillow
  • Converted to RGB (required for PDF compatibility)
  • The first image becomes the base, and the rest are appended

Running the Script

Just run:

python script.py

Common Pitfalls

  • Missing files: The script skips files that don’t exist
  • Wrong formats: Non-JPG files may fail unless supported by Pillow
  • Large images: High-resolution images can produce very large PDFs