unotools在文档中插入图像(libreoffice)

2024-06-03 04:36:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在一个由unotools处理/控制的libreoffice文档中插入一个图像。在

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

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

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

^{pr2}$

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

通过使用writer.set_string_到\u end()我可以在文档中添加一些文本。但我还想在文档中插入图像。到目前为止,我找不到任何资源来做这件事。图像在我的剪贴板中,所以理想情况下我希望直接从那里插入图像。或者我可以暂时保存图像并插入保存的文件。在

有没有已知的方法可以使用unotools插入图像?任何其他的解决方案都会很好。在


Tags: 代码文档图像命令localhosthostlibreofficeport
1条回答
网友
1楼 · 发布于 2024-06-03 04:36:32

我找到了一种使用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)

sources:

  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

我仍然不知道如何从剪贴板中插入图像,我通过先保存图像来解决这个问题。如果有人知道直接从剪贴板插入图像的方法,那还是很有用的。在

相关问题 更多 >