OpenOffice and Python
- Start openoffice so it listens on a port.
Connect to OpenOffice
- Open UNO. These are python bindings to openoffice api.
- Start python:
- Then import uno.
- Now import the local component context.
local = uno.getComponentContext()
Now access the UnoUrlResolver service. This will allow you to connect to OpenOffice.org program.
resolver = local.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", local)
Now load the context and you are now connected. You can access OpenOffice via its API mechanism.
context = resolver.resolve("uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext")
- There is a service responsible for the current document which is called desktop. This service can be access by the name "com.sun.star.frame.Desktop".
- We will be using that service so we need to create it/load it.
desktop = context.ServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", context)
- We now have access to the Desktop service. We now can load and manage documents.
To get the current document we call getCurrentComponent method:
document = desktop.getCurrentComponent()
- We need to create a cursor that we will use to write documents.
cursor = document.Text.createTextCursor()
- Lets add some text:
document.Text.insertString(cursor, "This text is being added to openoffice using python and uno package.", 0)
- Your text should show up on you screen.
==== Line breaks ===
- Line breaks:
document.Text.insertString(cursor, "\n\nThis is a new paragraph.", 0)
- The text is entered right after the previous sentence.