Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write text in particular font color in MS word using python-docx

I am trying to write text in an MS Word file using python library python-docx. I have gone through the documentation of python-docx's font color on this link and applied the same in my code, but am unsuccessful so far.

Here is my code:

from docx import Document
from docx.shared import RGBColor
document = Document()
run = document.add_paragraph('some text').add_run()
font = run.font
font.color.rgb = RGBColor(0x42, 0x24, 0xE9)
p=document.add_paragraph('aaa')
document.save('demo1.docx')

The text in word file 'demo.docx' is simply in black color.

I am not able to figure this out, help would be appreciated.

like image 750
troy_achilies Avatar asked Feb 01 '17 11:02

troy_achilies


People also ask

How do you change the Font in Python docx?

You can directly use add_paragraph() method to add paragraph but if you want to set a new font style of the 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().

How do you highlight text in DOCX with Python?

add_text() returns a _Text object, not a run. Also, a highlight is applied to the entire run, so you need to create a separate runs for each of the text before "vehicle", the "vehicle" word itself, and the text after "vehicle".

How do you change the color of certain text in Word?

You can change the color of text in your Word document. Select the text that you want to change. On the Home tab, in the Font group, choose the arrow next to Font Color, and then select a color.


1 Answers

I have found the answer myself using python-docx docs,

Here is the correct code:

from docx import Document
from docx.shared import RGBColor
document = Document()
run = document.add_paragraph().add_run('some text')
font = run.font
font.color.rgb = RGBColor(0x42, 0x24, 0xE9)
p=document.add_paragraph('aaa')
document.save('demo1.docx')

'some text' is a parameter of add_run() function rather than add_paragraph() function.

The above code gives desired color.

like image 51
troy_achilies Avatar answered Oct 17 '22 11:10

troy_achilies