Working with Highlighted Text in Python .docx Module
Word documents contain formatted text wrapped within three object levels. The Lowest level- run objects, middle level- paragraph objects and highest level- document object. So, we cannot work with these documents using normal text editors. But, we can manipulate these word documents in python using the python-docx module. Pip command to install this module is:
pip install python-docx
Python docx module allows users to manipulate docs by either manipulating the existing one or creating a new empty document and manipulating it. It is a powerful tool as it helps you to manipulate the document to a very large extend. You can also add highlighted text in your Word document.
To add the highlighted text you have to first create a paragraph object then you have to use add_run() method to add content. You can directly use add_paragraph() method to add a paragraph but if you want to add the highlighted text you have to use add_run() as all the block-level formatting is done by using add_paragraph() method while all the character-level formatting is done by using add_run().
Adding Highlighted Text
Text is highlighted by assigning a member of WD_COLOR_INDEX to Font.highlight_color. To use WD_COLOR_INDEX we have first import it using the following import statement.
from docx.enum.text import WD_COLOR_INDEX
Syntax: paragraph.add_run().font.highlight_color = Colour_Name
Parameter: Colour_Name: It is the name of the colour assign to highlight the text. It is the member of the WD_COLOR_INDEX.
Note: If we don’t assign the colour then default colour is NONE.
Example 1: Highlighting the complete paragraph using the python-docx module.
Example 2: Highlighting the specific word or phrase in a paragraph using the python-docx module.
There are various colour option to highlight the text. You can choose any colour which is a member of WD_COLOR_INDEX. The list of colours are as follows:
Colour Name In WD_COLOR_INDEX
Default or No Colour
Dark Blue Colour
Dark Red Colour
Dark Yellow Colour
Light Gray Colour
Dark Gray Colour
Dark Green Colour
Dark Cyan Colour
Dark Magenta Colour
Example 3: Adding styled highlighted text in the Word document.
Please Login to comment...