Search code examples
pythonlibreoffice

run libreoffice local macro from python?


In a python script, I know I can execute a custom libreoffice macro in the My Macros library container by grabbing a dispatcher and executing:

dispatcher.executeDispatch(frame, "macro:///Standard.Module1.mymacro", "", 0, ())

But how do I call a local document specific macro? I presume there is a replacement term for "macro///" such as perhaps "document///" that would make the call above work but I cannot find any documentation anywhere. What is the correct format for the macro call string?


Solution

  • Get the script provider from the document and use it to invoke the macro.

    desktop = XSCRIPTCONTEXT.getDesktop()
    file_url = uno.systemPathToFileUrl("C:/path/to/file.odt")
    doc = desktop.loadComponentFromURL(file_url, "_blank", 0, ())
    oScriptProvider = doc.getScriptProvider()
    oScript = oScriptProvider.getScript(
        "vnd.sun.star.script:Standard.Module1.mymacro?"
        "language=Basic&location=document")
    oScript.invoke((), (), ())
    

    Adapted from Execute LibreOffice Calc Basic macro from python.