RSS category feeds

RSS site feeds

More

Adobe Acrobat and Acrobat 3D Batch extension PDF Print E-mail

This is a PDF Batch Converter extension for Adobe Acrobat and Acrobat 3D. This tool converts 3D CAD models to 3D-PDF as well as Office documents to PDF and works in following modes:

  • Convert single files
  • Convert files in a directory in batch
  • Converts a type of files with wildcards like *.CATPart, *.prt, *.model, ...
  • Works as a deamon which watches into a directory (directory watcher)
If you want to download a compiled version: http://www.goermezer.de/dmdocuments/Acrobat2PDF.zip

If you want to use the source with a Python interpreter, it needs a config.ini with this content:

 
# Configuration of Acrobat2PDF:
[configsection]
 
# Only for usage as a server/deamon process
# Poll time is the time in seconds for each loop of conversion
 
polltime = 10

And here comes the Python source code. Pywin32 needed.

 
from __future__ import with_statement
"""
 Adobe Acrobat2PDF Batch Converter
 This tool converts all Office Documents to PDF and a lot of 3D CAD models
 to 3D-PDF
 Copyright Mustafa Goermezer
 http://www.goermezer.de
"""
import getopt
import os
from win32com.client.dynamic import Dispatch
import pythoncom
import win32gui
import time
import sys
import glob
import string
import ConfigParser
import datetime
 
 
def LoadConfig(file, config={}):
    """
    returns a dictionary with key's of the form
    <section>.<option> and the values
    """
    config = config.copy()
    cp = ConfigParser.ConfigParser()
    cp.read(file)
    for sec in cp.sections():
        name = string.lower(sec)
        for opt in cp.options(sec):
            config[name + "." + string.lower(opt)] = string.strip(cp.get(sec, opt))
    return config
def usage():
    print '''
    usage: acrobat2pdf.exe -i <input file/dir> -o <outputdir> [more options]\n
    Options:
    -i or --input\t\tInput directory or file (mandatory)
    -o or --output\t\tOutput directory (mandatory)
    -m or --movesource\t\tDirectory for converted source files
    -d or --deamon\t\tRun as deamon
    -h or --help\t\tThis help (usage)
    -n or --notoverwrite\tDoesn`t overwrite existing PDF files
    -l or --logfile <file>\tFilename of logfile to write
 
    Important: At minimum you have to select -i and -o for conversion !
    '''
    sys.exit(99)
 
def stdout(msg):
    print msg
    if logfile:
        with open(logfile, 'a') as log:
            log.write(msg+'\n')
 
def converter():
 
    starttime=datetime.datetime.now()
    conv_count = 0
    target = ".pdf"
    NOSAVE = -1
    PDSAVEFULL = 1
 
    # If running on one file
    if os.path.isfile(input):
        (inputdir, filename) = os.path.split(input)
        input_iter=[filename]
        wildcard = False
    # if running on directory
    elif os.path.isdir(input):
        input_iter = os.listdir(input)
        inputdir=input
        wildcard = False
    elif input.find('*') != -1:
        input_iter = glob.glob(input)
        wildcard = True
        #print input_iter
        #sys.exit()
    else:
        print 'Please use a filename, a directory or wildcards to convert documents!'
        sys.exit(99)
 
    for files in input_iter:
 
        (shortname, extension) = os.path.splitext(files)
        if wildcard == True:
            src = files
        else:
            src = inputdir+os.sep+files
        dst = outputdir+os.sep+shortname+target
 
        stdout('Converting %s'%(files))
 
        if os.path.isdir(src) == True:
            stdout('%s is a directory. Skipping...\n'%files)
            continue
 
        if overwrite == False:
            if os.access(dst, os.F_OK) == True:
                stdout('  %s already exists. Taking next one...'%(shortname+target))
                continue
        else:
            if os.access(dst, os.F_OK) == True:
                stdout('  %s already exists. Overwriting...'%(shortname+target))
 
        # Beginne Konvertierung
        avdoc = Dispatch("AcroExch.AVDoc")
        try:
            avdoc.Open(src, src)
            pddoc = avdoc.GetPDDoc()
            pddoc.Save(PDSAVEFULL, dst)
            pddoc.Close()
            del pddoc
            avdoc.Close(NOSAVE)
            del avdoc
            if movesourcedir != '' and os.access(dst, os.F_OK) == True:
                print '  Moving %s to %s' %(files, movesourcedir)
                try:
                    os.rename(src, movesourcedir+os.sep+files)
                except:
                    stdout('    !!! Couldn`t move %s !!!'%src)
            conv_count += 1
            stdout('  Converted file %s\n'%files)
        except:
            stdout('  !!! Couldn`t convert %s !!!\n'%files)
 
    stoptime = datetime.datetime.now()
    runningtime = stoptime-starttime
 
    if runtype == 'batch':
        if conv_count != 0:
            performance=(conv_count/(float(runningtime.seconds)))*60
        else:
            performance=0
        print '-----------------------------------------------'
        print 'Converted %s documents to PDF.'%(conv_count)
        print 'All conversions done. Estimated performance: %s docs/min'%(performance)
        print
        print 'Acrobat2PDF (c) Dipl.-Ing. Mustafa Goermezer'
        print 'More document conversion solutions at http://www.goermezer.de'
 
if __name__=="__main__":
    input = outputdir = logfile = movesourcedir = ''
    # Default is overwrite existing PDFs
    overwrite = True
    runtype = 'batch'
    cfgfile = 'config.ini'
    try:
        opts, args = getopt.getopt(sys.argv[1:], "dhni:o:m:l:c:", 
        ["deamon", "help", "notoverwrite", "input=", "output=", "movesource=", "logfile=", "config="])
    except getopt.GetoptError:
        usage()
    for o, a in opts:
        if o in ("-d", "--deamon"):
            runtype = 'deamon'
        if o in ("-h", "--help"):
            usage()
        if o in ("-n", "--notoverwrite"):
            overwrite = False
        if o in ("-i", "--input"):
            input = os.path.abspath(a)
        if o in ("-o", "--output"):
            outputdir = os.path.abspath(a)
        if o in ("-m", "--movesource"):
            movesourcedir = os.path.abspath(a)
        if o in ("-l", "--logfile"):
            logfile = a
        if o in("-c", "--config"):
            cfgfile = os.path.abspath(a)
 
    # min. 2 Argumente muessen angegeben werden:
    # Checking input:
    if len(sys.argv) < 2:
        usage()
 
    if os.access(input, os.F_OK) != True and input.find('*') == -1:
        print 'Input directory %s doesn`t exist.'%input
        sys.exit(99)
    if os.access(outputdir, os.F_OK) != True:
        print 'Output directory %s doesn`t exist.'%outputdir
        sys.exit(99)
    if movesourcedir:
        if os.access(movesourcedir, os.F_OK) != True:
            print 'Directory for moved source files %s doesn`t exist.'%movesourcedir
            sys.exit(99)
 
    config = LoadConfig(cfgfile)
    poll = config["configsection.polltime"]
 
    stdout('Running Acrobat2PDF in %s mode\n'%runtype)
    if runtype == 'deamon':
        while 1:
            converter()
            #stdout('Waiting %s seconds...'% poll)
            time.sleep(int(poll))
    else:
        converter()
Last Updated ( Sunday, 10 August 2008 )
 
Next >

Feedback

Advertisement

Comments

  • I have run your code on my own machine, but I just got the last paragraph of the... More...
  • Hello Gabriel, It seem that the linked site moved to github.com/.../weboutlook (... More...
  • There is no script to download, could you provide the right link More...
  • Interesting but doesn't really help me. I do not see what the 'xxxxx' in the Ses... More...
  • You can see more python editor comparison: sparkledge.com/.../ (http://sparkledg... More...

Login Form






Lost Password?

My prefered Python IDE

My prefered Python editor is Pyscripter from MMExperts. It is not only an editor. Pyscripter is a full Python IDE including (remote) debugging, a class browser, and all other nice helpers which a full featured IDE needs.

Do you have a script for me ?

Do you have an interesting Python script which does some really cool thing on Windows ? Please post them to this site. It`s very simple - simply copy&paste it to this form. No login is requiered.

Hint: For syntax highlighting and correct Python intendation place your code between html tags <pre> and </pre>.

My prefered web framework

My prefered web framework for developing web applications is Django. Django calls itself The web framework for perfectionists with deadlines. It is a really fast, scalable and (thanks Python) the sexiest web framework of the world.