首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >枚举libreoffice文档中的FieldMarks

枚举libreoffice文档中的FieldMarks
EN

Stack Overflow用户
提问于 2018-04-09 08:34:20
回答 1查看 358关注 0票数 1

Libreoffice将docx文本字段表示为字段标记。

我可以使用以下MWE通过UNO桥创建它们:

代码语言:javascript
运行
复制
# 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)

保存后,该段将正确保存为

代码语言:javascript
运行
复制
<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>

但是,我在文档中找不到任何当前的字段标记:

代码语言:javascript
运行
复制
# check if the contents are there
doc.getText().getString()
# -> 'Fieldmark-Start|Field contents|Fieldmark-End'

# try to enumerate all fields
tf = doc.getTextFields()
tf.hasElements() # -> true
enum = tf.createEnumeration()
enum.hasMoreElements() # -> false

# field = enum.nextElement()
# -> com.sun.star.container.NoSuchElementException
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-04-09 14:53:04

即使它们没有出现在doc.getTextFields()doc.getBookmarks()中,仍然可以通过枚举文本来找到它们。

代码语言:javascript
运行
复制
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

结果:

代码语言:javascript
运行
复制
'Fieldname'
'Testfieldtype'

从现在开始,遵循UNO文档(如https://wiki.openoffice.org/wiki/Documentation/DevGuide/Text/Bookmarks )。

https://ask.libreoffice.org/en/question/30175/how-access-fieldmarks-with-api/也提出了同样的问题,但没有一个有效的答案。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49728663

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档