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:
    images.extend(glob.glob(extension))

# Create instance of FPDF class
pdf=FPDF('P','in','letter')
# Add new page. Without this you cannot create the document.
pdf.add_page()
# Set font to Arial, 'B'old, 16 pts
pdf.set_font('Arial','B',16.0)

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

# Smaller font for image captions
pdf.set_font('Arial','',10.0)

# 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)
    pdf.ln(0.15)

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

# output content into a file ('F')
pdf.output('images-in-folder.pdf','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:
Selection_563

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s