Using docx python library, how to apply color and

2020-08-01 11:57发布

问题:

I am writing to an .docx file using python docx library. I want to prespecify the font size and color of a paricular sentence. My problem is that I am not able to do it simultaneously. Let me illustrate -

from docx import Document        
from docx.shared import Pt       #Helps to specify font size
from docx.shared import RGBColor #Helps to specify font Color
document=Document()              #Instantiation
p=document.add_heading(level=0)
p.add_run('I want this sentence colored red with fontsize=22').font.size=Pt(22)  #Specifies fontsize 22
p.add_run('This line gets colored red').font.color.rgb=RGBColor(255,0,0)    #Specifies RED color
document.save('path/file.docx')

Result:

I am very well aware that I am setting the color Red to the second sentence, and since there is an = before Pt(22) and RGBColor(255,00) so I cannot apply fontsize and color simultaneously

Is there a way to apply both attributes simultaneously?

Editted: I want the line I want this sentence colored red with fontsize=22 in Red color.

回答1:

maybe you can make this

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