我需要在 Linux 上的任何 LibreOffice 应用程序(Writer、Calc、Present、Draw)中读取/检索/获取/枚举当前打开的文档。
我尝试过的:
- 搜索命令行历史记录没有帮助:可以通过菜单在 LO 中打开/关闭文件。
- 最近文档列表仅显示过去的文档)。
- 使用 UNO-API,我只能读取当前文档。我找不到枚举/列出所有活动文档的命令。
这个 UNO python 程序只打印积极的文档的路径。~~但是我没有找到读取所有活动文档的方法~~。
#!/opt/libreoffice6.4/program/python
import unohelper
import os
import uno
localContext = uno.getComponentContext() # get the uno component context from the PyUNO runtime
resolver = localContext.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", localContext )
ctx = resolver.resolve( "uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext" ) # connect to the running office
smgr = ctx.ServiceManager
desktop = smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",ctx)
model = desktop.getCurrentComponent()
print(model.URL)
解决方案:
感谢Jim K的回答(我的版本在这里稍微更具Python风格):
components = desktop.getComponents()
docs = oComponents.createEnumeration()
for doc in docs:
location = doc.Location
title = doc.Title
答案1
DOCTYPE_WRITER = 'writer'
DOCTYPE_CALC = 'calc'
def getOpenDocs(self, doctype='any'):
"""Returns currently open documents of type doctype."""
doclist = []
oComponents = self.desktop.getComponents()
oDocs = oComponents.createEnumeration()
while oDocs.hasMoreElements():
oDoc = oDocs.nextElement()
if oDoc.supportsService("com.sun.star.text.TextDocument"):
if doctype in ['any', self.DOCTYPE_WRITER]:
doclist.append(oDoc)
elif oDoc.supportsService("com.sun.star.sheet.SpreadsheetDocument"):
if doctype in ['any', self.DOCTYPE_CALC]:
doclist.append(oDoc)
return doclist