Macros/Python Guide/Documents

From The Document Foundation Wiki
Jump to: navigation, search


Return to Index

Other languages:
English


Documents

IMPORTANT: For any argument path in methods of pyUNO objects, always use path in format URL, used function uno.systemPathToFileUrl(PATH)

New

import uno


CTX = uno.getComponentContext()
SM = CTX.getServiceManager()


def create_instance(name, with_context=False):
    if with_context:
        instance = SM.createInstanceWithContext(name, CTX)
    else:
        instance = SM.createInstance(name)
    return instance


def new_doc_calc():
    desktop = create_instance('com.sun.star.frame.Desktop', True)
    path = 'private:factory/scalc'
    doc = desktop.loadComponentFromURL(path, '_default', 0, ())
    return


def new_doc_writer():
    desktop = create_instance('com.sun.star.frame.Desktop', True)
    path = 'private:factory/swriter'
    doc = desktop.loadComponentFromURL(path, '_default', 0, ())
    return


g_exportedScripts = (new_doc_calc, new_doc_writer)
  • For other documents used:
    • Impress: simpress
    • Draw: sdraw
    • Math: smath
  • Open con arguments

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 new database of Base used:
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

  • Remember, always used path file in format URL.
    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)
  • Others commons arguments
    args = {'Hidden': True}
    args = {'ReadOnly': True}
    args = {'Preview': True}

    # For macros activate
    args = {'MacroExecutionMode': 4}

    # For open documents like template, or (False) for open template for edit.
    args = {'AsTemplate': True}

Get documents

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

Current document

    doc = XSCRIPTCONTEXT.getDocument()
    msgbox(doc.Title)

    # Or

    desktop = create_instance('com.sun.star.frame.Desktop', True)
    doc = desktop.getCurrentComponent()
    msgbox(doc.Title)

Type doc

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

Send focus

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

Visible

  • Show or hidden document
    doc = XSCRIPTCONTEXT.getDocument()
    win = doc.getCurrentController().getFrame().getComponentWindow()
    win.setVisible(False)
    msgbox(doc.Title)
    win.setVisible(True)

Zoom

  • Set factor to zoom view
    doc = XSCRIPTCONTEXT.getDocument()
    doc.getCurrentController().ZoomValue = 150

Selection

  • Get current selection
    doc = XSCRIPTCONTEXT.getDocument()
    sel = doc.getCurrentSelection()
    msgbox(sel.ImplementationName)

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 not view any, because the execution it’s blocked. Now, try.
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

Export to PDF

Look more options for export in PDF export filter data

  • Export Calc document
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
  • Used more 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