#!/usr/bin/python # author: Ney Estrabelli # site : www.neyestrabelli.com # created: 24.11.2010 # Thanks to Dinu C. Gherman for providing the # code example on http://python.net/~gherman/pdf2tiff.html # Thanks to Martin Michel martin.michel@macscripter.net # for the pdf2jpg import sys import os import zipfile import re import shutil from os.path import splitext from objc import YES, NO from Foundation import NSData from AppKit import * NSApp = NSApplication.sharedApplication() def main(): pdfpath = sys.argv[1].decode('utf-8') zipname = pdfpath[0:-4] os.mkdir(zipname) if len(sys.argv) <= 2 : resolution = 100 else: resolution = int(sys.argv[2].decode('utf-8')) print 'iniciando conversao...' pdf2jpg(pdfpath,zipname, resolution) print 'comprimindo diretorio..' zip_dir(zipname, zipname+".cbz") shutil.rmtree(zipname) def pdf2jpg(pdfpath,zipn, resolution=72): """I am converting all pages of a PDF file to JPG images.""" pdfdata = NSData.dataWithContentsOfFile_(pdfpath) pdfrep = NSPDFImageRep.imageRepWithData_(pdfdata) pagecount = pdfrep.pageCount() for i in range(0, pagecount): pdfrep.setCurrentPage_(i) pdfimage = NSImage.alloc().init() pdfimage.addRepresentation_(pdfrep) origsize = pdfimage.size() width, height = origsize pdfimage.setScalesWhenResized_(YES) rf = resolution / 72.0 pdfimage.setSize_((width*rf, height*rf)) tiffimg = pdfimage.TIFFRepresentation() bmpimg = NSBitmapImageRep.imageRepWithData_(tiffimg) data = bmpimg.representationUsingType_properties_(NSJPEGFileType, {NSImageCompressionFactor: 1.0}) jpgpath = "%s-%d.jpg" % (splitext(pdfpath)[0], i) if not os.path.exists(zipn+'/'+jpgpath): data.writeToFile_atomically_(zipn+'/'+jpgpath, False) def zip_dir(dirpath, zippath): fzip = zipfile.ZipFile(zippath, 'w', zipfile.ZIP_DEFLATED) basedir = os.path.dirname(dirpath) + '/' for root, dirs, files in os.walk(dirpath): if os.path.basename(root)[0] == '.': continue #skip hidden directories dirname = root.replace(basedir, '') for f in files: if f[-1] == '~' or (f[0] == '.' and f != '.htaccess'): #skip backup files and all hidden files except .htaccess continue fzip.write(root + '/' + f, dirname + '/' + f) fzip.close() if __name__ == '__main__': main()