Skip to content

Instantly share code, notes, and snippets.

@aspose-com-gists
Created July 23, 2024 07:17
Working with Table of Contents (TOC) in Word Using Python
# This code example shows how to add a Table of Contents in a Word document.
# Create a document
doc = aw.Document()
# Initialize a document builder
builder = aw.DocumentBuilder(doc)
# Insert table of contents
builder.insert_table_of_contents("\\o \"1-3\" \\h \\z \\u")
# Start the actual document content on the second page.
builder.insert_break(aw.BreakType.PAGE_BREAK)
builder.paragraph_format.style_identifier = aw.StyleIdentifier.HEADING1
builder.writeln("Heading 1")
builder.paragraph_format.style_identifier = aw.StyleIdentifier.HEADING2
builder.writeln("Heading 1.1")
builder.writeln("Heading 1.2")
builder.paragraph_format.style_identifier = aw.StyleIdentifier.HEADING1
builder.writeln("Heading 2")
builder.writeln("Heading 3")
builder.paragraph_format.style_identifier = aw.StyleIdentifier.HEADING2
builder.writeln("Heading 3.1")
builder.paragraph_format.style_identifier = aw.StyleIdentifier.HEADING3
builder.writeln("Heading 3.1.1")
builder.writeln("Heading 3.1.2")
builder.writeln("Heading 3.1.3")
builder.paragraph_format.style_identifier = aw.StyleIdentifier.HEADING2
builder.writeln("Heading 3.2")
builder.writeln("Heading 3.3")
# The newly inserted table of contents will be initially empty.
# It needs to be populated by updating the fields in the document.
doc.update_fields()
# Save the document
doc.save("insert_table_of_contents.docx")
# This code example shows how to extract a Table of Contents from a Word document.
# Load an existing Word document
doc = aw.Document(InsertTOC_out.docx")
# Loop through all the fields
for field in doc.range.fields:
# Check if it is FIELD_HYPERLINK
if (field.type == aw.fields.FieldType.FIELD_HYPERLINK):
hyperlink = field.as_field_hyperlink()
# Check if it in TOC section
if (hyperlink.sub_address != None and hyperlink.sub_address.find("_Toc") == 0):
tocItem = field.start.get_ancestor(aw.NodeType.PARAGRAPH).as_paragraph()
print(tocItem.to_string(aw.SaveFormat.TEXT).strip())
print("------------------")
# Print
bm = doc.range.bookmarks.get_by_name(hyperlink.sub_address)
pointer = bm.bookmark_start.get_ancestor(aw.NodeType.PARAGRAPH).as_paragraph()
print(pointer.to_string(aw.SaveFormat.TEXT))
# This code example shows how to insert a Table of Contents in an existing Word document.
# Load an existing Word document
doc = Document("toc_sample.docx");
builder = DocumentBuilder(doc);
# Insert a table of contents at the beginning of the document.
builder.insert_table_of_contents("\\o \"1-3\" \\h \\z \\u");
# The newly inserted table of contents will be initially empty.
# It needs to be populated by updating the fields in the document.
doc.update_fields();
# Save the document
doc.save("InsertTOC_out.docx");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment