使用docx python库,如何同时应用颜色和字体大小 [英] Using docx python library, how to apply color and font size simultaneously

查看:545
本文介绍了使用docx python库,如何同时应用颜色和字体大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用python docx库写入.docx文件。我想预先指定一个特殊句子的字体大小和颜色。我的问题是我无法同时进行。让我来说明-

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')

结果:

我非常清楚我将颜色设置为 Red 到第二句,并且由于在 Pt(22)和<前有一个 = code> RGBColor(255,00),因此我无法应用 fontsize a nd color 同时

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?

已编辑:我希望该行我希望此句子显示为红色,并且fontsize = 22 为红色。

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

推荐答案

也许您可以这样做

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)

这篇关于使用docx python库,如何同时应用颜色和字体大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆