Search code examples
pythoncolorsfontspython-docx

Python docx - Multiple color in one line


I'm currently genereting a word file using python docx library.

I create multiple table contening text and variables. When there is a variable in the line I mark them like this : <Variable_name>var

I need to change the color of the delimiter <>var to red to highlight it.

The only way think i've found about text color is:

p=document.add_paragraph()
wp = p.add_run('I want this sentence colored red with fontsize=22')
wp.font.color.rgb = RGBColor(255,0,0)

But it's for the all paragraph, not a specific part.


Solution

  • Character-level formatting ("font" characteristics) is controlled at the run level. A run is a sequence of characters that share the same character-level formatting. Consequently, if you want a "run" of red characters inside a normally formatted paragraph, you need three runs; one before, one red, and one after.

    paragraph = document.add_paragraph()
    paragraph.add_run("The part before the red bit ")
    run = paragraph.add_run("the red bit")
    run.font ... # --- make the font of this run red ---
    paragraph.add_run(" the part after the red bit.")