Converting folders of jpegs to single pdf per folder

vasishtha.spier at gmail.com vasishtha.spier at gmail.com
Fri Jan 17 00:42:17 EST 2014


On Thursday, January 16, 2014 12:07:59 PM UTC-8, Tim Golden wrote:
>
> Here's a quick example. 
> This should walk down the Python directory, creating a text file for 
> each directory. The textfile will contain the names of all the files in 
>  the directory. (NB this might create a lot of text files so run it 
>  inside some temp directory).

> <code>
> import os
> root = "c:/temp"
> for dirpath, dirnames, filenames in os.walk(root):
>      print("Looking at", dirpath)
>      txt_filename = os.path.basename(dirpath) + ".txt"
>      with open(txt_filename, "w") as f:
>        f.write("\n".join(filenames)
> </code>
> TJG

Thanks Tim.  It worked like a charm and saved me weeks of work using a drag and drop utility. About 250 pdf files created of 50 to 100 pages each.  Heres the code in case any one else can use it.  
----------------
import os
from reportlab.pdfgen import canvas
from reportlab.lib.utils import ImageReader

root = "C:\\Users\\Harry\\" 

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"
-------------------------



More information about the Python-list mailing list