Jump to content

マクロ/Pythonガイド/文書操作

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

目次に戻る


OS上での文書管理

重要 pyUNOオブジェクトのメソッドの引数パスには、uno.systemPathToFileUrl(PATH)関数を使用して常にURL形式のパスを使用します。Windowsユーザー向けの注意: パスの区切り記号はスラッシュ(/)を使います。

注意 以下に例を示しますが、USERは実際のユーザー名に置き換えてください。

新規文書を作成

import uno


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

# これは下の2つのサンプルに共通のブロックです

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


# Calc文書を開くには、このブロックのようにします:

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


# Writer文書を開くには、このブロックのようにします:

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)


ほかの文書形式を利用するには、path引数を指定します。

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

注意 便利な関数からmsgbox関数をコピーするかimportしておきます。

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

  • Baseの新規文書を開くには、このようにします

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

ファイルを開く

重要 ファイルパスには、URL形式を使用することを忘れないでください。

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

  • 引数を指定して開く

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

  • 共通して利用できる引数

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

 # 文書内でマクロを有効化する 
args = {'MacroExecutionMode': 4}

# テンプレートから文書を開く(True)。または編集するためにテンプレートから文書を開く(False)。 
args = {'AsTemplate': True}

イテレーターを使ってすべての文書を開く

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

現在の文書を取得

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

# 上と同じことを行う別の方法

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

PDFにエクスポートする

PDFのエクスポートについて、その他のオプションは PDFエクスポートフィルターをご覧ください。

  • Calc文書を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

  • オプションを指定してエクスポートする

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


LibreOfficeでの文書管理

文書形式を取得する

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

現在の文書にフォーカスを設定する

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

文書を表示、非表示にする

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

文書のズーム率を設定

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

選択している範囲を取得

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

ステータスバーの管理

  • このコードを試します

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

  • 実行がブロックされているため、何も表示できません。

次に、これを試します。:

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

目次に戻る