Skip to content

Python Automation to Convert Images to PDF

Python has several libraries for turning images into PDFs. Learn two quick automation methods you can copy into your own scripts.

2 min read
Photo cards flowing into a PDF document icon
On this page2 sections

Python has a lot of libraries for creating PDF files from images. Here are some of the most popular:

  1. img2pdf

  2. Python Imaging Library (PIL)

  3. pyPdf

  4. ReportLab

  5. xhtml2pdf

Each of these libraries has its own strengths and weaknesses, so you’ll need to decide which one is right for your needs.

img2pdf is probably the simplest library to use, and it produces good results. PIL is a popular general-purpose imaging library that also happens to have good PDF-creation capabilities. pyPdf is a pure-Python library that can be used to create PDF files from scratch or to manipulate existing PDFs. ReportLab is a commercial library that is not free for use, but it is very powerful and includes a lot of features. xhtml2pdf is a library that can be used to convert HTML files into PDFs.

Once you’ve decided on a library, you can follow the instructions for using it to convert your images into PDFs.

In case you have a lot of images and would like to convert them into a single PDF file, this script will be useful for you.

Method 1 to Convert Images to PDF in Python

Method 1 · convert-images-to-pdf.py
import os
import img2pdf
with open("output.pdf", "wb") as file:
file.write(img2pdf.convert([i for i in os.listdir(
'Path of image_Directory') if i.endswith(".jpg")]))

Method 2 to Convert Images to PDF in Python

Method 2 · convert-images-to-pdf.py
from fpdf import FPDF
Pdf = FPDF()
list_of_images = ["one.jpg", "second.jpg","third.jpg"]
for i in list_of_images:
Pdf.add_page()
Pdf.image(i,x,y,w,h)
Pdf.output("out.pdf", "F")
Filed underWeb DevelopmentPythonFPDFimg2pdf
Share

Rajan Dangi

Senior Web Developer

Senior web developer at SathiSoft. I write about PHP, Python, Linux and the practical details of building for the web.