Welcome, guest | Sign In | My Account | Store | Cart

Walk through a directory PDFing Images

Python, 23 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import os
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
from reportlab.lib.units import cm, mm, inch, pica

def pdfDirectory(imageDirectory, outputPDFName):
    dirim = str(imageDirectory)
    output = str(outputPDFName)
    width, height = letter
    height, width = letter
    c = canvas.Canvas(output, pagesize=letter)
    try:
        for root, dirs, files in os.walk(dirim):
            for name in files:
                lname = name.lower()
                if lname.endswith(".jpg") or lname.endswith(".gif") or lname.endswith(".png"):
                    filepath = os.path.join(root, name)
                    c.drawImage(filepath, inch, inch * 1)
                    c.showPage()
                    c.save()
        print "PDF of Image directory created"
    except:
        print "Failed creating PDF"

2 comments

jonvidh 15 years ago  # | flag

This looks good, but could the images be scaled to fit the pdf-pages? Now the images get cropped.

Arnau Sanchez 14 years, 1 month ago  # | flag

Indiscriminate "try/except"s are usually a bad idea. Let the caller deal with exceptions raised in the function.