I'm trying to define "variables" in an openoffice document, and I must be doing something wrong because when I try to display the value of the variable using a field, I only get an empty string.
Here's the code I'm using (using the Python UNO bridge). The interesting bit is the second function.
import time
import subprocess
import logging
import os
import sys
import uno
from com.sun.star.text.SetVariableType import STRING
def get_uno_model(): # helper function to connect to OOo. Only interesting
# if you want to reproduce the issue locally,
# don't spend time on this one
try:
model = XSCRIPTCONTEXT.getDocument()
except NameError:
pass # we are not running in a macro
# get the uno component context from the PyUNO runtime
localContext = uno.getComponentContext()
# create the UnoUrlResolver
resolver = localContext.ServiceManager.createInstanceWithContext(
"com.sun.star.bridge.UnoUrlResolver", localContext )
# connect to the running office
try:
ctx = resolver.resolve("uno:socket,host=localhost,port=2002;"
"urp;StarOffice.ComponentContext")
except:
cmd = ['soffice', '--writer', '-accept=socket,host=localhost,port=2002;urp;']
popen = subprocess.Popen(cmd)
time.sleep(1)
ctx = resolver.resolve("uno:socket,host=localhost,port=2002;"
"urp;StarOffice.ComponentContext")
smgr = ctx.ServiceManager
# get the central desktop object
desktop = smgr.createInstanceWithContext("com.sun.star.frame.Desktop", ctx)
# access the current writer document
model = desktop.getCurrentComponent()
return model
def build_variable(model, name, value):
# find or create a TextFieldMaster with the correct name
master_prefix = u"com.sun.star.text.fieldmaster.SetExpression"
variable_names = set([_name.split('.')[-1]
for _name in model.TextFieldMasters.ElementNames
if _name.startswith(master_prefix)])
master_name = u'%s.%s' % (master_prefix, name)
if name not in variable_names:
master = model.createInstance(master_prefix)
master.Name = name
else:
master = model.TextFieldMasters.getByName(master_name)
# create the SetExpression field
field = model.createInstance(u'com.sun.star.text.textfield.SetExpression')
field.attachTextFieldMaster(master)
field.IsVisible = True
field.IsInput = False
field.SubType = STRING
field.Content = value
return field
model = get_uno_model() # local function to connect to OpenOffice
text = model.Text
field = build_variable(model, u'Toto', 'nice variable')
text.insertTextContent(text.getEnd(), field, False)
This code works somehow (unless I removed too much), but if I manually insert a field to display the value of Toto I don't get the 'nice variable' string that I expect, and the field which is inserted has no value
The code is missing setting the SubType property of the master field to STRING after the creation of the master field.