SCRIPTS

Python Code to Convert a list of Images to PDF

In this post a python code is presented to get a list of images from a directory and convert them to a PDF.

The code utilizes the os and the fpdf library. PyFPDF is a library for PDF document generation under Python, ported from PHP.

The code gets the file names of images in the current directory and then creates a PDF of constant width.

import os
from fpdf import FPDF


pdf = FPDF()
pdf.set_auto_page_break(0)

files = os.listdir()

for file in files:
    if file.endswith(('.jpg', '.png', 'jpeg')):
        pdf.add_page()
        pdf.image(file, x = None, y = None, w = 180, h = 0, type = '', link = '')

pdf.output('image2pdf.pdf', 'F')