Search code examples
pythonlibreofficeuno

Python libreoffice set margin values, optimal height and print document with uno


I trying to interact with libreoffice with Python, which integrated in Libreoffice installation. And I didn't found anywhere how can I set margins in PageStyle, to set optimal height of row and prind few copies of document. Or, maybe, I can write macro in Libreoffice and run it from python. Code below is not working.

pageStyle = document.getStyleFamilies().getByName("PageStyles")
page = pageStyle.getByName("Default")
page.LeftMargin = 500

P.S. Sorry for my english.


Solution

  • In most versions of LibreOffice, the name of the default style is "Default Style". In Apache OpenOffice, it is named "Default" instead.

    Here is the complete code. For example, name the file change_settings.py.

    import uno
    
    def set_page_style_margins():
        document = XSCRIPTCONTEXT.getDocument()
        pageStyle = document.getStyleFamilies().getByName("PageStyles")
        page = pageStyle.getByName("Default Style")
        page.LeftMargin = 500
    
    g_exportedScripts = set_page_style_margins,
    

    On my Windows 10 system, this script is located under the directory C:\Users\<your username>\AppData\Roaming\LibreOffice\4\user\Scripts\python. You will need to create the last two directories, and case must match.

    Now, in LibreOffice Writer, go to Tools -> Macros -> Run Macro. Expand to My Macros -> change_settings and select the macro name set_page_style_margins.

    For a full introduction to Python with LibreOffice: