Using docx python library, how to apply color and font size simultaneously

╄→гoц情女王★ 提交于 2019-12-12 09:30:58

问题


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)


来源:https://stackoverflow.com/questions/48689438/using-docx-python-library-how-to-apply-color-and-font-size-simultaneously

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!