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
- Establish the environment to add Aspose.Words for Python via .NET to add bookmarks
- Create an empty document object and instantiate the DocumentBuilder object using it
- Start a bookmark and insert some text in the document
- Insert a nested bookmark and add some text after it
- Close the nested bookmark and add some text after it for testing
- 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
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.