Resource Center

Python Image to PDF: Batch Conversion Made Easy

Images and PDFs are easily the two file types we touch most every day. At work there is always a pile of screenshots or scanned photos that needs bundling into one file before it can be archived, shared, or sent to a client — which is exactly when images-to-PDF earns its keep. Once those images become a PDF, storing, sending, and protecting the content all get easier. This article covers how to do it in Python, and why that beats most online converters by a wide margin.

1. Why Use Python for Image to PDF?

Python is a capable language with a deep third-party library ecosystem, and handling images or PDFs is well within its wheelhouse. Bringing Python to this job pays off in several ways.

Efficiency

Python is interpreted, so writing and debugging code is much lighter than with a compiled language — no build step to babysit. When several dozen or a few hundred images need converting, a short script outruns clicking through an online tool one upload at a time. No repeated button presses, no waiting on page loads.

Flexibility

The Python ecosystem covers essentially every format you will meet, including JPG and PNG. It also chains cleanly into other tools and scripts — read every image in a folder, sort automatically, and shape the pipeline around your own rules. Online services mostly lock you into their fixed workflow, which is far more limiting.

Extensibility

Adding features later is cheap. Need image compression, watermarking, or batch renaming down the road? You do not rewrite anything — pull in the matching library and adjust a few lines. For developers or ops folks converting images to PDF regularly, this is the real payoff.

Dodging the Online Tool Pitfalls

One caveat worth raising: a lot of online converter sites come with strings attached — file size caps, paywalls once you pass a quota, or quietly retaining your images. Never upload anything sensitive to one. With a local Python script, files stay on your own machine, so you get far more control and safety.

2. How to Convert Images to PDF With Python

There are several routes, but here is the most common setup, built on Pillow and PyPDF2 with a clean division of labor: Pillow reads, processes, and writes the PDF pages; PyPDF2 stitches multiple PDFs together. The learning curve is gentle.

Step 1: Install the Dependencies

Open a terminal and install with pip:

pip install Pillow PyPDF2

One note: PyPDF2 was officially renamed pypdf at version 3.0. The old PyPDF2 package still installs and works, but in current releases PdfMerger has been folded into PdfWriter. For new projects, run pip install pypdf and follow the code below.

Step 2: Read the Local Image

With that installed, start coding — import Pillow's Image class and open a local file. To load image.jpg from the same directory:

from PIL import Image

image = Image.open("image.jpg")

Before you use the image object, normalize it to RGB. A PNG carrying an alpha channel (RGBA) will raise an error if you write it straight to PDF:

image = Image.open("image.jpg").convert("RGB")

Step 3: Write the Image to PDF

A single image is the simplest case — Pillow saves straight to PDF, and resolution records the reference DPI for the page:

image.save("output.pdf", "PDF", resolution=100.0)

Batch Conversion: Many Images, One Pass

Batch is where this actually earns its keep. Read every image in a folder in order and merge them into a multi-page PDF with save_all — a few dozen images take only a handful of lines:

from PIL import Image
from pathlib import Path

files = sorted(Path("./images").glob("*.jpg"))
pages = [Image.open(f).convert("RGB") for f in files]

pages[0].save(
    "output.pdf", "PDF",
    save_all=True,
    append_images=pages[1:],
    resolution=100.0,
)

Two things to watch: sorted() decides your page order, so use consistently zero-padded names (01.jpg, 02.jpg). Do not lean on the default directory traversal order — different operating systems return it differently.

Merging Multiple PDFs With PyPDF2 / pypdf

When you already have several PDFs and need to script them into one, this is PyPDF2's home turf. Current pypdf standardizes on PdfWriter (older versions used PdfMerger):

# pypdf 3.0+ / current PyPDF2 syntax
from pypdf import PdfWriter

writer = PdfWriter()
for item in ["part1.pdf", "part2.pdf", "part3.pdf"]:
    writer.append(item)

with open("merged.pdf", "wb") as f:
    writer.write(f)
writer.close()

# Older PyPDF2 syntax
# from PyPDF2 import PdfMerger
# merger = PdfMerger()
# for item in ["part1.pdf", "part2.pdf"]:
#     merger.append(item)
# merger.write("merged.pdf")
# merger.close()

Common Errors and Pitfalls

Beginners usually get stuck on one of these five:

  • Wrong path: with a relative path, "current directory" means where you launched the script, not where the script file lives. If the path contains spaces or non-ASCII characters, stick with pathlib.
  • Wrong image mode: RGBA or CMYK will throw when written to PDF. Always .convert("RGB") before saving.
  • Library version mismatch: older releases lack certain methods. Upgrade the library before you start doubting your own code — plenty of people lose an hour right here.
  • File size explosion: dropping a huge image straight into a PDF multiples the final size several times over. Downscale it with Pillow first, or apply one lossy compression pass before converting.
  • Repeated compression: when the source is already JPEG, saving it back and forth accumulates quality loss. Start from the original whenever you can get it.

3. Script or Online Tool: How to Choose

On the whole, a Python script suits batch jobs, privacy requirements, or anything that needs to be embedded in a project pipeline. A handful of lines gets you running, and you can extend it freely later. Compared with a web tool it asks for a little code knowledge, but it wins on control and security — and for frequent, long-term use it saves a great deal of repetitive clicking.

If this is a one-off and you would rather not set up an environment, an online tool is the better deal. Either way, these will finish the job:

  • Images to PDF: multi-select drag and drop, reorder pages whenever you like, pick an A4 layout with margins, and merge.
  • Image Compressor: shrink the sources before converting so the final PDF stays a manageable size.
  • PDF Compressor: compress the already-merged PDF once more so email attachment limits stop being a problem.
  • Merge & Split PDF: combine several PDFs into one without writing a single line of PyPDF2.

4. Frequently Asked Questions

Why is the PDF my Python script produced so large?

Fix it at the source first: resize images to a sensible pixel size with Pillow, convert them to RGB, and lower the JPEG quality if needed. If the PDF already exists, run it through a PDF compression pass, which does far more than repeatedly tweaking export settings.

Do I need PyPDF2 to turn images into PDF?

Not for the conversion itself. For a single image or a batch of images, Pillow's save(save_all=True, append_images=...) is enough. Reach for PyPDF2, officially renamed pypdf since version 3.0, only when you need to concatenate existing PDFs or split and rotate pages; its PdfMerger has been folded into PdfWriter.append().

How do I control the page order in a batch conversion?

Never rely on the default directory listing order. Name your files on a consistent rule such as a date or a zero-padded index, then read them with sorted(). When the order is strict, keep an explicit text list of filenames and have the script read that file line by line.

Is there an easier way to convert images to PDF without writing code?

Yes. An online Images to PDF tool takes your files by drag and drop, lets you reorder pages, and exports immediately with nothing to install. For sensitive documents, check whether files are uploaded to someone else's server and prefer a tool that states clearly it keeps nothing.

5. Wrap Up

The rule of thumb for images to PDF: online tools win for two files; a Python script wins for dozens or hundreds, especially with privacy in play. Once you have the combination down — Pillow writing pages, PyPDF2 or pypdf handling merges — batch processing, auto-sorting, watermarking, and encryption all extend naturally, and there is no going back to clicking buttons one at a time.

Not writing code is fine too. FreeConvertBox's Images to PDF turns a pile of images into one PDF in a few steps. No uploads, no retention. Your privacy is fully protected. The site also carries a dozen more free tools including an Image Format Converter, image compressor, PDF merge and split, ID photo maker, and QR code generator — no need to install a separate app for every format.

Note: Some source material was AI-assisted.


Free Converter Toolbox   Images to PDF, Image Format Converter