天天看點

python docx 标題字型顔色,使用docx python庫,如何同時應用顔色和字型大小

python docx 标題字型顔色,使用docx python庫,如何同時應用顔色和字型大小

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:

python docx 标題字型顔色,使用docx python庫,如何同時應用顔色和字型大小

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.

解決方案

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)