Jump to content

Makros/Python-Leitfaden/Dokumente

From The Document Foundation Wiki
This page is a translated version of the page Macros/Python Guide/Documents and the translation is 100% complete.

Zurück zum Inhaltsverzeichnis


Dokumenten-Management innerhalb des Betriebssystemmanagers

WICHTIG Für jeden Argumentpfad in Methoden von pyUNO-Objekten verwenden Sie den Pfad (Path) im Format URL, verwendete Funktion uno.systemPathToFileUrl(PATH). Windows-Anwender beachten: Pfad-Segmente sind getrennt durch einen Schrägstrich (/).

ACHTUNG In den folgenden Beispielen ersetzen Sie USER mit Ihrem wirklichen Benutzernamen.

Neues leeres Dokument

import uno


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

# Dies ist ein üblicher Block zu den folgenden zwei Beispielen

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


# Um ein Calc-Dokument zu öffnen verwenden Sie diesen 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


# Um ein Writer-Dokument zu öffnen, verwenden Sie diesen 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

# Beenden Sie das Makro mit der folgenden Zeile:

g_exportedScripts = (new_doc_calc, new_doc_writer)


Für andere Dokumenten-Typen verwenden Sie im path Argument:

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

VORSICHT Kopieren oder importieren Sie die Funktion msgbox von Nützliche Funktionen

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

  • Für ein neues Base-Dokument verwenden Sie:

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

Öffnen

WICHTIG Denken Sie daran, den Dateipfad immer im URL-Format zu verwenden.

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

  • Öffnen mit Argumenten

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

  • Andere übliche Argumente

args = {'Hidden': True}
args = {'ReadOnly': True}
args = {'Preview': True}

 # Um Makros innerhalb des Dokuments zu aktivieren 
args = {'MacroExecutionMode': 4}

# Um ein Dokument aus einer Vorlage zu öffnen (True) oder um eine Vorlage zum Bearbeiten zu öffnen (False). 
args = {'AsTemplate': True}

Über alle offenen Dokumente iterieren

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

Aktuelles Dokument holen

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

# Ein anderer Weg, um dasselbe wie oben zu erreichen:

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

Nach PDF exportieren

Schauen Sie für weitere Optionen für das Exportieren in PDF-Export-Filter-Daten

  • Calc-Dokument als PDF exportieren

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

  • Mit anderen Optionen exportieren

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


Dokumenten-Management innerhalb von LibreOffice

Den Dokument-Typ holen

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

Den Fokus auf das aktuelle Dokument setzen

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

Das Dokument sichtbar oder unsichtbar machen

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

Den Zoom-Faktor für das Dokument setzen

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

Die aktuelle Auswahl holen

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

Management in der Statusleiste

  • Versuchen Sie diesen 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

  • Sie können nichts sehen, da die Ausführung blockiert ist.

Versuchen Sie nun dies.

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

Zurück zum Inhaltsverzeichnis