Search code examples
pythonloopspdfpdf-generationfpdf

How to run python on multiple folder to create pdf?


The following code is to combine multiple images into one pdf. I am trying to run this code on multiple folder where each folder has several images as result, each folder will has one pdf.

import os
from PIL import Image
from fpdf import FPDF


pdf = FPDF()
sdir = "imageFolder/"
w,h = 0,0

for i in range(1, 100):
    fname = sdir + "IMG%.3d.png" % i
    if os.path.exists(fname):
        if i == 1:
            cover = Image.open(fname)
            w,h = cover.size
            pdf = FPDF(unit = "pt", format = [w,h])
        image = fname
        pdf.add_page()
        pdf.image(image,0,0,w,h)
    else:
        print("File not found:", fname)
    print("processed %d" % i)
pdf.output("output.pdf", "F")
print("done")

I was thinking to create another loop to bring the folder path which will come before the first loop:

   For j in range(1 to 70):
folderP=sdir+folder%1

And loop in each folder

Sorry I am still learning python. Any suggestion would be great!


Solution

  • You can use glob to get the paths of all pdfs and add them to a list, then you just iterate through the list and you wouldn't even need to check if they exist:

    from glob import glob
    
    sDir = 'imageFolder/'
    pdfPaths = []
    
    pdfPaths.extend(glob(f'{sDir}**/*.pdf', recursive=True))
    
    for pdf in pdfPaths:
        # do stuff