How to automatically update indices in headless mode?

I’m using --convert-to to convert a document generated by a script to PDF. This document contains a table of content, but this table is unpopulated. There is the menu-item “update all indexes” which does the thing I want it to do, but I can’t do any user interaction. There might be a way to use the UpdateAllIndexes uno dispatch, but I wouldn’t know how as the documentation for these things is either missing or very well hidden.

So: how do I update the table of content of a document without user interaction?

Hi - One solution might be to run a macro that would do the job (open the document, update the index, export to pdf format).

Command line: soffice.exe "macro:///Standard.Module1.PysIndexer(a.odt)"

Note: paths must be provided

Sample Code:

sub PysIndexer(sDocUrl as string)

dim oDocument as object
dim dispatcher as object

dim propExp(0) as new com.sun.star.beans.PropertyValue

dim sNewUrl as string

if fileExists(sDocUrl) then
	oDocument = starDesktop.loadComponentFromUrl(convertToUrl(sDocUrl), "_blank", 0, array())

	dispatcher = createUnoService("com.sun.star.frame.DispatchHelper")
	dispatcher.executeDispatch(oDocument.CurrentController.Frame, ".uno:UpdateAllIndexes", "", 0, Array())
	
	propExp(0).Name = "FilterName"
	propExp(0).Value = "writer_pdf_Export"
	
	GlobalScope.BasicLibraries.LoadLibrary("Tools")
	
	sNewUrl = GetFileNameWithoutExtension(sDocUrl) & ".pdf"

	oDocument.storeToURL(convertToUrl(sNewUrl), propExp())
end if

end sub

I needed to pass an absolute filename to the macro, but then it worked!

I found the standard approach of .uno:UpdateAllIndexes to be unreliable. I ended up iterating and updating each Index directly.

Python code:

    for i in range(0, doc.DocumentIndexes.getCount()):
      doc.DocumentIndexes.getByIndex(i).refresh()

If you find something “unreliable”, you should file a relevant bug report with steps to reproduce, so that it could be investigated and fixed.