How to convert image into pdf in Python

In this tutorial, we will learn how to convert image to pdf file in Python using img2pdf.

An image can be of any format with extensions like jpg or png.

pdf is an electronic image of elements.

Importing modules to convert image into pdf :

An img2pdf module is available in the Python library.

But in the user’s system, it may or may not be installed.

The following are the steps involved in installing the img2pdf module.

  1. Open the command prompt in windows or the terminal for Linux and ubuntu-users.
  2.  Type “ pip install img2pdf 
  3. The following packages will be installed and that’s it, we are ready to proceed.
  4. If the following doesn’t work try with “ sudo apt-get install img2pdf

PIL library gives the image more quality.

Converting image into PDF in Python

Certainly, this is the one which will be imported first.

import img2pdf                    
import os
from PIL import Image          # Image function is used to open an image based on location

Now, it’s time to provide the image path and pdf path

  • The image path defines the location of the image in your harddisk.
  • The pdf path defines the location of the resulting output pdf.
import img2pdf
import os
from PIL import Image

image_location = "/home/gvj861/Downloads/j.jpg"           # present image location 

pdfstore_location = "/home/gvj861/Desktop/ss.pdf" 	 	   #  where to store the resulting pdf file

The next step is to open the following image file and use the img2pdf converter function.

import img2pdf
import os
from PIL import Image

image_location = "/home/gvj861/Downloads/j.jpg"           # present image location 

pdfstore_location = "/home/gvj861/Desktop/ss.pdf" 	 	   #  where to store the resulting pdf file

myimage = Image.open(image_location)                          # opening the image

pdf_data = img2pdf.convert(myimage.filename)              # converting image to pdf using module 

It seems everything is ready, therefore quickly jumping to open a new file and write to file with the pdf_data.

.write( ) method is used to write into a file.

import img2pdf
import os
from PIL import Image

image_location = "/home/gvj861/Downloads/j.jpg"           # present image location 

pdfstore_location = "/home/gvj861/Desktop/ss.pdf" 	 	   #  where to store the resulting pdf file

myimage = Image.open(image_location)

pdf_data = img2pdf.convert(myimage.filename)

converted_file = open(pdfstore_location,"w+")

converted_file.write(pdf_data)

image.close()                                              # closing the previously opened file

The moment this code is executed, the following image is converted to pdf and can be seen in the destination location.

Also learn:

Leave a Reply

Your email address will not be published. Required fields are marked *