Hunter Zolomon
Hunter Zolomon

Reputation: 87

Python Convert all JPGS in a folder to PDF

I have code that converts all .jpgs in a folder to one PDF, but it is not working. I believe it to be because of something with my directory being passed. The below is the code and my output. Now it states that my PDF was written, but it doesn't display the directory.

root = "C:\\Users\\Matthew\\Desktop\\Comics\\" 

try:
   n = 0
   for dirpath, dirnames, filenames in os.walk(root):
    PdfOutputFileName = os.path.basename(dirpath) + ".pdf" 
    c = canvas.Canvas(PdfOutputFileName)
    if n > 0 :
        for filename in filenames:
            LowerCaseFileName = filename.lower()
            if LowerCaseFileName.endswith(".jpg"):
                    print(filename)
                    filepath    = os.path.join(dirpath, filename)
                    print(filepath)
                    im          = ImageReader(filepath)
                    imagesize   = im.getSize()
                    c.setPageSize(imagesize)
                    c.drawImage(filepath,0,0)
                    c.showPage()
                    c.save()
    n = n + 1
    print "PDF of Image directory created" + PdfOutputFileName

except:
     print "Failed creating PDF"

The below is my output:

PDF of Image directory created.pdf

Upvotes: 3

Views: 4536

Answers (2)

Adam Erickson
Adam Erickson

Reputation: 6363

Have a look at img2pdf for lossless conversion in Python:

https://gitlab.mister-muffin.de/josch/img2pdf

Example CLI usage:

img2pdf img1.png img2.jpg -o out.pdf

Upvotes: 2

Jean-François Fabre
Jean-François Fabre

Reputation: 140148

At start n is 0.

The os.walk loop only runs once in this case (since there's probably only one directory to scan, and you get only one print statement so that's the proof), providing filenames and dirnames as iterables, but you skip the iteration by testing n > 0, so it does nothing.

   for dirpath, dirnames, filenames in os.walk(root):
    PdfOutputFileName = os.path.basename(dirpath) + ".pdf" 
    c = canvas.Canvas(PdfOutputFileName)
    if n > 0 :

My advice: get rid of the if n > 0 test.

Upvotes: 3

Related Questions