Libreoffice将docx文本字段表示为字段标记。
我可以使用以下MWE通过UNO桥创建它们:
ValueError: invalid literal for int() with base 10
保存后,段落将正确保存为
# to connect as client`
import uno
from pythonscript import ScriptContext
resolver = uno.getComponentContext().ServiceManager.createInstance('com.sun.star.bridge.UnoUrlResolver')
# start libreoffice as
# libreoffice --writer --accept="socket,host=localhost,port=2002;urp;"`
client = resolver.resolve('uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext')
XSCRIPTCONTEXT = ScriptContext(client, None, None)
doc = XSCRIPTCONTEXT.getDocument()
def cursor():
return doc.getCurrentController().getSelection().getByIndex(0)
t = doc.getText()
# insert text before field
t.insertString(cursor(), 'Fieldmark-Start|', False)
# create the field
field = doc.createInstance('com.sun.star.text.Fieldmark')
fieldcursor = cursor()
# add the String 'Field contents' to the document
fieldcursor.setString('Field contents')
# actually insert the field in the document (linked to the string)
field.attach(fieldcursor)
field.setFieldType('Testfieldtype')
field.setName('Fieldname')
# insert text after the field
t.insertString(cursor(), '|Fieldmark-End', False)
但是,我在文档中找不到任何现有的字段标记:
<text:p text:style-name="Standard">Fieldmark-Start|
<field:fieldmark-start text:name="Fieldname" field:type="Testfieldtype"/>
Field contents
<field:fieldmark-end/>
|Fieldmark-End</text:p>
答案 0 :(得分:1)
即使它们没有出现在doc.getTextFields()
或doc.getBookmarks()
中,仍然可以通过枚举文本来找到它们。
paragraphs = t.createEnumeration()
while paragraphs.hasMoreElements():
text_portions = paragraphs.nextElement().createEnumeration()
while text_portions.hasMoreElements():
text_portion = text_portions.nextElement()
if text_portion.TextPortionType == "TextFieldStart":
bookmark = text_portion.Bookmark
bookmark.Name
bookmark.FieldType
结果:
'Fieldname'
'Testfieldtype'
从这一点开始,请遵循UNO API文档,例如https://wiki.openoffice.org/wiki/Documentation/DevGuide/Text/Bookmarks。
同样的问题在https://ask.libreoffice.org/en/question/30175/how-access-fieldmarks-with-api/被问到,但没有正确的答案。