Okay, since it isn’t the last thing I need to automate, I finally wrote a script using LO UNO API with python.
First one needs to start a server with the command below, so the executed script would connect to this instance.
soffice "--accept=socket,host=localhost,port=8100;urp;" --headless --invisible
I commented the code below, I hope it is clear. This code workig for me atm.
#!/usr/bin/python3
import uno
import os
def absoluteUrl(relativeFile):
"""Constructs absolute path to the current dir in the format required by PyUNO that working with files"""
return "file:///" + os.path.realpath(".") + "/" + relativeFile
def parBreak(document, cursor):
"""Inserts a paragraph break at cursor position"""
document.Text.insertControlCharacter( cursor.End,
uno.getConstantByName('com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK'),
False)
def updateTOC(document):
"""Update links in table of contents"""
iList = document.getDocumentIndexes()
assert(iList.getCount() > 0), "Table of contents not found, aborting!"
for i in range(0, iList.getCount()):
iList.getByIndex(i).update()
localContext = uno.getComponentContext()
resolver = localContext.ServiceManager.createInstanceWithContext(
"com.sun.star.bridge.UnoUrlResolver", localContext )
smgr = resolver.resolve( "uno:socket,host=localhost,port=8100;urp;StarOffice.ServiceManager" )
remoteContext = smgr.getPropertyValue( "DefaultContext" )
desktop = smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",remoteContext)
file = desktop.loadComponentFromURL(absoluteUrl("./build/output.odt") ,"_blank", 0, ())
#insert at the beginning the file with title page and TOC
cursor = file.Text.createTextCursor()
cursor.gotoStart(False)
#to not screw the first paragraph formatting let's first make an empty one here
parBreak(file, cursor)
cursor.gotoStart(False)
cursor.insertDocumentFromURL(absoluteUrl("./Title\'n\'TOC.odt"), ())
updateTOC(file) #the inserted TOC needs to be updated
#save the file
file.storeAsURL(absoluteUrl("./build/Курсовая.odt"),())
file.dispose()
A possible pit — the function insertDocumentFromURL
doesn’t tell anything when something gone wrong, e.g. if the file not exist (with the weird format for file paths that would happen pretty often). So one could use only indirect logic to figure out whether something gone wrong. In the code above the logic is the assert()
in the function that updates TOC.