How to Convert Images to PDF in Python?

Andrew Wilson
2 min readDec 7, 2023

--

One of the main reasons for converting images to PDF is to facilitate sharing and transfer. In addition, combining multiple images into one PDF file can also simplify file management. This article will share how to use a third-party library to convert jpg/png images to PDF file with Python.

To install the Python library (Spire.PDF for Python), run the following command:

pip install Spire.PDF

Convert Multiple Images to a PDF File in Python

The PDF Python library provides a way to convert images to PDF by drawing the image directly onto the pages of a PDF file. The images can be of any format such as jpg, jpeg or png. The mains steps are:

To get started, the following should be imported first.

from spire.pdf.common import *
from spire.pdf import *
import os

Then create a PDF file through the PdfDocument class and set the page margins.

 # Create a PdfDocument object
pdf = PdfDocument()
# Set the page margins to 0
pdf.PageSettings.SetMargins(0.0)

Next, specify the folders where images are stored. Iterate through the images and get their width and height. Then add new pages to the PDF with the same size as the images. Finally, draw the images onto the new pages.

# Get the folder where the images are stored
path = "Images\\"
files = os.listdir(path)

# Iterate through the files in the folder
for root, dirs, files in os.walk(path):
for file in files:

# Load a particular image
image = PdfImage.FromFile(os.path.join(root, file)) #FromFile(os.path.join(root, file))

# Get the image width and height
width = image.PhysicalDimension.Width
height = image.PhysicalDimension.Height

# Add a page that has the same size as the image
page = pdf.Pages.Add(SizeF(width, height))

# Draw image at (0, 0) of the page
page.Canvas.DrawImage(image, 0.0, 0.0, width, height)

The last step is to save the PDF file to a specified file path.

# Save to file
pdf.SaveToFile("ConvertImagesToPdf.pdf")
pdf.Dispose()

After executing the above code, you can convert multiple images to a single PDF file quickly. The resulting PDF file may look like this:

Other features of the Python library that may be of interest to you:

Convert PDF to Images (JPG, PNG, BMP) in Python

Convert PDF to SVG in Python

Convert PDF to Excel in Python

Extract Text and Images from PDF in Python

--

--

Andrew Wilson

Explore C#, Java and Python solutions for processing Word/Excel/PowerPoint/PDF files.