Convert your image to PDF using just 4 lines of code.

Vineet Joshi
2 min readJan 14, 2019

--

Image source: Unsplash.com

Today, Camscanner is one of the most well known and widely used applications for scanning and sharing of documents. It allows the user to scan via there mobile, apply image straightening and share multiple documents simultaneously as a PDF.

Often times, we face a similar situation in our system where we need to convert a pile of Images into a PDF, for ease of sharing and compaction. This tutorial will give you a basic 4 line python code to replicate this specific functioning of Camscanner and achieve the task.

Let’s start

Although a number of libraries are available on the internet which can be used to convert images into pdf but for this tutorial, we will use img2pdf.

So before we understand how to use img2pdf, let's install it.

Open the command prompt on your system and run the following script.

pip install img2pdf

As explained in the original documentation, img2pdf allows us to perform a lossless conversion of images into PDF. A lossless conversion will always have the exact same color information for every pixel as the input, which is often the desired property. img2pdf gives a very basic function img2pdf.convert, to perform this task.

Now that our required library is installed, let's move ahead.

Create a file chat.py and import os and img2pdf libraries.

import os
import img2pdf

The OS module in Python provides a way of using operating system dependent functionality. We will be using it for accessing the images name in the CWD (Current Working Directory).

Open the Output.pdf file in “wb” mode

with open("output.pdf", "wb") as f:

The “wb” indicates that we are writing in our output.pdf in binary mode.

Run a loop inside the write method which pics up a “.jpeg” image,converts it and writes it to the pdf file.

with open("output.pdf", "wb") as f:
f.write(img2pdf.convert([i for i in os.listdir('.') if i.endswith(".jpg")]))

The above code can be broken down for a better understanding. The os.listdir() method returns a list of all the files in the current directory, iterator ‘i’, traverses through the list and pics up jpeg images one by one, converts them and then write them to the output.pdf we opened earlier.

To run the converter, just go to the command prompt and type

python Converter.py

Source Code:

import os
import img2pdf
with open("output.pdf", "wb") as f:
f.write(img2pdf.convert([i for i in os.listdir('.') if i.endswith(".jpg")]))

Note: If you are straightaway copying the code for use, please make sure that all your images are in your CWD (Current Working Directory).

--

--