Search code examples
pythonpython-3.xpython-docx

highlight paragraph in docx file using python-docx


I am trying to highlight a paragraph in a .docx file using python-docx.

from docx import Document
from docx.enum.text import WD_COLOR_INDEX

source_folder = 'D:/project/data2/'
f = source_folder+'test.docx'
document = Document(f)


for para in document.paragraphs:
    font1 = para.add_run().font
    font1.highlight_color = WD_COLOR_INDEX.RED
document.save(source_folder+'new.docx')

This code should highlight all the paragraphs in the document but it is not.


Solution

  • from docx import Document
    from docx.enum.text import WD_COLOR_INDEX
    
    source_folder = 'D:/project/data2/'
    f = source_folder+'test.docx'
    document = Document(f)
    
    
    for para in document.paragraphs:
        for run in para.runs:
            run.font.highlight_color = WD_COLOR_INDEX.RED
    document.save(source_folder+'new.docx')