Macros/Python Guide/Documents

    From The Document Foundation Wiki
    Other languages:

    Return to Index


    Document management within operating system manager

    IMPORTANT For any argument path in methods of pyUNO objects, always use path in format URL, used function uno.systemPathToFileUrl(PATH). Windows users note: path segments are separated by a slash (/).

    CAUTION In the following examples, substitute USER with your real username.

    New blank document

    import uno
    
    
    CTX = uno.getComponentContext()
    SM = CTX.getServiceManager()
    
    # This is a common block to the following two examples
    
    def create_instance(name, with_context=False):
        if with_context:
            instance = SM.createInstanceWithContext(name, CTX)
        else:
            instance = SM.createInstance(name)
        return instance
    
    
    # To open a Calc document use this block:
    
    def new_doc_calc():
        desktop = create_instance('com.sun.star.frame.Desktop', True)
        path = 'private:factory/scalc'
        doc = desktop.loadComponentFromURL(path, '_default', 0, ())
        return
    
    
    # To open a Writer document, use this block:
    
    def new_doc_writer():
        desktop = create_instance('com.sun.star.frame.Desktop', True)
        path = 'private:factory/swriter'
        doc = desktop.loadComponentFromURL(path, '_default', 0, ())
        return
    
    # End the macro with the following line:
    
    g_exportedScripts = (new_doc_calc, new_doc_writer)


    For other document types, use in path argument:

    • Impress: simpress
    • Draw: sdraw
    • Math: smath

    CAUTION Copy or import function msgbox from Useful functions

    from com.sun.star.beans import PropertyValue
    
    
    def new_doc_args():
        desktop = create_instance('com.sun.star.frame.Desktop', True)
        path = 'private:factory/sdraw'
        args = (PropertyValue(Name='Hidden', Value=True),)
        doc = desktop.loadComponentFromURL(path, '_default', 0, args)
        msgbox(doc.Title)
        doc.close(True)
        return

    • For a new Base document, use:

    def new_db():
        path = uno.systemPathToFileUrl('/home/USER/newdb.odb')
        dbc = create_instance('com.sun.star.sdb.DatabaseContext')
        db = dbc.createInstance()
        db.URL = 'sdbc:embedded:firebird'
        db.DatabaseDocument.storeAsURL(path, ())
        return

    Open

    IMPORTANT Remember, always use file path in URL format.

    path = uno.systemPathToFileUrl('/home/USER/calc.ods')
    desktop = create_instance('com.sun.star.frame.Desktop', True)
    doc = desktop.loadComponentFromURL(path, '_default', 0, ())

    • Open with arguments

    from com.sun.star.beans import PropertyValue
    
    def open_args():
        path = uno.systemPathToFileUrl('/home/USER/writer.odt')
        desktop = create_instance('com.sun.star.frame.Desktop', True)
        args = (PropertyValue(Name='Password', Value='letmein'),)
        doc = desktop.loadComponentFromURL(path, '_default', 0, args)
        return

    • Others commons arguments

    args = {'Hidden': True}
    args = {'ReadOnly': True}
    args = {'Preview': True}
    
     # To activate macros inside the document 
    args = {'MacroExecutionMode': 4}
    
    # To open a document from a template (True), or to open a template for editing (False). 
    args = {'AsTemplate': True}

    Iterate over all open documents

    desktop = create_instance('com.sun.star.frame.Desktop', True)
    for doc in desktop.getComponents():
        msgbox(doc.Title)

    Get current document

    doc = XSCRIPTCONTEXT.getDocument()
    msgbox(doc.Title)
    
    # Another way to accomplish the same above:
    
    desktop = create_instance('com.sun.star.frame.Desktop', True)
    doc = desktop.getCurrentComponent()
    msgbox(doc.Title)

    Export to PDF

    Look more options for exporting in PDF export filter data

    • Export Calc document as PDF

    from com.sun.star.beans import PropertyValue
    
    
    def dict_to_property(values, uno_any=False):
        ps = tuple([PropertyValue(Name=n, Value=v) for n, v in values.items()])
        if uno_any:
            ps = uno.Any('[]com.sun.star.beans.PropertyValue', ps)
        return ps
    
    
    def main():
        path_pdf = uno.systemPathToFileUrl('/home/mau/calc.pdf')
        doc = XSCRIPTCONTEXT.getDocument()
        args = {
            'FilterName': 'calc_pdf_Export',
        }
        args = dict_to_property(args)
        doc.storeToURL(path_pdf, args)
        return

    • Export with other options

    def main():
        path_pdf = uno.systemPathToFileUrl('/home/mau/calc.pdf')
        doc = XSCRIPTCONTEXT.getDocument()
        args = {
            'EncryptFile': True,
            'DocumentOpenPassword': 'letmein',
        }
        filter_data = dict_to_property(args, True)
        args = {
            'FilterName': 'calc_pdf_Export',
            'FilterData': filter_data,
        }
        args = dict_to_property(args)
        doc.storeToURL(path_pdf, args)
        return


    Document management within LibreOffice

    Get the document type

    def get_type_doc(doc):
        TYPE_DOC = {
            'calc': 'com.sun.star.sheet.SpreadsheetDocument',
            'writer': 'com.sun.star.text.TextDocument',
            'impress': 'com.sun.star.presentation.PresentationDocument',
            'draw': 'com.sun.star.drawing.DrawingDocument',
            'base': 'com.sun.star.sdb.DocumentDataSource',
            'math': 'com.sun.star.formula.FormulaProperties',
            'basic': 'com.sun.star.script.BasicIDE',
        }
        for k, v in TYPE_DOC.items():
            if doc.supportsService(v):
                return k
        return ''
    
    
    def main():
        doc = XSCRIPTCONTEXT.getDocument()
        msgbox(get_type_doc(doc))
        return

    Set focus for current document

    doc = XSCRIPTCONTEXT.getDocument()
    win = doc.getCurrentController().getFrame().getComponentWindow()
    win.setFocus()

    Make document visible or hidden

    doc = XSCRIPTCONTEXT.getDocument()
    win = doc.getCurrentController().getFrame().getComponentWindow()
    win.setVisible(False)
    msgbox(doc.Title)
    win.setVisible(True)

    Set zoom factor for a document

    doc = XSCRIPTCONTEXT.getDocument()
    doc.getCurrentController().ZoomValue = 150

    Get current selection

    doc = XSCRIPTCONTEXT.getDocument()
    sel = doc.getCurrentSelection()
    msgbox(sel.ImplementationName)

    Management in status bar

    • Try this code

    from time import sleep
    
    
    def main():
        doc = XSCRIPTCONTEXT.getDocument()
        statusbar = doc.getCurrentController().getStatusIndicator()
        statusbar.start('Line', 10)
        for i in range(10):
            statusbar.setValue(i)
            sleep(1)
        # ~ Is important free status bar
        statusbar.end()
        return

    • You cannot view anything because execution is blocked.

    Now, try this.

    import threading
    from time import sleep
    
    
    def run_in_thread(fn):
        def run(*k, **kw):
            t = threading.Thread(target=fn, args=k, kwargs=kw)
            t.start()
            return t
        return run
    
    
    @run_in_thread
    def update_status_bar(statusbar, text, limit):
        statusbar.start(text, limit)
        for i in range(limit):
            statusbar.setValue(i)
            sleep(1)
        # ~ Is important free status bar
        statusbar.end()
        return
    
    
    def main():
        doc = XSCRIPTCONTEXT.getDocument()
        statusbar = doc.getCurrentController().getStatusIndicator()
        update_status_bar(statusbar, 'Line', 10)
        return

    Return to Index