How to Convert Images to PDF using Python
In this tutorial, you will learn how to convert an image file to a pdf file using Python.
TLDR solution
img2pdf.py
import img2pdf
with open('/target-path/file_name.pdf', 'wb') as f:
f.write(img2pdf.convert('/path-to-image/img.png'))
Required: Install the img2pdf Package
If you don't have img2pdf already installed, execute the following command in your terminal:
pip install img2pdf
Example 1: Convert an Image
Let's say, you have test.jpg on your desktop.
You can then convert it to pdf like this:
img2pdf.py
import os
import img2pdf
desktop_path = os.path.expanduser("~/Desktop")
# supports jpg, png, png, tiff
with open(desktop_path + 'test.pdf', 'wb') as f:
f.write(img2pdf.convert(desktop_path + '/test.jpg'))
After you run this, you should find a test.pdf on your desktop.
Example 2: Convert Multiple Images to a Single PDF
To convert more than one image to a single pdf file, simply input a list of image files:
img2pdf.py
import os
import img2pdf
desktop_path = os.path.expanduser("~/Desktop")
with open(desktop_path + 'test.pdf', 'wb') as f:
f.write(img2pdf.convert([desktop_path + '/test1.jpg',
desktop_path + '/test2.jpg']))
Example 3: Convert Multiple Images to Multiple PDFs
If you want to create a pdf file per image, use a for loop:
img2pdf.py
import os
import img2pdf
desktop_path = os.path.expanduser("~/Desktop")
image_list = ['test1', 'test2']
for i in image_list:
with open(desktop_path + f'{i}.pdf', 'wb') as f:
f.write(img2pdf.convert(desktop_path + f'/{i}.jpg'))
That's it! You just learned how to convert images to pdf using Python.