How to Insert a Bookmark in Word using Python

This short tutorial contains information on how to insert a bookmark in Word using Python. It shares the details to set the environment, a step-wise process to write the application, and a runnable sample code to automatically create bookmarks in Word using Python. All the necessary resources, classes, and methods are also presented to write this application using a few API calls only and then saving the output file as a DOCX, or DOC as per the requirement.

Steps to Insert a Bookmark in Word using Python

  1. Establish the environment to add Aspose.Words for Python via .NET to add bookmarks
  2. Create an empty document object and instantiate the DocumentBuilder object using it
  3. Start a bookmark and insert some text in the document
  4. Insert a nested bookmark and add some text after it
  5. Close the nested bookmark and add some text after it for testing
  6. Close the first bookmark and save the document on the disk

These steps explain the process to create bookmark in Word using Python. First, a document is created and a bookmark is added to it. Then some other text and a nested bookmark are created however these steps are not necessary and are provided just for clarification. Once all the bookmarks are closed, the resultant document is saved on the disk.

Code to Add Bookmark in Word using Python

import aspose.words as aw
# Load the license
wordLic = aw.License()
wordLic.set_license("Aspose.Total.lic")
# Create a document
doc = aw.Document()
# Create a document builder object
builder = aw.DocumentBuilder(doc)
# Start a bookmark
builder.start_bookmark("first_bookmark")
# Add some sample text
builder.writeln("Text for the first bookmark")
# Start nested bookmark
builder.start_bookmark("second_nested_bookmark")
# Add some sample text within nested bookmark as well as in the first bookmark
builder.writeln("Text inside the nested bookmark as well as in the first bookmark")
# End the nested bookmark
builder.end_bookmark("second_nested_bookmark")
# Write some sample text again
builder.writeln("Text after nested bookmark within the first bookmark.")
# End the first bookmark
builder.end_bookmark("first_bookmark")
# Save the resultant bookmark
doc.save("Output.docx")
print ("Bookmarks added successfully in the Word file")

This code demonstrates the process to add bookmark to Word document using Python. It uses the DocumentBuilder class object to start and close bookmarks and also to add sample text to test the feature in the output document. You can also use DocumentBuilder class to add and close column-wise bookmarks using the start_column_bookmark() method and move to a particular bookmark using the move_to_bookmark().

This article has guided us to add multiple bookmarks in a Word document. If you want to learn the process to add a watermark to a Word file, refer to the article on how to put a watermark on a Word document using Python.

 English