Search code examples
pythongoogle-docs-api

Google Docs API programmatically adding a table of content


I have a python script which does some analysis and output the results as text (paragraphs) on a Google Doc. I know how to insert text, update paragraph and text style through batchUpdate.

doc_service.documents().batchUpdate(documentId=<ID>,body={'requests': <my_request>}).execute()

where, for instance, "my_request" takes the form of something like:

request = [
        {
            "insertText": {
                "location": {
                    "index": <index_position>,
                    "segmentId": <id>
                },
                "text": <text>
            }
        },
        {
            "updateParagraphStyle": {
                "paragraphStyle": {
                    "namedStyleType": <paragraph_type>
                },
                "range": {
                    "segmentId": <id>,
                    "startIndex": <index_position>,
                    "endIndex": <index_position>
                },
                "fields": "namedStyleType"
            }
        },
    ]

However, once the script is done updating the table, it would be fantastic if a table of content could be added at the top of the document.

However, I am very new to Google Docs API and I am not entirely sure how to do that. I know I should use "TableOfContents" as a StructuralElement. I also know this option currently does not update automatically after each modification brought to the document (this is why I would like to create it AFTER the document has finished updating and place it at the top of the document).

How to do this with python? I am unclear where to call "TableOfContents" in my request.

Thank you so very much!


Solution

  • After your comment, I was able to understand better what you are desiring to do, but I came across these two Issue Tracker's posts:

    These are well-known feature requests that unfortunately haven't been implemented yet. You can hit the ☆ next to the issue number in the top left on this page as it lets Google know more people are encountering this and so it is more likely to be seen faster.

    Therefore, it's not possible to insert/update a table of contents programmatically.