在OpenOffice.org Writer中以编程方式创建SetExpression字段

时间:2012-12-31 16:58:03

标签: openoffice.org uno

我正在尝试在openoffice文档中定义“变量”,我必须做错事,因为当我尝试使用字段显示变量的值时,我只得到一个空字符串。

这是我正在使用的代码(使用Python UNO桥)。有趣的是第二个功能。

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)

这段代码以某种方式工作(除非我删除太多),但如果我手动插入一个字段来显示Toto的值我没有得到我期望的'nice variable'字符串,并且插入的字段有没有价值

2 个答案:

答案 0 :(得分:0)

在创建主字段后,缺少将主字段的SubType属性设置为STRING的代码。

答案 1 :(得分:0)

尝试

field.CurrentPresentation = value

请告诉我们这是否解决了您的问题,谢谢。