OO-Snippets: Create and insert or modify an existing table of contents or index

Commons

Keywordsindex, table of contents, ContentIndex, getDocumentIndexes, CreateFromOutline
LanguageOOBasic
ApplicationWriter
AuthorsAndrew Pitonyak (initial)
Supported Versions
Supported OS
Question How can I insert a table of contents into my document?
Answer

Create a com.sun.star.text.ContentIndex from the document and then insert the text content.

Be certain to set the appropriate properties. I have some discussion at: http://www.oooforum.org/forum/viewtopic.php?t=10251

Code-Snippet-Listing (snippet-source)

Sub InsertATOC
  REM Author: Andrew Pitonyak
  Dim oCurs                  'Used to insert the text content.
  Dim oIndexes               'All of the existing indexes
  Dim oIndex                 'The TOC if it exists and a new one if not
  Dim i As Integer           'Find an existing TOC
  Dim bIndexFound As Boolean 'Flag to track if the TOC was found

  REM First, find an existing TOC if it exists. If so, 
  REM then this will simply be updated.
  oIndexes = ThisComponent.getDocumentIndexes()
  bIndexFound = False
  For i = 0 To oIndexes.getCount() - 1
    oIndex = oIndexes.getByIndex(i)
    If oIndex.supportsService("com.sun.star.text.ContentIndex") Then
      bIndexFound = True
      Exit For
    End If
  Next

  If Not bIndexFound Then
    Print "I did not find an existing content index"
    REM Perhaps you should create and insert a new one!
    REM Notice that this MUST be created by the document that will
contain
    REM the index.
    oIndex = ThisComponent.createInstance("com.sun.star.text.ContentIndex")
    
    REM On my system, these are the default values
    REM How do you want to create the index?
    REM CreateFromChapter = False
    REM CreateFromLevelParagraphStyles = False
    REM CreateFromMarks = True
    REM CreateFromOutline = False
    oIndex.CreateFromOutline = True

    REM You can set all sorts of other things such as the
    REM Title or Level

    oCurs = ThisComponent.getText().createTextCursor()
    oCurs.gotoStart(False)
    ThisComponent.getText().insertTextContent(oCurs, oIndex, False)
  End If
  
  REM Even the newly inserted index is not updated until right HERE!
  oIndex.update()
End Sub

Changelog

DateUserModification
2004-06-29pitonyakInitial version

and