### Dispatching Commands Example Source: https://github.com/amourspirit/python_ooo_dev_tools/blob/main/docs/odev/part1/chapter04.rst This example demonstrates how to use the Lo.dispatch_cmd method to send commands to LibreOffice, such as opening a document, setting it to read-only, and opening the 'Get Involved' webpage. It includes argument parsing for specifying the document path and loading the LibreOffice instance. ```python #!/usr/bin/env python # coding: utf-8 # region Imports from __future__ import annotations import argparse import sys from ooodev.loader.lo import Lo from ooodev.gui import GUI # endregion Imports # region args def args_add(parser: argparse.ArgumentParser) -> None: parser.add_argument( "-d", "--doc", help="Path to document", action="store", dest="fnm_doc", required=True, ) # endregion args # region Main def main() -> int: # create parser to read terminal input parser = argparse.ArgumentParser(description="main") # add args to parser args_add(parser=parser) if len(sys.argv) <= 1: parser.print_help(sys.stderr) return 1 # read the current command line args args = parser.parse_args() fnm = args.fnm_doc loader = Lo.load_office(Lo.ConnectPipe()) try: doc = Lo.open_doc(fnm=fnm, loader=loader) # breakpoint() except Exception: print(f"Could not open '{fnm}'") Lo.close_office() raise SystemExit(1) GUI.set_visible(is_visible=True, odoc=doc) Lo.delay(3000) # delay 3 seconds # put doc into readonly mode Lo.dispatch_cmd("ReadOnlyDoc") Lo.delay(1000) # opens get involved webpage of LibreOffice in local browser Lo.dispatch_cmd("GetInvolved") return 0 if __name__ == "__main__": raise SystemExit(main()) # endregion main ``` -------------------------------- ### Impress Get Info Output Example Source: https://github.com/amourspirit/python_ooo_dev_tools/blob/main/tests/samples/Impress/Slides_Info/README.md Example output from the Impress Get Info script, showing the loading process, document details (slide count, size), layer properties, and style family information. ```txt Loading Office... Opening /home/user/LibreOffice/ooouno-dev-tools/tests/fixtures/presentation/algs.odp No. of slides: 12 Size of slide (mm)(254, 190) Layer 0 Properties Description: IsLocked: False IsPrintable: True IsVisible: True Name: layout Title: Layer 1 Properties Description: IsLocked: False IsPrintable: True IsVisible: True Name: background Title: Layer 2 Properties Description: IsLocked: False IsPrintable: True IsVisible: True Name: backgroundobjects Title: Layer 3 Properties Description: IsLocked: False IsPrintable: True IsVisible: True Name: controls Title: Layer 4 Properties Description: IsLocked: False IsPrintable: True IsVisible: True Name: measurelines Title: Background Object Props Properties Description: IsLocked: False IsPrintable: True IsVisible: True Name: backgroundobjects Title: Style Families in this document: No. of names: 4 'cell' 'Default' 'graphics' 'table' Styles in the "Default" style family: No. of names: 14 'background' 'backgroundobjects' 'notes' 'outline1' 'outline2' 'outline3' 'outline4' 'outline5' 'outline6' 'outline7' 'outline8' 'outline9' 'subtitle' 'title' Styles in the "cell" style family: No. of names: 34 'blue1' 'blue2' 'blue3' 'bw1' 'bw2' 'bw3' 'default' 'earth1' 'earth2' 'earth3' 'gray1' 'gray2' 'gray3' 'green1' 'green2' 'green3' 'lightblue1' 'lightblue2' 'lightblue3' 'orange1' 'orange2' 'orange3' 'seetang1' 'seetang2' 'seetang3' 'sun1' 'sun2' 'sun3' 'turquoise1' 'turquoise2' 'turquoise3' 'yellow1' 'yellow2' 'yellow3' Styles in the "graphics" style family: No. of names: 40 'A4' 'A4' 'Arrow Dashed' 'Arrow Line' 'Filled' 'Filled Blue' 'Filled Green' 'Filled Red' 'Filled Yellow' 'Graphic' 'Heading A0' 'Heading A4' 'headline' 'headline1' 'headline2' 'Lines' 'measure' 'Object with no fill and no line' 'objectwitharrow' 'objectwithoutfill' 'objectwithshadow' 'Outlined' 'Outlined Blue' 'Outlined Green' 'Outlined Red' 'Outlined Yellow' 'Shapes' 'standard' 'Text' 'text' 'Text A0' 'Text A4' 'textbody' 'textbodyindent' 'textbodyjustfied' 'title' 'Title A0' 'Title A4' 'title1' 'title2' Styles in the "table" style family: No. of names: 11 'blue' 'bw' 'default' 'earth' 'green' 'lightblue' 'orange' 'seetang' 'sun' 'turquoise' 'yellow' Closing the document Closing Office Office terminated Office bridge has gone!! ``` -------------------------------- ### Install Dependencies with Poetry (Windows) Source: https://github.com/amourspirit/python_ooo_dev_tools/blob/main/docs/dev_docs/dev_notes.rst Installs project dependencies using Poetry after activating the virtual environment on Windows. Assumes Poetry is installed. ```powershell (.venv) PS C:\python_ooo_dev_tools> poetry install ``` -------------------------------- ### Installation Guide for LibreOffice Extension Source: https://github.com/amourspirit/python_ooo_dev_tools/blob/main/docs/version/version_hist.rst A guide has been added detailing how to install OooDev as a LibreOffice Extension. This provides an alternative installation method for users who prefer managing extensions within LibreOffice. ```markdown See the guide for installing OooDev as a LibreOffice `Extension `__. ``` -------------------------------- ### Poetry Project Initialization Output Source: https://github.com/amourspirit/python_ooo_dev_tools/blob/main/docs/guide/virtual_env/windows_poetry_env.rst Example output from the `poetry init` command, showing the interactive prompts for project details such as name, version, description, author, license, and compatible Python versions. ```text This command will guide you through creating your pyproject.toml config. Package name [project]: Version [0.1.0]: Description []: My fantastic project Author [Secret Name , n to skip]: License []: MIT Compatible Python versions [^3.9]: ^3.8 Would you like to define your main dependencies interactively? (yes/no) [yes] n Would you like to define your development dependencies interactively? (yes/no) [yes] n ``` -------------------------------- ### Python Solver Setup and Execution Source: https://github.com/amourspirit/python_ooo_dev_tools/blob/main/docs/odev/part4/chapter27.rst Demonstrates setting up a solver with objectives, variables, and constraints, then executing it. It also shows how to configure solver properties and report results. ```python solver.Document = doc.component solver.Objective = objective solver.Variables = vars solver.Constraints = constraints solver.Maximize = True # restrict the search to the top-right quadrant of the graph Props.show_obj_props("Solver", solver) # switch off nonlinear dialog about current progress Props.set(solver, EnhancedSolverStatus=False) # execute the solver solver.solve() # Profit max == 10; vars are very close to 6, 8, and 4, but off by 6-7 dps Calc.solver_report(solver) doc.close_doc() ``` -------------------------------- ### Running the Binder Example Source: https://github.com/amourspirit/python_ooo_dev_tools/blob/main/docs/odev/part3/chapter15.rst Command-line arguments to run the binder example, demonstrating the binding functionality. ```bash python -m start -k bind ``` -------------------------------- ### Package Installation Output Source: https://github.com/amourspirit/python_ooo_dev_tools/blob/main/docs/guide/virtual_env/linux_flatpak_lo_pip.rst Example output from the pip installation process, showing the collection and successful installation of ooo-dev-tools and its related packages. ```text Collecting ooo-dev-tools Using cached ooo_dev_tools-0.11.8-py3-none-any.whl (2.2 MB) Collecting ooouno>=2.1.2 Using cached ooouno-2.1.2-py3-none-any.whl (9.8 MB) Collecting lxml>=4.9.2 Using cached lxml-4.9.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_24_x86_64.whl (7.1 MB) Collecting typing-extensions<5.0.0,>=4.6.2 Using cached typing_extensions-4.6.3-py3-none-any.whl (31 kB) Collecting types-unopy>=1.2.3 Using cached types_unopy-1.2.3-py3-none-any.whl (5.2 MB) Collecting types-uno-script>=0.1.1 Using cached types_uno_script-0.1.1-py3-none-any.whl (9.3 kB) Installing collected packages: typing-extensions, types-uno-script, lxml, types-unopy, ooouno, ooo-dev-tools Successfully installed lxml-4.9.2 ooo-dev-tools-0.11.8 ooouno-2.1.2 types-uno-script-0.1.1 types-unopy-1.2.3 typing-extensions-4.6.3 ``` -------------------------------- ### Setup and Chart Formatting Example Source: https://github.com/amourspirit/python_ooo_dev_tools/blob/main/docs/help/chart2/format/direct_static/wall_floor/area.rst Demonstrates the general setup for chart formatting examples, including opening a document, accessing a chart, styling its background with a line border, and applying a wall color. This serves as a foundational example for subsequent formatting operations. ```python import uno from ooodev.format.chart2.direct.wall.area import Color as WallColor from ooodev.format.chart2.direct.general.borders import LineProperties as ChartLineProperties from ooodev.office.calc import Calc from ooodev.office.chart2 import Chart2 from ooodev.utils.color import StandardColor from ooodev.gui import GUI from ooodev.loader.lo import Lo def main() -> int: with Lo.Loader(connector=Lo.ConnectPipe()): doc = Calc.open_doc("col_chart3d.ods") GUI.set_visible(True, doc) Lo.delay(500) Calc.zoom(doc, GUI.ZoomEnum.ZOOM_100_PERCENT) sheet = Calc.get_active_sheet() Calc.goto_cell(cell_name="A1", doc=doc) chart_doc = Chart2.get_chart_doc(sheet=sheet, chart_name="col_chart") chart_bdr_line = ChartLineProperties(color=StandardColor.BLUE_DARK1, width=1.0) Chart2.style_background(chart_doc=chart_doc, styles=[chart_bdr_line]) wall_color = WallColor(color=StandardColor.DEFAULT_BLUE) Chart2.style_wall(chart_doc=chart_doc, styles=[wall_color]) Lo.delay(1_000) Lo.close_doc(doc) return 0 if __name__ == "__main__": SystemExit(main()) ``` -------------------------------- ### LoPipeStart Connection Example Source: https://github.com/amourspirit/python_ooo_dev_tools/blob/main/docs/src/conn/connect/lo_pipe_start.rst Demonstrates how to instantiate and use the LoPipeStart class to connect to LibreOffice via a pipe, obtain the service manager and desktop instance, and then terminate the LibreOffice process. ```python from ooodev.conn.connect import LoPipeStart from ooodev.conn.connectors import ConnectPipe conn = LoPipeStart(ConnectPipe()) conn.connect() # may take a few seconds smgr = conn.ctx.getServiceManager() desktop = smgr.createInstanceWithContext("com.sun.star.frame.Desktop", conn.ctx) # do some work ... conn.kill_soffice() ``` -------------------------------- ### Lo.load_office Method Implementation (Simplified) Source: https://github.com/amourspirit/python_ooo_dev_tools/blob/main/docs/odev/part1/chapter02.rst Provides a simplified, internal view of the Lo.load_office class method, illustrating the logic for handling different connector types (direct start, pipes, sockets) and initializing the Office context, service manager, and component loader. ```python # in Lo class (simplified) @classmethod def load_office( cls, connector: ConnectPipe | ConnectSocket | None = None, cache_obj: Cache | None = None ) -> XComponentLoader: Lo.print("Loading Office...") if connector is None: try: cls._lo_inst = LoDirectStart() cls._lo_inst.connect() except Exception as e: Lo.print(( "Office context could not be created." " A connector must be supplied if not running as a macro" )) Lo.print(f" {e}") raise SystemExit(1) elif isinstance(connector, ConnectPipe): try: cls._lo_inst = LoPipeStart(connector=connector, cache_obj=cache_obj) cls._lo_inst.connect() except Exception as e: Lo.print("Office context could not be created") Lo.print(f" {e}") raise SystemExit(1) elif isinstance(connector, ConnectSocket): try: cls._lo_inst = LoSocketStart(connector=connector, cache_obj=cache_obj) cls._lo_inst.connect() except Exception as e: Lo.print("Office context could not be created") Lo.print(f" {e}") raise SystemExit(1) else: Lo.print("Invalid Connector type. Fatal Error.") raise SystemExit(1) cls._xcc = cls._lo_inst.ctx cls._mc_factory = cls._xcc.getServiceManager() if cls._mc_factory is None: Lo.print("Office Service Manager is unavailable") raise SystemExit(1) ``` -------------------------------- ### Install Dependencies with Poetry (Linux) Source: https://github.com/amourspirit/python_ooo_dev_tools/blob/main/docs/dev_docs/dev_notes.rst Installs project dependencies using Poetry after activating the virtual environment on Linux. Assumes Poetry is installed. ```shell (.venv) $ poetry install ``` -------------------------------- ### Lo Connect Pipe Example Reference Source: https://github.com/amourspirit/python_ooo_dev_tools/blob/main/docs/src/conn/connect/lo_pipe_start.rst Includes an external reStructuredText file containing an example of establishing a LibreOffice connection using a pipe. ```rst .. include:: ../../../resources/utils/lo_connect_pipe_ex.rst ``` -------------------------------- ### Full Example: Chart Font Effects Setup Source: https://github.com/amourspirit/python_ooo_dev_tools/blob/main/docs/help/chart2/format/direct/axis/font_effects.rst A comprehensive example demonstrating the setup and application of font effects to chart axes. It includes opening a document, accessing chart elements, and applying various formatting options including border, area gradient, and axis font effects. ```python from __future__ import annotations from pathlib import Path import uno from ooo.dyn.awt.gradient_style import GradientStyle from ooo.dyn.awt.font_underline import FontUnderlineEnum from ooodev.calc import CalcDoc, ZoomKind from ooodev.utils.color import StandardColor from ooodev.loader.lo import Lo from ooodev.utils.data_type.color_range import ColorRange from ooodev.utils.data_type.offset import Offset from ooodev.format.inner.direct.write.char.font.font_effects import FontLine def main() -> int: with Lo.Loader(connector=Lo.ConnectPipe()): fnm = Path.cwd() / "tmp" / "bon_voyage.ods" doc = CalcDoc.open_doc(fnm=fnm, visible=True) Lo.delay(500) doc.zoom(ZoomKind.ZOOM_100_PERCENT) sheet = doc.sheets[0] sheet["A1"].goto() chart_table = sheet.charts[0] chart_doc = chart_table.chart_doc _ = chart_doc.style_border_line( color=StandardColor.GREEN_DARK2, width=0.9 ) _ = chart_doc.style_area_gradient( step_count=0, offset=Offset(41, 50), style=GradientStyle.RADIAL, grad_color=ColorRange( StandardColor.TEAL, StandardColor.YELLOW_DARK1 ), ) _ = chart_doc.axis_y.style_font_effect( color=StandardColor.RED, underline=FontLine( line=FontUnderlineEnum.SINGLE, color=StandardColor.BLUE ), shadowed=True, ) Lo.delay(1_000) doc.close() return 0 if __name__ == "__main__": SystemExit(main()) ``` -------------------------------- ### Activate Virtual Environment and Import Uno Source: https://github.com/amourspirit/python_ooo_dev_tools/blob/main/docs/dev_docs/dev_notes.rst Demonstrates how to activate the Python virtual environment and import the 'uno' library to test the environment setup. ```shell PS C:\python_ooo_dev_tools> .\.venv\scripts\activate (.venv) PS C:\python_ooo_dev_tools> python Python 3.8.10 (default, Mar 23 2022, 15:43:48) [MSC v.1928 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import uno >>> ``` -------------------------------- ### Get LibreOffice Python Executable Path Source: https://github.com/amourspirit/python_ooo_dev_tools/blob/main/docs/guide/virtual_env/linux_lo_install_pip.rst Demonstrates how to find the Python executable path used by LibreOffice via the APSO extension. This is crucial for ensuring compatibility when installing packages. ```python >>> import sys >>> sys.executable '/usr/bin/python3' ``` -------------------------------- ### Example Usage with Version Changed (RST) Source: https://github.com/amourspirit/python_ooo_dev_tools/blob/main/docs/style_guide.md Provides a comprehensive example of documenting a function's usage, including arguments, return values, see also references, and a version changed note. ```rst Prints a 2-Dimensional table to console Args: name (str): Name of table table (Table): Table Data format_opt (FormatterTable, optional): Format when printing to console Returns: None: See Also: - :ref:`ch21_format_data_console` - :py:data:`~.type_var.Table` .. versionchanged:: 0.12.4 Added ``format_opt`` parameter ``` -------------------------------- ### Build Documentation (Linux) Source: https://github.com/amourspirit/python_ooo_dev_tools/blob/main/docs/dev_docs/dev_notes.rst Command to build HTML documentation using Sphinx on Linux after activating the virtual environment and navigating to the docs directory. ```text (.venv) $ make html ``` -------------------------------- ### Build Documentation (Windows) Source: https://github.com/amourspirit/python_ooo_dev_tools/blob/main/docs/dev_docs/dev_notes.rst Command to build HTML documentation using Sphinx on Windows after activating the virtual environment and navigating to the docs directory. ```text PS C:\python_ooo_dev_tools\docs> make html ``` -------------------------------- ### Installed Extensions Output Source: https://github.com/amourspirit/python_ooo_dev_tools/blob/main/docs/odev/part2/chapter10.rst Example output listing various installed extensions in LibreOffice, such as script organizers, dictionaries, grammar checkers, and other language tools, along with their version numbers and file paths. ```text Extensions: 1. ID: apso.python.script.organizer Version: 1.3.0 Loc: file:///C:/Users/bigby/AppData/Roaming/LibreOffice/4/user/uno_packages/cache/uno_packages/lu1271241oyk.tmp_/apso.oxt 2. ID: org.openoffice.en.hunspell.dictionaries Version: 2021.11.01 Loc: file:///C:/Program%20Files/LibreOffice/program/../share/extensions/dict-en 3. ID: French.linguistic.resources.from.Dicollecte.by.OlivierR Version: 7.0 Loc: file:///C:/Program%20Files/LibreOffice/program/../share/extensions/dict-fr 4. ID: org.openoffice.languagetool.oxt Version: 5.8 Loc: file:///C:/Users/bigby/AppData/Roaming/LibreOffice/4/user/uno_packages/cache/uno_packages/lu107803j3h0.tmp_/LanguageTool-stable.oxt 5. ID: com.sun.star.comp.Calc.NLPSolver Version: 0.9 Loc: file:///C:/Program%20Files/LibreOffice/program/../share/extensions/nlpsolver 6. ID: spanish.es.dicts.from.rla-es Version: __VERSION__ Loc: file:///C:/Program%20Files/LibreOffice/program/../share/extensions/dict-es 7. ID: com.sun.wiki-publisher Version: 1.2.0 Loc: file:///C:/Program%20Files/LibreOffice/program/../share/extensions/wiki-publisher ``` -------------------------------- ### Setup and Chart Formatting Example Source: https://github.com/amourspirit/python_ooo_dev_tools/blob/main/docs/help/chart2/format/direct_static/title/area.rst Demonstrates the general setup for chart formatting, including applying background colors and gradients to a chart. It utilizes various classes from the ooodev library to achieve this. ```python import uno from ooodev.format.chart2.direct.title.area import Color as TitleBgColor from ooodev.format.chart2.direct.general.borders import LineProperties as ChartLineProperties from ooodev.format.chart2.direct.general.area import Gradient as ChartGradient from ooodev.format.chart2.direct.general.area import GradientStyle, ColorRange from ooodev.office.calc import Calc from ooodev.office.chart2 import Chart2 from ooodev.utils.color import StandardColor from ooodev.gui import GUI from ooodev.loader.lo import Lo def main() -> int: with Lo.Loader(connector=Lo.ConnectPipe()): doc = Calc.open_doc("pie_flat_chart.ods") GUI.set_visible(True, doc) Lo.delay(500) Calc.zoom(doc, GUI.ZoomEnum.ZOOM_100_PERCENT) sheet = Calc.get_active_sheet() Calc.goto_cell(cell_name="A1", doc=doc) chart_doc = Chart2.get_chart_doc(sheet=sheet, chart_name="pie_chart") chart_bdr_line = ChartLineProperties(color=StandardColor.PURPLE_DARK1, width=0.7) chart_grad = ChartGradient( chart_doc=chart_doc, step_count=64, style=GradientStyle.SQUARE, angle=45, grad_color=ColorRange(StandardColor.BLUE_DARK1, StandardColor.PURPLE_LIGHT2), ) Chart2.style_background(chart_doc=chart_doc, styles=[chart_grad, chart_bdr_line]) title_color = TitleBgColor(color=StandardColor.DEFAULT_BLUE) Chart2.style_title(chart_doc=chart_doc, styles=[title_color]) Lo.delay(1_000) Lo.close_doc(doc) return 0 if __name__ == "__main__": SystemExit(main()) ``` -------------------------------- ### Display Help for Draw Gradient Example Source: https://github.com/amourspirit/python_ooo_dev_tools/blob/main/tests/samples/Draw/gradient/README.md Shows how to display the command-line help for the Draw gradient example script across different operating systems. ```sh python -m start -h ``` ```sh python ./tests/samples/Draw/gradient/start.py -h ``` ```ps python .\tests\samples\Draw\gradient\start.py -h ``` -------------------------------- ### Full Example: Create and Style Chart Source: https://github.com/amourspirit/python_ooo_dev_tools/blob/main/docs/help/chart2/format/direct/title/alignment.rst A comprehensive example demonstrating the setup of a Calc document, creation of a pie chart, styling its border and area, and then applying custom alignment and write mode to its title. ```python from __future__ import annotations from pathlib import Path import uno from ooo.dyn.awt.gradient_style import GradientStyle from ooodev.calc import CalcDoc, ZoomKind from ooodev.loader.lo import Lo from ooodev.utils.color import StandardColor from ooodev.utils.data_type.color_range import ColorRange from ooodev.format.chart2.direct.title.alignment import DirectionModeKind def main() -> int: with Lo.Loader(connector=Lo.ConnectPipe()): fnm = Path.cwd() / "tmp" / "piechart.ods" doc = CalcDoc.open_doc(fnm=fnm, visible=True) Lo.delay(500) doc.zoom(ZoomKind.ZOOM_100_PERCENT) sheet = doc.sheets[0] sheet["A1"].goto() chart_table = sheet.charts[0] chart_doc = chart_table.chart_doc _ = chart_doc.style_border_line( color=StandardColor.PURPLE_DARK1, width=0.7, ) _ = chart_doc.style_area_gradient( step_count=64, style=GradientStyle.SQUARE, angle=45, grad_color=ColorRange( StandardColor.BLUE_DARK1, StandardColor.PURPLE_LIGHT2, ), ) title = chart_doc.get_title() if title is None: raise ValueError("Title not found") title.style_orientation(angle=15, vertical=False) title.style_write_mode(mode=DirectionModeKind.LR_TB) Lo.delay(1_000) doc.close() return 0 if __name__ == "__main__": SystemExit(main()) ``` -------------------------------- ### Load Office with Clean Profile Source: https://github.com/amourspirit/python_ooo_dev_tools/blob/main/docs/odev/part1/chapter02.rst Demonstrates how to load LibreOffice using a context manager with a clean profile directory by setting profile_path to an empty string. This is useful for ensuring a fresh environment for each session. ```python from ooodev.loader.lo import Lo from ooodev.conn.cache import Cache def main(): with Lo.Loader( Lo.ConnectSocket(headless=True), cache_obj=Cache(profile_path=""), ) as loader: # do work and then loader will be closed automatically. pass if __name__ == "__main__": main() ``` -------------------------------- ### Get Python Version from LibreOffice Flatpak Source: https://github.com/amourspirit/python_ooo_dev_tools/blob/main/docs/guide/virtual_env/linux_flatpak_lo_pip.rst This snippet shows how to access the Python console within the LibreOffice Flatpak to determine the installed Python version, which is crucial for creating a compatible virtual environment. ```python APSO python console [LibreOffice] 3.10.11 (main, Nov 10 2011, 15:00:00) [GCC 12.2.0] Type "help", "copyright", "credits" or "license" for more information. >>> ``` -------------------------------- ### Run Impress Copy Slide Script (Cross Platform) Source: https://github.com/amourspirit/python_ooo_dev_tools/blob/main/tests/samples/Impress/Copy_Slide/README.md Executes the Impress copy slide script from the current example folder using the module entry point. ```sh python -m start ``` -------------------------------- ### LoSocketStart Class Initialization and Connection Source: https://github.com/amourspirit/python_ooo_dev_tools/blob/main/docs/src/conn/connect/lo_socket_start.rst Demonstrates how to initialize the LoSocketStart class with a socket connector and establish a connection to LibreOffice. It also shows how to retrieve the Service Manager and Desktop instance. ```python from ooodev.conn.connect import LoSocketStart from ooodev.conn.connectors import ConnectSocket # Initialize LoSocketStart with a socket connector conn = LoSocketStart(ConnectSocket()) # Establish the connection to LibreOffice conn.connect() # may take a few seconds # Get the Service Manager from the connection context smgr = conn.ctx.getServiceManager() # Create an instance of the Desktop service desktop = smgr.createInstanceWithContext("com.sun.star.frame.Desktop", conn.ctx) # Perform operations with LibreOffice... # Terminate the LibreOffice instance conn.kill_soffice() ``` -------------------------------- ### Get Paragraph Font from Style Source: https://github.com/amourspirit/python_ooo_dev_tools/blob/main/docs/help/writer/format/modify/para/font_only.rst Retrieves the font style properties from an existing paragraph style in a LibreOffice Writer document. This example shows how to get the font details of the 'Standard' paragraph style. ```python # ... other code f_style = FontOnly.from_style( doc=doc.component, style_name=StyleParaKind.STANDARD ) assert f_style.prop_style_name == str(StyleParaKind.STANDARD) ``` -------------------------------- ### Example Output for Office and OS Information Source: https://github.com/amourspirit/python_ooo_dev_tools/blob/main/docs/odev/part1/chapter03.rst This is sample output demonstrating the information that can be retrieved about the operating system and the Office application using the provided Python script. ```text OS Platform: Linux-5.15.0-41-generic-x86_64-with-debian-bookworm-sid OS Version: #44-Ubuntu SMP Wed Jun 22 14:20:53 UTC 2022 OS Release: 5.15.0-41-generic OS Architecture: ('64bit', 'ELF') Office Name: LibreOffice Office version (long): 7.3.4.2 Office version (short): 7.3 Office language location: en-US System language location: Working Dir: file:///home/user/Documents Office Dir: /usr/lib/libreoffice Addin Dir: file:///usr/lib/libreoffice/program/addin Filters Dir: file:///usr/lib/libreoffice/program/filter ... ``` -------------------------------- ### Setup and Orientation Example Source: https://github.com/amourspirit/python_ooo_dev_tools/blob/main/docs/help/chart2/format/direct_static/series/data_series/options.rst Demonstrates the setup for chart formatting and applies orientation options to a chart. It imports necessary classes from ooodev and configures a pie chart with clockwise orientation and a 45-degree angle. ```python import uno from ooodev.format.chart2.direct.series.data_series.options import Orientation from ooodev.utils.data_type.angle import Angle from ooodev.format.chart2.direct.general.borders import LineProperties as ChartLineProperties from ooodev.format.chart2.direct.general.area import Gradient as ChartGradient, PresetGradientKind from ooodev.office.calc import Calc from ooodev.office.chart2 import Chart2 from ooodev.utils.color import StandardColor from ooodev.gui import GUI from ooodev.loader.lo import Lo def main() -> int: with Lo.Loader(connector=Lo.ConnectPipe()): doc = Calc.open_doc("pie_chart.ods") GUI.set_visible(True, doc) Lo.delay(500) Calc.zoom(doc, GUI.ZoomEnum.ZOOM_100_PERCENT) sheet = Calc.get_active_sheet() Calc.goto_cell(cell_name="A1", doc=doc) chart_doc = Chart2.get_chart_doc(sheet=sheet, chart_name="pie_chart") chart_bdr_line = ChartLineProperties(color=StandardColor.BLUE_LIGHT3, width=0.7) chart_grad = ChartGradient.from_preset(chart_doc, PresetGradientKind.TEAL_BLUE) Chart2.style_background(chart_doc=chart_doc, styles=[chart_grad, chart_bdr_line]) orient = Orientation(chart_doc=chart_doc, clockwise=True, angle=Angle(45)) Chart2.style_data_series(chart_doc=chart_doc, styles=[orient]) Lo.delay(1_000) Lo.close_doc(doc) return 0 if __name__ == "__main__": SystemExit(main()) ``` -------------------------------- ### LibreOffice Automation Example Source: https://github.com/amourspirit/python_ooo_dev_tools/blob/main/docs/resources/utils/lo_connect_pipe_ex.rst Demonstrates the basic workflow for loading LibreOffice, creating a new Calc document, performing operations, and then closing the document and the office instance. ```python from ooodev.loader.lo import Lo from ooodev.office.calc import Calc loader = Lo.load_office(connector=Lo.ConnectPipe()) doc = Calc.create_doc(loader) # do work ... Lo.close_doc(doc=doc) Lo.close_office() ``` -------------------------------- ### Setup and Apply Cell Alignment Properties Source: https://github.com/amourspirit/python_ooo_dev_tools/blob/main/docs/help/calc/format/direct_static/cell/alignment.rst Demonstrates the setup for LibreOffice Calc examples and applies text properties like auto-wrap and text direction to a specific cell. It also shows how to retrieve these properties from the cell. ```python import uno from ooodev.office.calc import Calc from ooodev.gui.gui import GUI from ooodev.loader.lo import Lo from ooodev.format.calc.direct.cell.alignment import Properties, TextDirectionKind def main() -> int: with Lo.Loader(connector=Lo.ConnectSocket()): doc = Calc.create_doc() sheet = Calc.get_sheet() GUI.set_visible(True, doc) Lo.delay(500) Calc.zoom_value(doc, 400) cell = Calc.get_cell(sheet=sheet, cell_name="A1") style = Properties(wrap_auto=True, hyphen_active=True, direction=TextDirectionKind.PAGE) Calc.set_val(value="Hello World! Sunny Day!", cell=cell, styles=[style]) f_style = Properties.from_obj(cell) assert f_style is not None Lo.delay(1_000) Lo.close_doc(doc) return 0 if __name__ == "__main__": SystemExit(main()) ``` -------------------------------- ### Start Slide Show (Python) Source: https://github.com/amourspirit/python_ooo_dev_tools/blob/main/docs/odev/part3/chapter11.rst Demonstrates how to start a slide show for a given document using Python. It involves loading the office, opening a document, and accessing presentation-related interfaces. ```python from ooodev.loader.lo import Lo loader = Lo.load_office(Lo.ConnectPipe()) doc = Lo.open_doc("foo", loader) ps = Lo.qi(XPresentationSupplier, doc) Lo.qi(XPresentation, ps.getPresentation()) show.start() ``` -------------------------------- ### Setup and Style Chart Area Gradient Source: https://github.com/amourspirit/python_ooo_dev_tools/blob/main/docs/help/chart2/format/direct/series/data_series/transparency.rst Sets up a Calc document, styles the chart border and area gradient, and then sets the transparency for the data series. This example demonstrates the initial setup and application of gradient transparency. ```python from __future__ import annotations from pathlib import Path import uno from ooodev.calc import CalcDoc, ZoomKind from ooodev.loader.lo import Lo from ooodev.utils.color import StandardColor from ooodev.format.inner.preset.preset_gradient import PresetGradientKind def main() -> int: with Lo.Loader(connector=Lo.ConnectPipe()): fnm = Path.cwd() / "tmp" / "col_chart.ods" doc = CalcDoc.open_doc(fnm=fnm, visible=True) Lo.delay(500) doc.zoom(ZoomKind.ZOOM_100_PERCENT) sheet = doc.sheets[0] sheet["A1"].goto() chart_table = sheet.charts[0] chart_doc = chart_table.chart_doc _ = chart_doc.style_border_line( color=StandardColor.BLUE_LIGHT3, width=0.7, ) _ = chart_doc.style_area_gradient_from_preset( preset=PresetGradientKind.TEAL_BLUE, ) ds = chart_doc.get_data_series()[0] ds.style_area_transparency_transparency(50) Lo.delay(1_000) doc.close() return 0 if __name__ == "__main__": SystemExit(main()) ``` -------------------------------- ### Initialize Service Manager Source: https://github.com/amourspirit/python_ooo_dev_tools/blob/main/docs/odev/part1/chapter02.rst Shows how to initialize the `XMultiServiceFactory` service manager by applying `Lo.qi` to a document. ```python # _ms_factory global in Lo doc = loader.loadComponentFromURL("private:factory/swriter", "_blank", 0, props) Lo._ms_factory = Lo.qi(XMultiServiceFactory, doc) ``` -------------------------------- ### Full Example: Chart2 Direct Title/Subtitle Font Only Source: https://github.com/amourspirit/python_ooo_dev_tools/blob/main/docs/help/chart2/format/direct/title/font_only.rst A complete example demonstrating the setup and application of font formatting to both the title and subtitle of a chart. It includes opening a document, accessing chart elements, applying styles, and closing the document. ```python from __future__ import annotations from pathlib import Path import uno from ooo.dyn.awt.gradient_style import GradientStyle from ooodev.calc import CalcDoc, ZoomKind from ooodev.loader.lo import Lo from ooodev.utils.color import StandardColor from ooodev.utils.data_type.color_range import ColorRange def main() -> int: with Lo.Loader(connector=Lo.ConnectPipe()): fnm = Path.cwd() / "tmp" / "piechart.ods" doc = CalcDoc.open_doc(fnm=fnm, visible=True) Lo.delay(500) doc.zoom(ZoomKind.ZOOM_100_PERCENT) sheet = doc.sheets[0] sheet["A1"].goto() chart_table = sheet.charts[0] chart_doc = chart_table.chart_doc _ = chart_doc.style_border_line( color=StandardColor.PURPLE_DARK1, width=0.7, ) _ = chart_doc.style_area_gradient( step_count=64, style=GradientStyle.SQUARE, angle=45, grad_color=ColorRange( StandardColor.BLUE_DARK1, StandardColor.PURPLE_LIGHT2, ), ) title = chart_doc.get_title() if title is None: raise ValueError("Title not found") title.style_font( name="Lucida Calligraphy", size=14, font_style="italic", ) Lo.delay(1_000) doc.close() return 0 if __name__ == "__main__": SystemExit(main()) ``` -------------------------------- ### Get LibreOffice/OpenOffice Paths Source: https://github.com/amourspirit/python_ooo_dev_tools/blob/main/docs/odev/part1/chapter03.rst Demonstrates how to retrieve various predefined paths within the LibreOffice/OpenOffice environment using the Info class. This includes getting the office installation directory, add-in directory, filter directory, template directories, and gallery directory. ```python print(f"\nOffice Dir: {Info.get_office_dir()}") print(f"\nAddin Dir: {Info.get_paths('Addin')}") print(f"\nFilters Dir: {Info.get_paths('Filter')}") print(f"\nTemplates Dirs: {Info.get_paths('Template')}") print(f"\nGallery Dir: {Info.get_paths('Gallery')}") ``` -------------------------------- ### Install Script Provider Source: https://github.com/amourspirit/python_ooo_dev_tools/blob/main/docs/guide/virtual_env/linux_manual_venv_snap.rst Installs the necessary apt package that allows Python scripts to connect to LibreOffice on Linux. ```bash sudo apt install libreoffice-script-provider-python ``` -------------------------------- ### Setup and Style Chart Background Source: https://github.com/amourspirit/python_ooo_dev_tools/blob/main/docs/help/chart2/format/direct_static/general/area.rst Demonstrates the general setup for chart examples and how to style the background of a chart with a specific color and border line. It includes opening a document, accessing a chart, applying styles, and verifying the style. ```python import uno from ooodev.format.chart2.direct.general.area import Color as ChartColor from ooodev.format.chart2.direct.general.borders import LineProperties as ChartLineProperties from ooodev.office.calc import Calc from ooodev.office.chart2 import Chart2 from ooodev.utils.color import StandardColor from ooodev.gui import GUI from ooodev.loader.lo import Lo def main() -> int: with Lo.Loader(connector=Lo.ConnectPipe()): doc = Calc.open_doc("col_chart.ods") GUI.set_visible(True, doc) Lo.delay(500) Calc.zoom(doc, GUI.ZoomEnum.ZOOM_100_PERCENT) sheet = Calc.get_active_sheet() Calc.goto_cell(cell_name="A1", doc=doc) chart_doc = Chart2.get_chart_doc(sheet=sheet, chart_name="col_chart") chart_bdr_line = ChartLineProperties(color=StandardColor.GREEN_DARK3, width=0.7) chart_color = ChartColor(color=StandardColor.GREEN_LIGHT2) Chart2.style_background(chart_doc=chart_doc, styles=[chart_color, chart_bdr_line]) f_style = ChartColor.from_obj(chart_doc.getPageBackground()) assert f_style is not None Lo.delay(1_000) Lo.close_doc(doc) return 0 if __name__ == "__main__": SystemExit(main()) ``` -------------------------------- ### Lo.create_instance_mcf Method Source: https://github.com/amourspirit/python_ooo_dev_tools/blob/main/docs/odev/part1/chapter02.rst Illustrates the implementation of the create_instance_mcf class method within the Lo class, responsible for creating LibreOffice service instances using the MultiComponentFactory. ```python @classmethod def create_instance_mcf( cls, atype: Type[T], service_name: str, args: Tuple[Any, ...] | None = None, raise_err: bool = False ) -> T | None: if cls._xcc is None or cls._mc_factory is None: raise Exception("No office connection found") try: if args is not None: obj = cls._mc_factory.createInstanceWithArgumentsAndContext( service_name, args, cls._xcc ) else: obj = cls._mc_factory.createInstanceWithContext(service_name, cls._xcc) if raise_err is True and obj is None: CreateInstanceMcfError(atype, service_name) interface_obj = cls.qi(atype=atype, obj=obj) if raise_err is True and interface_obj is None: raise MissingInterfaceError(atype) return interface_obj except CreateInstanceMcfError: raise except MissingInterfaceError: raise except Exception as e: raise Exception(f"Couldn't create interface for '{service_name}'") from e ``` -------------------------------- ### Get Help for Impress Slide to Image Tool Source: https://github.com/amourspirit/python_ooo_dev_tools/blob/main/tests/samples/Impress/Slide_to_Image/README.md Displays the help message for the `start` module, outlining available commands and arguments for the Impress Slide to Image tool. ```sh python -m start --help ``` -------------------------------- ### Full Example: Draw Document with Line Shadow Source: https://github.com/amourspirit/python_ooo_dev_tools/blob/main/docs/help/draw/format/direct/shape/line/shadow.rst A complete example demonstrating the setup of a LibreOffice Draw document, drawing a line, applying a shadow to it, and then retrieving the shadow properties. Includes document visibility, zoom, and cleanup. ```python from __future__ import annotations import uno from ooodev.draw import Draw, DrawDoc, ZoomKind from ooodev.loader.lo import Lo from ooodev.format.draw.direct.line import Shadow, ShadowLocationKind from ooodev.utils.color import StandardColor def main() -> int: with Lo.Loader(connector=Lo.ConnectSocket()): doc = DrawDoc(Draw.create_draw_doc()) doc.set_visible() Lo.delay(500) doc.zoom(ZoomKind.ZOOM_75_PERCENT) slide = doc.get_slide() width = 36 height = 36 x = round(width / 2) y = round(height / 2) line = slide.draw_line(x1=x, y1=y, x2=x + width, y2=y + height) style = Shadow( use_shadow=True, location=ShadowLocationKind.TOP_RIGHT, color=StandardColor.GRAY, distance=2, blur=1, transparency=50, ) style.apply(line.component) f_style = Shadow.from_obj(line.component) assert f_style is not None assert f_style.prop_use_shadow is True assert f_style.prop_use_shadow is True assert f_style.prop_location == ShadowLocationKind.TOP_RIGHT Lo.delay(1_000) doc.close_doc() return 0 # To run this example, you would typically call main() # main() ``` -------------------------------- ### Window Event Handling Example Source: https://github.com/amourspirit/python_ooo_dev_tools/blob/main/docs/odev/part1/chapter04.rst Provides an example of handling the `windowOpened` event, casting the event data to `EventObject`, and retrieving the `XWindow` instance to print its size. ```python def windowOpened(self, event: EventObject) -> None: xwin = Lo.qi(XWindow, event.Source) GUI.print_rect(xwin.getPosSize()) ```