Reputation: 621
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.
Upvotes: 17
Views: 27060
Reputation: 1107
from docx import Document
from docx.shared import RGBColor
document = Document()
paragraph = document.add_paragraph()
run = paragraph.add_run('Red ')
run.font.color.rgb = RGBColor(255, 0, 0)
run = paragraph.add_run('Green ')
run.font.color.rgb = RGBColor(0x00, 0xFF, 0x00)
run = paragraph.add_run('Blue')
run.font.color.rgb = RGBColor.from_string('0000FF')
document.save('test.docx')
Upvotes: 4
Reputation: 11
font.color.rgb = RGBColor.from_string('FF0000')
This will be handy to construct RGBColor.
Upvotes: 1
Reputation: 621
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.
Upvotes: 26