【问题标题】:Using docx python library, how to apply color and font size simultaneously使用 docx python 库,如何同时应用颜色和字体大小
【发布时间】:2018-07-19 06:09:02
【问题描述】:

我正在使用 python docx 库写入 .docx 文件。我想预先指定特定句子的字体大小和颜色。我的问题是我无法同时做到这一点。让我举例说明-

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)RGBColor(255,00) 之前有一个 = 所以我不能同时应用 fontsizecolor

有没有办法同时应用这两个属性?

已编辑:我想要红色的线 I want this sentence colored red with fontsize=22

【问题讨论】:

  • 同时做这两个有什么好处?
  • 嗯,我的意图是让“我希望这句话用 fontsize=22 染成红色”这一行染成红色。最终结果很重要,手段不重要,所以如果你有其他方法同样好。

标签: python fonts colors font-size python-docx


【解决方案1】:

也许你可以做这个

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)

【讨论】:

  • 这正是我想要的。非常干净的解决方案。非常感谢你,因为今天是你使用 stackoverflow 的第一天。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2020-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-19
  • 2022-11-13
  • 2011-03-14
  • 1970-01-01
相关资源
最近更新 更多