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: c299d73e65fd25148baba0bc516a70f2.png

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)

### 如何使用 `python-docx` 设置段落字体颜色 在 `python-docx` 中,设置段落字体颜色可以通过访问 `run` 对象的 `font.color.rgb` 属性来实现。以下是一个完整的代码示例,展示如何设置段落中的文本字体颜色[^1]。 ```python from docx import Document from docx.shared import RGBColor # 创建一个新的文档对象 doc = Document() # 添加一个段落 paragraph = doc.add_paragraph() # 在段落中添加文本,并设置字体颜色 run = paragraph.add_run("这是一个设置了红色字体颜色的文本示例。") run.font.color.rgb = RGBColor(255, 0, 0) # 设置字体颜色为红色 # 保存文档 doc.save("set_font_color.docx") ``` #### 代码说明 - 使用 `add_run()` 方法向段落中添加文本。 - 通过 `run.font.color.rgb` 属性设置字体颜色,`RGBColor` 类用于定义颜色值。 - 颜色值以 `(R, G, B)` 的形式传入,其中 R、G B 分别表示红、绿、蓝三种颜色的强度,取值范围为 0 到 255。 如果需要对整个段落的所有文本应用相同的字体颜色,可以遍历段落中的所有 `run` 对象并逐一设置其颜色。 ```python from docx import Document from docx.shared import RGBColor # 创建一个新的文档对象 doc = Document() # 添加一个段落 paragraph = doc.add_paragraph() paragraph.add_run("这是第一部分文本。") paragraph.add_run(" 这是第二部分文本。") # 遍历段落中的所有 run 对象并设置字体颜色 for run in paragraph.runs: run.font.color.rgb = RGBColor(0, 0, 255) # 设置字体颜色为蓝色 # 保存文档 doc.save("set_paragraph_font_color.docx") ``` #### 注意事项 - 如果段落包含多个 `run` 对象,则需要分别对每个 `run` 设置字体颜色,因为每个 `run` 可以有不同的格式。 - 如果需要清空段落的样式(包括字体颜色),可以使用类似的方法将 `run.font.color.rgb` 设置为 `None`[^2]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值