#!/usr/bin/python import os,sys,re import traceback from optparse import OptionParser def main(): usage = """ usage: pdftopngs [options] pdfname Converts a PDF file to a series of PNG images, one per page in the PDF file. By default, the images are 512x512, which will probably be distorted from your PDF file, but is best suited for uploading as textures to Second Life. Prerequisites : you must have the ghostscript ("gs") and netpbm command-line utilities installed. """ parser = OptionParser(usage = usage) parser.add_option("-x","--x-size", action="store", type="int", dest="xsize", default=512, help="Width of the resultant images (def: 512)") parser.add_option("-y","--y-size", action="store", type="int", dest="ysize", default=512, help="Height of the resultant images (def: 512)") parser.add_option("-r","--resolution", action="store", type="int", dest="resolution", default=150, help="DPI in the initial PDF conversion (def: 150)") parser.add_option("-g","--gs-args", action="store", type="string", dest="gsargs", default=None, help="Additional arguments to pass to ghostscript") options,args = parser.parse_args() try: if len(args) < 1: print "Please specify the name of a pdf file to convert" sys.exit(20) pdfname = args[0] res = options.resolution xsize = options.xsize ysize = options.ysize gsargs = "" if options.gsargs is not None: gsargs = options.gsargs pdfre = re.compile("^(.*)\.pdf") pdfmatch = pdfre.search(pdfname) if (pdfmatch is None): print "Error parsing %s as the name of a PDF file" % pdfname sys.exit(20) fnamebase = pdfmatch.group(1) cmd = "gs -q -sDEVICE=ppmraw -dNOPAUSE -sOutputFile=%s_%%02d.ppm " \ "-r%s %s %s.pdf -c quit" % (fnamebase, res, gsargs, fnamebase) print cmd os.system(cmd) files = os.listdir(".") ppmre = re.compile("^%s_(\d+)\.ppm" % fnamebase) maxnum = 0 for file in files: ppmmatch = ppmre.search(file) if (ppmmatch is not None): num = int(ppmmatch.group(1)) if num > maxnum: maxnum = num if maxnum == 0: print "ERROR : no output from gs!" sys.exit(20) for i in range(1, maxnum+1): thisnamebase = "%s_%02d" % (fnamebase, i) cmd = "pnmscale -width %s -height %s %s.ppm | pnmtopng > %s.png" \ % (xsize, ysize, thisnamebase, thisnamebase) print cmd os.system(cmd) try: os.unlink("%s.ppm" % thisnamebase) except OSError: pass except Exception: print "FAIL" traceback.print_exc() sys.exit(20) # ********************************************************************** if __name__ == "__main__": sys.exit(main())