A PDF with images in a folder

Using `pyFPDF`, this is one way of building a PDF with all images in a folder:

# Import FPDF class
from fpdf import FPDF

# Import glob module to find all the files matching a pattern
import glob

# Image extensions
image_extensions = ("*.png", "*.jpg", "*.gif")

# This list will hold the images file names
images = []

# Build the image list by merging the glob results (a list of files)
# for each extension. We are taking images from current folder.
for extension in image_extensions:

# Create instance of FPDF class
# Add new page. Without this you cannot create the document.
# Set font to Arial, 'B'old, 16 pts

# Page header
pdf.cell(4.0,1.0,'Images in this folder')

# Smaller font for image captions

# Loop through the image list and position
# them with their caption one below the other
for image in images:

    # Setting image width to half the page and
    # height to 1/4th of the page
    pdf.image(image, w=pdf.w/2.0, h=pdf.h/4.0)

    # Image caption
    pdf.cell(3.0, 0.0, image)

# output content into a file ('F')

The code assumes we are getting the images from the same folder the script is running. Change the extension list like this to specify a particular folder:

image_extensions = ("path/to/folder/*.png", "path/to/folder/*.jpg", "path/to/folder/*.gif")

Something like this will be the output:


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s