Python to Convert an Image to PDF with Source Code

The Python script enables the user to convert images into PDF files. However, you must note that the script can only work well for JPG file formats. You can use the converter for revamping JPG images into PDF format.

Requirements

img2pdf module

The img2pdf is an external Python module that enables you to convert a JPG image into a PDF.

pip install img2pdf

How to run the script

Using Terminal

  • Add the image in the JPG format with name as ‘input’ in this folder.
  • Run converter_terminal.py script
  • Output PDF file will be generated in this folder

Requirements:

  • img2pdf==0.4.0

Source Code:

import sys
import img2pdf
import os

filepath = sys.argv[1]
if os.path.isdir(filepath):
    with open("output.pdf", "wb") as f:
        imgs = []
        for fname in os.listdir(filepath):
            if not fname.endswith(".jpg"):
                continue
            path = os.path.join(filepath, fname)
            if os.path.isdir(path):
                continue
            imgs.append(path)
        f.write(img2pdf.convert(imgs))
elif os.path.isfile(filepath):
    if filepath.endswith(".jpg"):
        with open("output.pdf", "wb") as f:
            f.write(img2pdf.convert(filepath))
else:
    print("please input file or dir")

Output:

Leave a Comment