Python UNO create TOC

Hi there,

I am using LO 7.5.4.2.

I am trying to create a TOC in Writer using python.

Using the UI, I can create a TOC as per this image:

Back to python, I am doing:

url = "my_file_path"
document = desktop.loadComponentFromURL(url, "_blank", 0, ())
toc = document.createInstance("com.sun.star.text.ContentIndex")
toc.setPropertyValue("Level", 10)  # Include all heading levels
text = document.Text
cursor = text.createTextCursor()
text.insertTextContent(cursor, toc, False)

But it is not outputting anything other than an empty TOC, because it’s not picking up the Heading Styles (Additional Styles that I have to set when creating the TOC in the UI, as per the image above).

Looking here:
https://www.openoffice.org/api/docs/common/ref/com/sun/star/text/ContentIndex.html

it seems that I must apply ::com::sun::star::container::XIndexReplace LevelParagraphStyles as a toc property via toc.setPropertyValue but it’s all getting a bit deep and I could really use some advice if anyone can help please?

Thanks

Try with this code:

    toc = doc.createInstance('com.sun.star.text.ContentIndex')
    toc.CreateFromOutline = True
    text = doc.obj.Text
    cursor = text.createTextCursor()
    text.insertTextContent(cursor, toc, False)
    toc.update()

Because the API is mostly same when you use Python, maybe Andrew Pitonyak’s macro code snippets will help you:

14.13 Table of contents

in the

OpenOffice.org Macros Explained
OOME Fourth Edition”

https://www.pitonyak.org/oo.php