Python Automation to Convert Images to PDF

Python Automation to Convert Images to PDF


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

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

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")

Add a Comment

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