As you know the LibreOffice includes several applications that make it the most powerful Free and Open Source office suite on the market: Writer (word processing), Calc (spreadsheets), Impress (presentations), Draw (vector graphics and flowcharts), Base (databases), and Math (formula editing).
This tutorial is about LibreOffice and python scripts used like macros.
First, you need to assign the permission for your user to write into the script folder.
The main reason comes from your software – the LibreOffice and your script editor for python language need to using this path: C:\Program Files (x86)\LibreOffice 5\share\Scripts.
If you using one of the linux OS then he path will be: /Applications/LibreOffice.app/Contents/Resources/Scripts/python/.
Your script can be run using the LibreOffice macro: Tools – Macros – Organize Macros – Python.
This allows you to see the python files and also can be run with the Run button.
I used LibreOffice version: 126.96.36.199 to make one default python script.
I open my python script with the LibreOffice default interface ( not Writer, Calc, Base, etc.) and this allows me to run python scripts for any type of LibreOffice applications.
Let’s see the python script:
"""Prints the Python version into the current document"""
#get the doc from the scripting context
desktop = XSCRIPTCONTEXT.getDesktop()
# made available to all scripts
model = desktop.getCurrentComponent()
#check whether there's already an opened document
#if not, create a new one
if not hasattr(model, "Text"):
model = desktop.loadComponentFromURL(
"private:factory/swriter","_blank", 0, () )
#get the XText interface
text = model.Text
#create an XTextRange at the end of the document
tRange = text.End
#add the python version to the string
tRange.String = "The Python version is %s.%s.%s" % sys.version_info[:3] + " and the executable path is " + sys.executable
The output of the running script will be open under a new document named Untitled 1.
The content of this result is: The Python version is 3.3.5 and the executable path is C:\Program Files (x86)\LibreOffice 5\program\soffice.bin.
The size of the text is 12, Default Style and the font is Liberation Serif.
The python script is simple: Is like take the interface model and put some text into that.
About hasattr part is just to reduce your possible errors and avoid confusing differences in behavior between Python 2 and 3.
Don’t use Python’s hasattr() unless you’re writing Python 3-only code and understand how it works.
The syntax under Python 3 is:
The arguments are an object and a string. The result is True if the string is the name of one of the object’s attributes, False if not. (This is implemented by calling getattr(object, name) and seeing whether it raises an AttributeError or not.)