Class Lo

class ooodev.loader.Lo[source]

LibreOffice helper class

property bridge

Static read-only property.

Gets connection bridge component

Method NOT is Lo Instance Safe. Use Class LoContext when using with multiple document instances.

Return type:

XComponent

property current_doc

Static read-only property.

Gets the current document. Such as ooodev.calc.CalcDoc or ooodev.write.WriteDoc.

Method NOT is Lo Instance Safe. Use Class LoContext when using with multiple document instances.

Return type:

OfficeDocumentT

property is_macro_mode

Static read-only property.

Gets if currently running scripts inside of LO (macro) or standalone.

Return type:

bool

property null_date

Static read-only property.

Gets Value of Null Date in UTC.

Method is Lo Instance Safe for use with multiple documents.

Return type:

datetime

Note

If Lo has no document to determine date from then a default date of 1889/12/30 is returned.

property star_desktop

Static read-only property.

Get current desktop.

Method NOT is Lo Instance Safe. Use Class LoContext when using with multiple document instances.

Return type:

XDesktop

property this_component

Static read-only property.

When the current component is the Basic IDE, the ThisComponent object returns in Basic the component owning the currently run user script. Above behavior cannot be reproduced in Python.

When running in a macro this property can be access directly to get the current document.

When not in a macro then load_office() must be called first.

Method NOT is Lo Instance Safe. Use Class LoContext when using with multiple document instances.

Return type:

XComponent

property xscript_context

Static read-only property a substitute to XSCRIPTCONTEXT LibreOffice/OpenOffice built-in.

Method NOT is Lo Instance Safe. Use Class LoContext when using with multiple document instances.

Return type:

XScriptContext

property bridge_connector

Static read-only property.

Method NOT is Lo Instance Safe. Use Class LoContext when using with multiple document instances.

Get the current Bride connection

Return type:

LoBridgeCommon

property current_lo

Static read-only property.

Method NOT is Lo Instance Safe. Use Class LoContext when using with multiple document instances.

Get the current Lo instance

Return type:

LoInst

property loader_current

Static read-only property.

Method NOT is Lo Instance Safe. Use Class LoContext when using with multiple document instances.

Gets the current XComponentLoader instance.

Return type:

XComponentLoader

property desktop

Static read-only property.

Get the current Desktop instance.

Method NOT is Lo Instance Safe. Use Class LoContext when using with multiple document instances.

Desktop instance. Component property implments is XDesktop

Return type:

TheDesktop

property global_event_broadcaster

Static read-only property.

Get the current Global Broadcaster instance. This is a simpler way to add listeners to the global event broadcaster that are broadcasted by theGlobalEventBroadcaster.

Method NOT is Lo Instance Safe. Use Class LoContext when using with multiple document instances.

Desktop instance. Component property implments is XDesktop

Return type:

TheGlobalEventBroadcaster

import contextlib
from typing import TYPE_CHECKING, Any, cast
from ooodev.loader import Lo

if TYPE_CHECKING:
    from com.sun.star.document import DocumentEvent
else:
    DocumentEvent = Any

#  Add a listener to the global event broadcaster
Lo.global_event_broadcaster.add_event_document_event_occurred(_on_global_document_event)

def _on_global_document_event(src: Any, event: EventArgs, *args, **kwargs) -> None:
    # This is a listener for the global event broadcaster
    with contextlib.suppress(Exception):
        doc_event = cast(DocumentEvent, event.event_data)
        name = doc_event.EventName
        if name == "OnUnfocus":
            # only interested in the OnUnfocus event
            self._clear_cache()
class CLSID(value)

CLSID for Office documents

CALC = '47bbb4cb-ce4c-4e80-a591-42d9ae74950f'
CHART = '12dcae26-281f-416f-a234-c3086127382e'
DRAW = '4bab8970-8a3b-45b3-991c-cbeeac6bd5e3'
IMPRESS = '9176e48a-637a-4d1f-803b-99d9bfac1047'
MATH = '078b7aba-54fc-457f-8551-6147e776a997'
WRITER = '8bc6b165-b1b2-4edd-aa47-dae2ee689dd6'
class ConnectPipe(pipe=None, **kwargs)

Connect to LO via pipe

Parameters:

pipe (str | None) –

__init__(pipe=None, **kwargs)

Constructor

Parameters:

pipe (str | None, optional) – Name of pipe. Auto generated if None. Defaults to None.

Keyword Arguments:
  • no_restore (bool, optional) – Default True

  • no_first_start_wizard (bool, optional) – Default True

  • no_logo (bool, optional) – Default True

  • invisible (bool, optional) – Default True

  • headless (bool, optional) – Default False

  • start_as_service (bool, optional) – Default False

  • start_office (bool, optional) – Default True

  • soffice (Path | str, optional) – Path to soffice

  • env_vars (Dict[str, str], optional) – Environment variables to be set when starting office

  • extended_args (List[str], optional) – Extended arguments to be passed to soffice, such as ["--display :0"].

  • remote_connection (bool, optional) – Specifies if the connection is to a remote server. Default is False

Return type:

None

get_connection_identifier()

Gets connection identifier

Such as pipe,name="a34rt84y002"

Return type:

str

get_connection_str()

Gets connection string.

Such as uno:socket,host=localhost,port=2002;urp;StarOffice.ServiceManager

Return type:

str

property pipe: str

Gets/Sets pipe used to connect. Default is auto generated hex value

Return type:

str

class ConnectSocket(host='localhost', port=2002, **kwargs)

Connect to LO via socket

__init__(host='localhost', port=2002, **kwargs)

Constructor

Parameters:
  • host (str, optional) – Connection host. Defaults to localhost.

  • port (int, optional) – Connection port. Defaults to 2002.

Keyword Arguments:
  • no_restore (bool, optional) – Default True

  • no_first_start_wizard (bool, optional) – Default True

  • no_logo (bool, optional) – Default True

  • invisible (bool, optional) – Default True

  • headless (bool, optional) – Default False

  • start_as_service (bool, optional) – Default False

  • start_office (bool, optional) – Default True

  • soffice (Path | str, optional) – Path to soffice

  • env_vars (Dict[str, str], optional) – Environment variables to be set when starting office

  • extended_args (List[str], optional) – Extended arguments to be passed to soffice, such as ["--display :0"].

  • remote_connection (bool, optional) – Specifies if the connection is to a remote server. Default is False

Return type:

None

get_connection_identifier()

Gets connection identifier

Such as socket,host=localhost,port=2002

Return type:

str

get_connection_str()

Gets connection string.

Such as uno:socket,host=localhost,port=2002;urp;StarOffice.ServiceManager

Return type:

str

property host: str

Gets/Sets host. Default localhost

Return type:

str

property port: int

Gets/Sets port. Default 2002

Return type:

int

class ControllerLock(lo_inst=None)[source]

Context manager for Locking Controller

In the following example ControllerLock is called using with.

All code inside the with Lo.ControllerLock() as x_doc block is written with controller locked. This means the ui will not update until the block is done. A soon as the block is processed the controller is unlocked and the ui is updated.

Can be useful for large writes in document. Will give a speed improvement.

When using ControllerLock in multi document mode the lo_inst must be passed.

Example

Single-document Mode example.

doc1  = WriteDoc.create_doc()

with Lo.ControllerLock() as x_doc:
    cursor = doc1.get_cursor()
    cursor.append(text="Some examples of simple text ")
    # do a bunch or work.
    ...

Multi-document Mode example.

lo_inst = Lo.create_lo_instance()

doc2  = WriteDoc.create_doc(lo_inst=lo_inst)

with Lo.ControllerLock(lo_inst=doc.lo_inst) as x_doc:
    cursor = doc2.get_cursor()
    cursor.append("Some examples of simple text ")
    # do a bunch or work.
    ...

If Class LoContext is used it is not necessary to pass lo_inst in multi-document mode.

from ooodev.utils.context.lo_context import LoContext
lo_inst = Lo.create_lo_instance()

doc2  = WriteDoc.create_doc(lo_inst=lo_inst)

with LoContext(lo_inst=doc.lo_inst):
    with Lo.ControllerLock() as x_doc:
        cursor = doc2.get_cursor()
        cursor.append("Some examples of simple text ")
        # do a bunch or work.
        ...
Parameters:

lo_inst (lo_inst.LoInst | None) –

__init__(lo_inst=None)[source]

ControllerLock constructor.

Parameters:

lo_inst (LoInst, optional) – Lo Instance. Use when creating multiple documents. Defaults to Lo.current_lo.

class DocType(value)

Document Type

get_doc_type_str()

Gets the document type as string Enum

Return type:

DocTypeStr

get_service()

Gets the service type as Service Enum

Return type:

Service

BASE = 2
CALC = 3
DRAW = 4
IMPRESS = 5
MATH = 6
UNKNOWN = 0
WRITER = 1
class DocTypeStr(value)

Document Type as string Enum

get_doc_type()

Gets the document type as DocType Enum

Return type:

DocType

get_service()

Gets the service type as Service Enum

Return type:

Service

BASE = 'sbase'
CALC = 'scalc'
DRAW = 'sdraw'
IMPRESS = 'simpress'
MATH = 'smath'
UNKNOWN = 'unknown'
WRITER = 'swriter'
class Loader(connector, cache_obj=None, opt=None)[source]

Context Manager for Loader

Example

with Lo.Loader(Lo.ConnectSocket()) as loader:
    doc = Write.create_doc(loader)
    ...
Parameters:
__init__(connector, cache_obj=None, opt=None)[source]

Create a connection to office

Parameters:
  • connector (connectors.ConnectPipe | connectors.ConnectSocket | None) – Connection information. Ignore for macros.

  • cache_obj (Cache | None, optional) – Cache instance that determines if LibreOffice profile is to be copied and cached Ignore for macros. Defaults to None.

  • opt (Options, optional) – Extra Load options.

Changed in version 0.6.10: Added opt parameter.

Hint: - Options can be imported from ooodev.loader.inst.options

class Options(verbose=False, dynamic=True, log_level=20, lo_cache_size=200)

Lo Load options

New in version 0.6.10.

Parameters:
  • verbose (bool) –

  • dynamic (bool) –

  • log_level (int) –

  • lo_cache_size (int) –

__init__(verbose=False, dynamic=True, log_level=20, lo_cache_size=200)
Parameters:
  • verbose (bool) –

  • dynamic (bool) –

  • log_level (int) –

  • lo_cache_size (int) –

Return type:

None

dynamic: bool = True

Determines if the script context is dynamic.

Also When loading a component via LoInst.load_component() It is recommended to set this value to False.

If dynamic the script context is created with the current document; Otherwise, context is static. Static context is useful when the script is only going to operate on a a single document. There may be a performance gain when using static context.

Default True

New in version 0.11.13.

lo_cache_size: int = 200

Lo Instance cache size. Default 200, 0 or less means no caching. Normally you should not need to change this value. If you do, it should be a power of 2.

log_level: int = 20

Logging level. Default logging.INFO

verbose: bool = False

Determines if various info is sent to console. Default False

class Service(value)

Service Type

get_doc_type()

Gets the document type as DocType Enum

Return type:

DocType

get_doc_type_str()

Gets the document type as DocTypeStr Enum

Return type:

DocTypeStr

BASE = 'com.sun.star.sdb.OfficeDatabaseDocument'
CALC = 'com.sun.star.sheet.SpreadsheetDocument'
DRAW = 'com.sun.star.drawing.DrawingDocument'
IMPRESS = 'com.sun.star.presentation.PresentationDocument'
MATH = 'com.sun.star.formula.FormulaProperties'
UNKNOWN = 'com.sun.frame.XModel'
WRITER = 'com.sun.star.text.TextDocument'
classmethod addon_initialize(addon_xcc)[source]

Initialize and ad-don.

Method NOT is Lo Instance Safe. Use Class LoContext when using with multiple document instances.

Parameters:

addon_xcc (XComponentContext) – Add-on component context

Raises:
  • TypeError – If addon_xcc is None

  • Exception – If unable to get service manager from addon_xcc

  • Exception – If unable to access desktop

  • Exception – If unable to access document

  • MissingInterfaceError – If unable to get XMultiServiceFactory interface instance

  • CancelEventError – If DOC_OPENING is canceled

Returns:

add-on as component

Return type:

XComponent

Events:

Note

Event args event_data is a dictionary containing all method parameters.

static capitalize(s)[source]

Capitalizes a string.

Method is Lo Instance Safe for use with multiple documents.

Parameters:

s (str) – String to capitalize.

Returns:

string capitalized.

Return type:

str

classmethod close(closeable)[source]
classmethod close(closeable, deliver_ownership: bool)
classmethod close(closeable, deliver_ownership=False)

Closes a document.

Method is Lo Instance Safe for use with multiple documents.

Parameters:
  • closeable (XCloseable) – Object that implements XCloseable interface.

  • deliver_ownership (bool) – True delegates the ownership of this closing object to anyone which throw the CloseVetoException. This new owner has to close the closing object again if his still running processes will be finished. False let the ownership at the original one which called the close() method. They must react for possible CloseVetoExceptions such as when document needs saving and try it again at a later time. This can be useful for a generic UI handling.

Returns:

True if Closed; Otherwise, False

Return type:

bool

Events:
classmethod close_doc(doc)[source]
classmethod close_doc(doc, deliver_ownership: bool)
classmethod close_doc(doc, deliver_ownership=False)

Closes document.

Method is Lo Instance Safe for use with multiple documents.

Parameters:
  • doc (XCloseable) – Close-able document

  • deliver_ownership (bool) – If True delegates the ownership of this closing object to anyone which throw the CloseVetoException. Default is False.

Raises:

MissingInterfaceError – if doc does not have XCloseable interface

Return type:

None

Note

If deliver_ownership is True then new owner has to close the closing object again if his still running processes will be finished.

False let the ownership at the original one which called the close() method. They must react for possible CloseVetoExceptions such as when document needs saving and try it again at a later time. This can be useful for a generic UI handling.

Attention

close() method is called along with any of its events.

classmethod close_office()[source]

Closes the office connection.

Method NOT is Lo Instance Safe. Use Class LoContext when using with multiple document instances.

Returns:

True if office is closed; Otherwise, False

Return type:

bool

Events:
classmethod create_doc(doc_type: DocTypeStr)[source]
classmethod create_doc(doc_type: DocTypeStr, loader: com.sun.star.frame.XComponentLoader)
classmethod create_doc(doc_type: DocTypeStr, *, props: Iterable[ooo.lo.beans.property_value.PropertyValue])
classmethod create_doc(doc_type: DocTypeStr, loader: com.sun.star.frame.XComponentLoader, props: Iterable[ooo.lo.beans.property_value.PropertyValue])
classmethod create_doc(doc_type, loader=None, props=None)

Creates a document.

Method NOT is Lo Instance Safe. Use Class LoContext when using with multiple document instances.

Parameters:
  • doc_type (DocTypeStr) – Document type.

  • loader (XComponentLoader) – Component Loader.

  • props (Iterable[PropertyValue]) – Property values.

Raises:

Exception – If unable to create document.

Returns:

document as component.

Return type:

XComponent

Events:

Note

Event args event_data is a dictionary containing all method parameters.

classmethod create_doc_from_template(template_path)[source]
classmethod create_doc_from_template(template_path, loader: com.sun.star.frame.XComponentLoader)
classmethod create_doc_from_template(template_path, loader=None)

Create a document from a template.

Method NOT is Lo Instance Safe. Use Class LoContext when using with multiple document instances.

Parameters:
  • template_path (PathOrStr) – path to template file.

  • loader (XComponentLoader) – Component Loader.

Raises:

Exception – If unable to create document.

Returns:

document as component.

Return type:

XComponent

classmethod create_instance_mcf(atype: Type[ooodev.utils.type_var.T], service_name: str) T | None[source]
classmethod create_instance_mcf(atype: Type[ooodev.utils.type_var.T], service_name: str, args: Tuple[Any, ...] | None) T | None
classmethod create_instance_mcf(atype: Type[ooodev.utils.type_var.T], service_name: str, *, raise_err: Literal[True]) ooodev.utils.type_var.T
classmethod create_instance_mcf(atype: Type[ooodev.utils.type_var.T], service_name: str, *, raise_err: Literal[False]) T | None
classmethod create_instance_mcf(atype: Type[ooodev.utils.type_var.T], service_name: str, args: Tuple[Any, ...] | None, raise_err: Literal[True]) ooodev.utils.type_var.T
classmethod create_instance_mcf(atype: Type[ooodev.utils.type_var.T], service_name: str, args: Tuple[Any, ...] | None, raise_err: Literal[False]) T | None
classmethod create_instance_mcf(atype, service_name, args=None, raise_err=False)

Creates an instance of a component which supports the services specified by the factory, and optionally initializes the new instance with the given arguments and context.

The interface specified by atype is returned from created instance.

Method NOT is Lo Instance Safe. Use Class LoContext when using with multiple document instances.

Parameters:
  • atype (Type[T]) – Type of interface to return from created instance. Any Uno class that starts with X such as XInterface

  • service_name (str) – Service Name

  • args (Tuple[Any, ...], Optional) – Args

  • raise_err (bool, optional) – If True then can raise CreateInstanceMcfError or MissingInterfaceError. Default is False

Raises:
  • CreateInstanceMcfError – If raise_err is True and no instance was created

  • MissingInterfaceError – If raise_err is True and instance was created but does not implement atype interface.

  • Exception – if unable to create instance for any other reason

Return type:

T | None

Note

When raise_err=True return value will never be None.

Returns:

Instance of interface for the service name or possibly None if raise_err is False.

Return type:

T | None

Parameters:
  • atype (Type[T]) –

  • service_name (str) –

  • args (Tuple[Any, ...] | None) –

  • raise_err (bool) –

Example

In the following example tk is an instance of XExtendedToolkit

from com.sun.star.awt import XExtendedToolkit
tk = Lo.create_instance_mcf(XExtendedToolkit, "com.sun.star.awt.Toolkit")
classmethod create_instance_msf(atype: Type[ooodev.utils.type_var.T], service_name: str) T | None[source]
classmethod create_instance_msf(atype: Type[ooodev.utils.type_var.T], service_name: str, msf: Any | None) T | None
classmethod create_instance_msf(atype: Type[ooodev.utils.type_var.T], service_name: str, *, raise_err: Literal[True]) ooodev.utils.type_var.T
classmethod create_instance_msf(atype: Type[ooodev.utils.type_var.T], service_name: str, *, raise_err: Literal[False]) T | None
classmethod create_instance_msf(atype: Type[ooodev.utils.type_var.T], service_name: str, msf: Any | None, raise_err: Literal[True]) ooodev.utils.type_var.T
classmethod create_instance_msf(atype: Type[ooodev.utils.type_var.T], service_name: str, msf: Any | None, raise_err: Literal[True], *args: Any) ooodev.utils.type_var.T
classmethod create_instance_msf(atype: Type[ooodev.utils.type_var.T], service_name: str, msf: Any | None, raise_err: Literal[False]) T | None
classmethod create_instance_msf(atype: Type[ooodev.utils.type_var.T], service_name: str, msf: Any | None, raise_err: Literal[False], *args: Any) T | None
classmethod create_instance_msf(atype, service_name, msf=None, raise_err=False, *args)

Creates an instance classified by the specified service name and optionally passes arguments to that instance.

The interface specified by atype is returned from created instance.

Method NOT is Lo Instance Safe. Use Class LoContext when using with multiple document instances.

Parameters:
  • atype (Type[T]) – Type of interface to return from created service. Any Uno class that starts with ‘X’ such as XInterface

  • service_name (str) – Service name

  • msf (XMultiServiceFactory, optional) – Multi service factory used to create instance

  • raise_err (bool, optional) – If True then can raise CreateInstanceMsfError or MissingInterfaceError. Default is False

  • args (Any, optional) – Arguments to pass to instance

Raises:
  • CreateInstanceMsfError – If raise_err is True and no instance was created

  • MissingInterfaceError – If raise_err is True and instance was created but does not implement atype interface.

  • Exception – if unable to create instance for any other reason

Returns:

Instance of interface for the service name or possibly None if raise_err is False.

Return type:

T

Note

When raise_err=True return value will never be None.

Example

In the following example src_con is an instance of XSheetCellRangeContainer

from com.sun.star.sheet import XSheetCellRangeContainer
src_con = Lo.create_instance_msf(XSheetCellRangeContainer, "com.sun.star.sheet.SheetCellRanges")

Changed in version 0.40.0: Added args parameter

classmethod create_lo_instance(opt=None)[source]

Creates a new Lo instance.

Parameters:

opt (LoOptions, optional) – Options for Lo instance. Defaults to current options.

Returns:

Lo instance

Return type:

LoInst

classmethod create_macro_doc(doc_type)[source]
classmethod create_macro_doc(doc_type, loader: com.sun.star.frame.XComponentLoader)
classmethod create_macro_doc(doc_type, loader=None)

Create a document that allows executing of macros.

Method NOT is Lo Instance Safe. Use Class LoContext when using with multiple document instances.

Parameters:
  • doc_type (DocTypeStr) – Document type.

  • loader (XComponentLoader) – Component Loader.

Returns:

document as component.

Return type:

XComponent

Attention

create_doc() method is called along with any of its events.

static delay(ms)[source]

Delay execution for a given number of milliseconds.

Method is Lo Instance Safe for use with multiple documents.

Parameters:

ms (int) – Number of milliseconds to delay

Return type:

None

classmethod dispatch_cmd(cmd, props=None, frame=None, in_thread=False)[source]

Dispatches a LibreOffice command.

Method NOT is Lo Instance Safe. Use Class LoContext when using with multiple document instances.

Parameters:
  • cmd (str) – Command to dispatch such as GoToCell. Note: cmd does not need to start with .uno: prefix.

  • props (PropertyValue, optional) – properties for dispatch.

  • frame (XFrame, optional) – Frame to dispatch to.

  • in_thread (bool, optional) – If True then dispatch is done in a separate thread.

Raises:
Returns:

A possible result of the executed internal dispatch. The information behind this any depends on the dispatch!

Return type:

Any

Events:

Note

There are many dispatch command constants that can be found in dispatch Namespace

DISPATCHING Event args data contains any properties passed in via props.
DISPATCHED Event args data contains any results from the dispatch commands.

Changed in version 0.40.0: Now supports in_thread parameter.

classmethod doc_type_str(doc_type_val)[source]

Converts a doc type into a DocTypeStr representation.

Method is Lo Instance Safe for use with multiple documents.

Parameters:

doc_type_val (DocType) – Doc type as int

Returns:

doc type as string.

Return type:

DocTypeStr

classmethod ext_to_doc_type(ext)[source]

Gets document type from extension.

Method is Lo Instance Safe for use with multiple documents.

Parameters:

ext (str) – extension used for lookup

Returns:

DocTypeStr enum. If not match if found defaults to DocTypeStr.WRITER

Return type:

DocTypeStr

classmethod ext_to_format(ext)[source]
classmethod ext_to_format(ext, doc_type: DocType)
classmethod ext_to_format(ext, doc_type=DocType.UNKNOWN)

Convert the extension string into a suitable office format string. The formats were chosen based on the fact that they are being used to save (or export) a document.

Method is Lo Instance Safe for use with multiple documents.

Parameters:
  • ext (str) – document extension

  • doc_type (DocType) – Type of document.

Returns:

format of ext such as text, rtf, odt, pdf, jpg etc… Defaults to text if conversion is unknown.

Return type:

str

Note

doc_type is used to distinguish between the various meanings of the PDF ext. This could be a lot more extensive.

Use Info.getFilterNames() to get the filter names for your Office.

classmethod extract_item_name(uno_cmd)[source]

Extract a uno command from a string that was created with make_uno_cmd().

Method is Lo Instance Safe for use with multiple documents.

Parameters:

uno_cmd (str) – uno command.

Raises:

ValueError – If unable to extract command.

Returns:

uno command.

Return type:

str

classmethod find_container_props(con, nm)[source]

Find as Property Set in a container.

Method is Lo Instance Safe for use with multiple documents.

Parameters:
  • con (XIndexAccess) – Container to search.

  • nm (str) – Name of property to search for.

Raises:

TypeError – if con is None.

Returns:

Found property set; Otherwise, None.

Return type:

XPropertySet | None

classmethod get_component_factory()[source]

Gets current multi component factory.

Method NOT is Lo Instance Safe. Use Class LoContext when using with multiple document instances.

Return type:

XMultiComponentFactory

classmethod get_container_names(con)[source]

Gets container names.

Method is Lo Instance Safe for use with multiple documents.

Parameters:

con (XIndexAccess) – container.

Returns:

Container name is found; Otherwise, None.

Return type:

List[str] | None

classmethod get_context()[source]

Gets current LO Component Context.

Method NOT is Lo Instance Safe. Use Class LoContext when using with multiple document instances.

Return type:

XComponentContext

classmethod get_desktop()[source]

Gets current LO Desktop.

Method NOT is Lo Instance Safe. Use Class LoContext when using with multiple document instances.

Return type:

XDesktop

classmethod get_flat_filter_name(doc_type)[source]

Gets the Flat XML filter name for the doc type.

Method is Lo Instance Safe for use with multiple documents.

Parameters:

doc_type (DocTypeStr) – Document type.

Returns:

Flat XML filter name.

Return type:

str

New in version 0.12.0.

classmethod get_frame()[source]

Gets XFrame for current LibreOffice instance.

Method NOT is Lo Instance Safe. Use Class LoContext when using with multiple document instances.

Returns:

frame

Return type:

XFrame

classmethod get_model()[source]

Gets XModel.

Method NOT is Lo Instance Safe. Use Class LoContext when using with multiple document instances.

Returns:

Gets model for current LibreOffice instance

Return type:

XModel

static get_parent(a_component)[source]

Retrieves the parent of the given object.

Method is Lo Instance Safe for use with multiple documents.

Parameters:

a_component (XChild) – component to get parent of.

Returns:

parent component.

Return type:

XInterface

classmethod get_relative_doc()[source]

Gets current document.

If the current options are set to dynamic, then the current document is returned from the script context. Otherwise, the current internal document is returned. The internal document is set when a new document is created via the Write, Calc, etc.

In most instances the internal document is the same as the xscript context document.

By Default the dynamic option is set to False.

Method NOT is Lo Instance Safe. Use Class LoContext when using with multiple document instances.

Raises:

NoneError – If the document is None.

Returns:

Current Document

Return type:

XComponent

classmethod get_service_factory()[source]

Gets current multi service factory.

Method NOT is Lo Instance Safe. Use Class LoContext when using with multiple document instances.

Return type:

XMultiServiceFactory

classmethod get_singleton(name)[source]

Gets a singleton object from the office default context.

Parameters:

name (str) – Singleton name such as /singletons/com.sun.star.frame.theDesktop.

Returns:

Singleton object or None if not found.

Return type:

Any

New in version 0.40.0.

classmethod get_supported_dispatch_prefixes()[source]

Get supported dispatch prefixes by the dispatch_cmd() method.

Method is Lo Instance Safe for use with multiple documents.

Returns:

Tuple of supported dispatch prefixes.

Return type:

Tuple[str, …]

New in version 0.40.0.

classmethod has_controllers_locked()[source]

Determines if there is at least one lock remaining.

While there is at least one lock remaining, some notifications for display updates are not broadcast to the controllers.

Method NOT is Lo Instance Safe. Use Class LoContext when using with multiple document instances.

Returns:

True if any lock exist; Otherwise, False.

Return type:

bool

classmethod inspect(obj)[source]

Inspects object using org.openoffice.InstanceInspector inspector.

Method NOT is Lo Instance Safe. Use Class LoContext when using with multiple document instances.

Parameters:

obj (object) – object to inspect.

Return type:

None

static is_none_or_empty(s)[source]

Gets is a string is None or Empty.

Method is Lo Instance Safe for use with multiple documents.

Parameters:

s (str) – String to check.

Returns:

True if None or empty string; Otherwise, False

Return type:

bool

static is_null_or_empty(s)

Gets is a string is None or Empty.

Method is Lo Instance Safe for use with multiple documents.

Parameters:

s (str) – String to check.

Returns:

True if None or empty string; Otherwise, False

Return type:

bool

classmethod is_uno_interfaces(component, *args)[source]

Gets if an object contains interface(s).

Method is Lo Instance Safe for use with multiple documents.

Parameters:
  • component (Any) – object to check for supplied interfaces.

  • args (str | UnoInterface) – one or more strings such as ‘com.sun.star.uno.XInterface’ or Any uno interface that Starts with X such has XEnumTypeDescription.

Returns:

True if component contains all supplied interfaces; Otherwise, False

Return type:

bool

classmethod is_url(fnm)[source]

Gets if a string is a URL format.

Method is Lo Instance Safe for use with multiple documents.

Parameters:

fnm (PathOrStr) – string to check.

Returns:

True if URL format; Otherwise, False

Return type:

bool

classmethod kill_office()[source]

Kills the office connection.

Method NOT is Lo Instance Safe. Use Class LoContext when using with multiple document instances.

Return type:

None

See also

close_office()

classmethod load_office(connector=None, cache_obj=None, opt=None)[source]

Loads Office

Not available in a macro.

If running outside of office then a bridge is created that connects to office.

If running from inside of office e.g. in a macro, then Lo.XSCRIPTCONTEXT is used. using_pipes is ignored with running inside office.

Parameters:
  • connector (connectors.ConnectPipe, connectors.ConnectSocket, optional) – Connection information. Ignore for macros.

  • cache_obj (Cache, optional) – Cache instance that determines of LibreOffice profile is to be copied and cached Ignore for macros. Defaults to None.

  • opt (Options, optional) – Extra Load options.

Return type:

XComponentLoader

Method NOT is Lo Instance Safe. Use Class LoContext when using with multiple document instances.

Returns:

component loader

Return type:

XComponentLoader

Events:
Parameters:

Note

Event args event_data is a dictionary containing all method parameters.

Example

loader =  Lo.Loader(Lo.ConnectSocket()):
doc = Write.create_doc(loader)
...

Changed in version 0.6.10: Added opt parameter.

Changed in version 0.11.11: If office is already loaded and a new call is made to this method, then the new call will return the existing office instance if the following conditions are met:

Connection must be ConnectorSocket or ConnectorPipe and the connections strings must match.

classmethod lock_controllers()[source]

Suspends some notifications to the controllers which are used for display updates.

The calls to lock_controllers() and unlock_controllers() may be nested and even overlapping, but they must be in pairs. While there is at least one lock remaining, some notifications for display updates are not broadcast.

Method NOT is Lo Instance Safe. Use Class LoContext when using with multiple document instances.

Raises:

MissingInterfaceError – If unable to obtain XModel interface.

Returns:

False if CONTROLLERS_LOCKING event is canceled; Otherwise, True

Return type:

bool

Events:
static make_uno_cmd(item_name)[source]

Make a uno command that can be used with extract_item_name().

Method is Lo Instance Safe for use with multiple documents.

Parameters:

item_name (str) – command item name.

Returns:

uno command string.

Return type:

str

classmethod mri_inspect(obj)[source]

Call MRI’s inspect() to inspect obj.

Method NOT is Lo Instance Safe. Use Class LoContext when using with multiple document instances.

Parameters:

obj (object) – obj to inspect

Raises:

Exception – If MRI service could not be instantiated.

Return type:

None

Return type:

None

Parameters:

obj (object) –

classmethod open_doc(fnm)[source]
classmethod open_doc(fnm, loader: com.sun.star.frame.XComponentLoader)
classmethod open_doc(fnm, *, props: Iterable[ooo.lo.beans.property_value.PropertyValue])
classmethod open_doc(fnm, loader: com.sun.star.frame.XComponentLoader, props: Iterable[ooo.lo.beans.property_value.PropertyValue])
classmethod open_doc(fnm, loader=None, props=None)

Open a office document.

Method NOT is Lo Instance Safe. Use Class LoContext when using with multiple document instances.

Parameters:
  • fnm (PathOrStr) – path of document to open.

  • loader (XComponentLoader) – Component Loader.

  • props (Iterable[PropertyValue]) – Properties passed to component loader.

Raises:
  • Exception – if unable to open document.

  • CancelEventError – if DOC_OPENING event is canceled.

Returns:

Document.

Return type:

XComponent

Events:

Note

Event args event_data is a dictionary containing all method parameters.

Note

If connection it office is a remote server then File URL must be used, such as file:///home/user/fancy.odt

Example

from ooodev.loader.lo import Lo

# connect to office
with Lo.Loader() as loader:
    doc = Lo.open_doc("/home/user/fancy.odt", loader)
    ...
classmethod open_flat_doc(fnm, doc_type)[source]
classmethod open_flat_doc(fnm, doc_type, loader: com.sun.star.frame.XComponentLoader)
classmethod open_flat_doc(fnm, doc_type, loader=None)

Opens a flat document.

Method NOT is Lo Instance Safe. Use Class LoContext when using with multiple document instances.

Parameters:
  • fnm (PathOrStr) – path of XML document

  • doc_type (DocType) – Type of document to open

  • loader (XComponentLoader) – Component loader

Returns:

Document

Return type:

XComponent

Attention

open_doc() method is called along with any of its events.

classmethod open_readonly_doc(fnm)[source]
classmethod open_readonly_doc(fnm, loader: com.sun.star.frame.XComponentLoader)
classmethod open_readonly_doc(fnm, loader=None)

Open a office document as read-only.

Method NOT is Lo Instance Safe. Use Class LoContext when using with multiple document instances.

Parameters:
  • fnm (PathOrStr) – path of document to open.

  • loader (XComponentLoader) – Component Loader.

Raises:

Exception – if unable to open document.

Returns:

Document.

Return type:

XComponent

Attention

open_doc() method is called along with any of its events.

static parse_int(s)[source]

Converts string into int.

Method is Lo Instance Safe for use with multiple documents.

Parameters:

s (str) – string to parse

Returns:

String as int. If unable to convert s to int then 0 is returned.

Return type:

int

classmethod print(*args, **kwargs)[source]

Utility function that passes to actual print.

Method is Lo Instance Safe for use with multiple documents.

If GblNamedEvent.PRINTING event is canceled the this method will not print.

Events:

GblNamedEvent.PRINTING Standard Cancel Event

Return type:

None

Note

When global GblNamedEvent.PRINTING event is canceled it will silently exits method. See CancelEventArgs

Return type:

None

classmethod print_names(names)[source]
classmethod print_names(names, num_per_line)
classmethod print_names(names, num_per_line=4)

Prints names to console.

Method is Lo Instance Safe for use with multiple documents.

Parameters:
  • names (Iterable[str]) – names to print

  • num_per_line (int) – Number of names per line. Default 4

  • format_opt (FormatterTable, optional) – Optional format used to format values when printing to console such as FormatterTable(format=">2")

Return type:

None

Example

Given a list of 20 names the output is similar to:

No. of names: 20
  ----------|-----------|-----------|-----------
  Accent    | Accent 1  | Accent 2  | Accent 3
  Bad       | Default   | Error     | Footnote
  Good      | Heading   | Heading 1 | Heading 2
  Hyperlink | Neutral   | Note      | Result
  Result2   | Status    | Text      | Warning
classmethod print_table(name: str, table: Any) None[source]
classmethod print_table(name: str, table: Any, format_opt: ooodev.formatters.formatter_table.FormatterTable) None
classmethod print_table(name, table, format_opt=None)

Prints a 2-Dimensional table to console.

Method is Lo Instance Safe for use with multiple documents.

Parameters:
  • name (str) – Name of table

  • table (Table) – Table Data

  • format_opt (FormatterTable, optional) – Optional format used to format values when printing to console such as FormatterTable(format=".2f")

Return type:

None

Changed in version 0.6.7: Added format_opt parameter

classmethod qi(atype: Type[ooodev.utils.type_var.T], obj: Any) T | None[source]
classmethod qi(atype: Type[ooodev.utils.type_var.T], obj: Any, raise_err: Literal[True]) ooodev.utils.type_var.T
classmethod qi(atype: Type[ooodev.utils.type_var.T], obj: Any, raise_err: Literal[False]) T | None
classmethod qi(atype, obj, raise_err=False)

Generic method that get an interface instance from an object.

Method is Lo Instance Safe for use with multiple documents.

Parameters:
  • atype (T) – Interface type to query obj for. Any Uno class that starts with ‘X’ such as XInterface

  • obj (object) – Object that implements interface.

  • raise_err (bool, optional) – If True then raises MissingInterfaceError if result is None. Default False

Raises:

MissingInterfaceError – If ‘raise_err’ is ‘True’ and result is None

Returns:

instance of interface if supported; Otherwise, None

Return type:

T | None

Note

When raise_err=True return value will never be None.

Example

from com.sun.star.util import XSearchable
cell_range = ...
search = Lo.qi(XSearchable, cell_range)
sd = search.createSearchDescriptor()
classmethod save(doc)[source]

Save as document.

Method is Lo Instance Safe for use with multiple documents.

Parameters:

doc (object) – Office document.

Raises:
  • Exception – If unable to save document

  • MissingInterfaceError – If doc does not implement XStorable interface

Returns:

False if DOC_SAVING event is canceled; Otherwise, True

Return type:

bool

Events:

Note

Event args event_data is a dictionary containing doc.

classmethod save_doc(doc: object, fnm: Any) bool[source]
classmethod save_doc(doc: object, fnm: Any, password: str) bool
classmethod save_doc(doc: object, fnm: Any, password: str, format: str) bool
classmethod save_doc(doc, fnm, password=None, format=None)

Save document.

Method is Lo Instance Safe for use with multiple documents.

Parameters:
  • doc (object) – Office document.

  • fnm (PathOrStr) – file path to save as.

  • password (str, optional) – password to save document with.

  • format (str, optional) – document format such as ‘odt’ or ‘xml’.

Raises:

MissingInterfaceError – If doc does not implement XStorable interface.

Returns:

False if DOC_SAVING event is canceled; Otherwise, True

Return type:

bool

Events:

Note

Event args event_data is a dictionary containing all method parameters.

Attention

store_doc() method is called along with any of its events.

classmethod script_initialize(sc)[source]

Initialize script.

Method NOT is Lo Instance Safe. Use Class LoContext when using with multiple document instances.

Parameters:

sc (XScriptContext) – Script context

Raises:
  • TypeError – If sc is None

  • Exception – if unable to get Component Context from sc

  • Exception – If unable to get service manager

  • Exception – If unable to access desktop

  • Exception – If unable to access document

  • MissingInterfaceError – if unable to get XMultiServiceFactory interface instance

Returns:

script component

Return type:

XComponent

Events:

Note

Event args event_data is a dictionary containing all method parameters.

classmethod store_doc(store, doc_type: DocType, fnm)[source]
classmethod store_doc(store, doc_type: DocType, fnm, password: str)
classmethod store_doc(store, doc_type, fnm, password=None)

Stores/Saves a document.

Method is Lo Instance Safe for use with multiple documents.

Parameters:
  • store (XStorable) – instance that implements XStorable interface.

  • doc_type (DocType) – Document type

  • fnm (PathOrStr) – Path to save document as. If extension is absent then text .txt is assumed.

  • password (str) – Password for document.

Returns:

True if document is saved; Otherwise False

Return type:

bool

Events:

Note

Event args event_data is a dictionary containing all method parameters.

classmethod store_doc_format(store: com.sun.star.frame.XStorable, fnm: Any, format: str) bool[source]
classmethod store_doc_format(store: com.sun.star.frame.XStorable, fnm: Any, format: str, password: str) bool
classmethod store_doc_format(store, fnm, format, password=None)

Store document as format.

Method is Lo Instance Safe for use with multiple documents.

Parameters:
  • store (XStorable) – instance that implements XStorable interface.

  • fnm (PathOrStr) – Path to save document as.

  • format (str) – document format such as ‘odt’ or ‘xml’

  • password (str) – Password for document.

Raises:

Exception – If unable to save document

Returns:

True if document is stored; Otherwise False

Return type:

bool

Events:

Note

Event args event_data is a dictionary containing all method parameters.

See also

store_doc()

classmethod unlock_controllers()[source]

Resumes the notifications which were suspended by lock_controllers().

The calls to lock_controllers() and unlock_controllers() may be nested and even overlapping, but they must be in pairs. While there is at least one lock remaining, some notifications for display updates are not broadcast.

Method NOT is Lo Instance Safe. Use Class LoContext when using with multiple document instances.

Raises:

MissingInterfaceError – If unable to obtain XModel interface.

Returns:

False if CONTROLLERS_UNLOCKING event is canceled; Otherwise, True

Return type:

bool

Events:
static wait(ms)

Delay execution for a given number of milliseconds.

Method is Lo Instance Safe for use with multiple documents.

Parameters:

ms (int) – Number of milliseconds to delay

Return type:

None

static wait_enter()[source]

Console displays Press Enter to continue…

Method is Lo Instance Safe for use with multiple documents.

Return type:

None