On lance une instance d'OpenOffice:
  • Pour la mise au point des scripts, on démarre une instance d'OpenOffice en mode server sur un port quelconque (ici 2002) comme ceci :
    soffice "-accept=socket,host=localhost,port=2002;urp;" 
    
    ce qui pemet de voir ce qui se passe.
  • Quand ça marche, on démarre l'instance dans un serveur X "virtual framebuffer" qui n'affiche rien.
    xvfb-run -a soffice "-accept=socket,host=localhost,port=2002;urp;" -headless
    
Le script Python

Nota : Il faut d'abord installer python-uno. Le script a été écrit par couper-coller et récupération de petits bouts de gauche à droite, il y a probablement des choses inutiles du côté des "from" par exemple. Pour le tester, commencer par créer un petit document HTML dans /tmp/a.html.

# -*- coding: latin-1 -*-

sourceFile = "/tmp/a.html"
targetFilePrefix = "/tmp/sortie"

import uno
import unohelper
import os.path

# a UNO struct later needed to create a document
from com.sun.star.text.ControlCharacter import PARAGRAPH_BREAK
from com.sun.star.text.TextContentAnchorType import AS_CHARACTER
from com.sun.star.awt import Size
from com.sun.star.beans import PropertyValue

# here we go
localContext = uno.getComponentContext()
resolver = localContext.ServiceManager.createInstanceWithContext(
    "com.sun.star.bridge.UnoUrlResolver",
    localContext )

s = "uno:socket,host=localhost,port=2002;urp;StarOffice.ServiceManager"
smgr = resolver.resolve(s)
remoteContext = smgr.getPropertyValue( "DefaultContext" )

desktop = smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",
                                          remoteContext)

# open a writer document
sourceUrl = unohelper.systemPathToFileUrl(os.path.abspath(sourceFile));
sourceDoc = desktop.loadComponentFromURL( sourceUrl, "_blank", 0, () )

# play with it
text = sourceDoc.Text
cursor = text.createTextCursor()
range = text.End
range.String = "\n et hop une ligne à la fin\n"
text.insertString( cursor, "\n et hop\nune ligne supplémentaire", 0)

# export it as PDF
properties = (PropertyValue('FilterName', 0, 'writer_pdf_Export', 0),)
targetUrl = unohelper.systemPathToFileUrl(os.path.abspath(
    targetFilePrefix + ".pdf"))
sourceDoc.storeToURL(targetUrl, properties)


# export it as DOC
properties = (PropertyValue('FilterName', 0, 'MS Word 95', 0),)
targetUrl = unohelper.systemPathToFileUrl(os.path.abspath(
    targetFilePrefix + ".doc" ))
sourceDoc.storeToURL(targetUrl, properties)
# end it
sourceDoc.close(True)
(à suivre)