#!/usr/bin/env python
#!/usr/lib/openoffice/share/Scripts/python
# fix this bang path to the appropriate path to the openoffice python interpreter if you want to run from command line
# eg: !/home/dusty/OpenOffice.org1.1.2/program/python
# OpenOffice1.1 comes with its own python interpreter.
# This Script needs to be run with the python from OpenOffice.org:
#   /opt/OpenOffice.org/program/python 
# Start the Office before connecting:
# soffice "-accept=socket,host=localhost,port=2002;urp;"
#

# pyUNO Imports

import uno
from com.sun.star.beans import PropertyValue

# Python Imports

import os
import sys

# For a list of possible export formats see
# http://www.openoffice.org/files/documents/25/111/filter_description.html
# or
# /opt/OpenOffice.org/share/registry/data/org/openoffice/Office/TypeDetection.xcu

export_extension="pdf"
export_format="writer_pdf_Export"

def usage():
    print """Usage: %s in_file
All files in in_dir will be opened with OpenOffice.org and
saved to out_dir
You must start the office with this line before starting
this script:
  soffice "-accept=socket,host=localhost,port=2002;urp;"
  """ % (os.path.basename(sys.argv[0]))

def do_file(file, desktop):
    # Load File
    file=os.path.abspath(file)
    dir=os.path.dirname(file)
    url="file:///%s" % file
    properties=[]
    p=PropertyValue()
    p.Name="Hidden"
    p.Value=True
    properties.append(p)
    doc=desktop.loadComponentFromURL(url, "_blank", 0, tuple(properties));
    if not doc:
        print "Failed to open '%s'" % file
        return
    # Save File
    properties=[]
    p=PropertyValue()
    p.Name="Overwrite"
    p.Value=True
    properties.append(p)
    p=PropertyValue()
    p.Name="FilterName"
    p.Value=export_format
    properties.append(p)
    p=PropertyValue()
    p.Name="Hidden"
    p.Value=True
    basename=os.path.basename(file)
    idx=basename.rfind(".")
    if (idx!=-1):
        basename=basename[:idx]
    out_file="%s/%s.%s" % (dir, basename, export_extension)
    url_save="file://%s" % (out_file)
    try:
        doc.storeToURL(
            url_save, tuple(properties))
    except:
        print "Failed while writing: '%s.%s'" % (basename, export_extension)
    doc.dispose()
         
def main():
    if len(sys.argv)!=2:
        usage()
        sys.exit(1)
    in_file=sys.argv[1]
    # Init: Connect to running soffice process
    context = uno.getComponentContext()
    resolver=context.ServiceManager.createInstanceWithContext(
        "com.sun.star.bridge.UnoUrlResolver", context)
    try:
        ctx = resolver.resolve("uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext")
    except:
        print "Could not connect to running openoffice."
        usage()
        sys.exit()
    smgr=ctx.ServiceManager
    desktop = smgr.createInstanceWithContext("com.sun.star.frame.Desktop",ctx)
    print "Processing %s" % in_file
    do_file(in_file, desktop)

if __name__=="__main__":
    main()
