python - 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 插入图像?任何替代解决方案也会很棒。
解决方案
我找到了一种使用 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)
来源:
我仍然不知道如何从剪贴板插入图像,我通过先保存图像解决了这个问题。如果有人知道直接从剪贴板插入图像的方法,那仍然会有所帮助。
推荐阅读
- google-chrome - 如何在浏览器的控制台中查看 CORS 飞行前 OPTIONS 请求?
- unity3d - 在最新版本的 HoloToolKit 中,“TestButton”的等效更新名称是什么?2017.4.3.0
- java - Android:清除活动堆栈
- c# - Visual Studio 调试器进入 azure 函数项目的非用户代码
- html - 将两个段落放在不同标题高度的相同位置
- vim - 在 cscope 搜索中使用光标下的单词
- sql - 外连接或联合所有将行转换为列
- interface-builder - Interface Builder 中的 Xcode 11 beta 颜色库有什么用?
- react-redux - 如何让 Redux Action Creator 返回承诺?
- javascript - 需要时出现非法指令错误('@tensorflow/tfjs-node-gpu')