1

I need to read / retrieve / get / enumerate currently open documents in any LibreOffice app (Writer, Calc, Present, Draw), on linux.

What I tried:

  • Searching the command line history is not helpful: Files can be opened/closed in LO via menus.
  • The Recent Document list shows only past docs).
  • using UNO-API, I was able to read only current document. I couln't find a command to enumerate / list all active documents.

This UNO python program just prints the active document's path. ~~But I didn't find a way to read all active documents~~.

#!/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) 

Solution:

Thanks to Jim K's answer (My version here is slightly more pythonic) :

components = desktop.getComponents() docs = oComponents.createEnumeration() for doc in docs: location = doc.Location title = doc.Title 
3
  • LibreOffice naming is a pain in the butt, especially when coming from VBA naming bg: "components" should've been "documents", and all the namespace has a huge overhead. Commented Jun 25, 2020 at 9:30
  • 1
    In LibreOffice, not all components are documents, for example, the Basic IDE. Also, there may be some older versions where for doc in docs fails. If you want to take shortcuts like that, then be sure to test the versions of LibreOffice and Python that the code needs to be compatible with. Commented Jun 25, 2020 at 17:42
  • As far as I can see, in Basic one has to access desktop using the name StarDesktop. Commented Sep 29, 2023 at 13:12

1 Answer 1

1

Call XDesktop.getComponents().

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 
1
  • As far as I can see, in Basic one has to access self.desktop using the name StarDesktop. Commented Sep 29, 2023 at 13:13

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.