首页 > 解决方案 > unotools 将图像插入文档(libreoffice)

问题描述

我正在尝试将图像插入到由 unotools 处理/控制的 libreoffice 文档中。

因此,我使用以下命令启动 LibreOffice:

soffice --accept='socket,host=localhost,port=8100;urp;StarOffice.Service'

在我的 python 代码中,我可以连接到 LibreOffice:

from unotools import Socket, connect
from unotools.component.writer import Writer
context = connect(Socket('localhost', 8100))
writer = Writer(context)

(此代码取自本文档:https ://pypi.org/project/unotools/ )

通过使用 writer.set_string_to_end() 我可以在文档中添加一些文本。但我也想在文档中插入图像。到目前为止,我找不到任何完成此操作的资源。图像在我的剪贴板内,所以理想情况下我想直接从那里插入图像。或者,我可以暂时保存图像并插入保存的文件。

有没有已知的方法如何使用 unotools 插入图像?任何替代解决方案也会很棒。

标签: pythonlibreofficeuno

解决方案


我找到了一种使用 uno 而不是 unotools 插入图像的方法:

import uno
from com.sun.star.awt import Size
from pythonscript import ScriptContext

def connect_to_office():
    if not 'XSCRIPTCONTEXT' in globals():
        localContext = uno.getComponentContext()
        resolver = localContext.ServiceManager.createInstanceWithContext(
                         'com.sun.star.bridge.UnoUrlResolver', localContext )
        client = resolver.resolve("uno:socket,host=localhost,port=8100;urp;StarOffice.ComponentContext" )
        global XSCRIPTCONTEXT
        XSCRIPTCONTEXT = ScriptContext(client, None, None)

def insert_image(doc):
    size = Size()
    path = uno.systemPathToFileUrl('/somepath/image.png')
    draw_page = self.doc.DrawPage
    image = doc.createInstance( 'com.sun.star.drawing.GraphicObjectShape')
    image.GraphicURL = path
    draw_page.add(image)
    size.Width = 7500
    size.Height = 5000
    image.setSize(size)
    image.setPropertyValue('AnchorType', 'AT_FRAME')

connect_to_office()
doc = XSCRIPTCONTEXT.getDocument()
insert_image(doc)

来源:

  1. https://ask.libreoffice.org/en/question/38844/how-do-i-run-python-macro-from-the-command-line/

  2. https://forum.openoffice.org/en/forum/viewtopic.php?f=45&t=80302

我仍然不知道如何从剪贴板插入图像,我通过先保存图像解决了这个问题。如果有人知道直接从剪贴板插入图像的方法,那仍然会有所帮助。


推荐阅读