text color in python-pptx module

∥☆過路亽.° 提交于 2019-12-23 09:40:47

问题


I would like to color a sentence, in different color - say, the first half in red and rest in blue.

my code so far is like

from pptx import Presentation
from pptx.util import Inches, Pt
from pptx.dml.color import ColorFormat, RGBColor
from pptx.enum.dml import MSO_COLOR_TYPE, MSO_THEME_COLOR
import codecs


prs = Presentation()
title_slide_layout = prs.slide_layouts[0]
slide = prs.slides.add_slide(title_slide_layout)


text_file = open("content.txt", "r")
# read the lyrics file
lines = text_file.readlines()

# page title
title = slide.shapes.title

# text frame in the page
tf = title.textframe

# paragrap in the text frame
p = tf.add_paragraph()
# write the first sentence 
#p.text = unicode(lines[0], encoding='utf-8')
p.text = "hello is red the rest is blue"
p.font.bold = True
p.font.color.rgb = RGBColor(255, 0, 0)

prs.save('test.pptx')
text_file.close()

in my code, the entire sentence is red; I would like to know how can I address different words to different color - again, say first half red the rest in blue.


回答1:


Add them as separate runs like so:

from pptx.dml.color import RGBColor
from pptx.enum.dml import MSO_THEME_COLOR
from pptx.util import Pt

p = tf.add_paragraph()
run = p.add_run()
run.text = 'hello'
font = run.font
font.name = 'Calibri'
font.size = Pt(18)
font.bold = True
font.color.theme_color = MSO_THEME_COLOR.ACCENT_1

run = p.add_run()
run.text = ' is red and the rest is blue'
run.font.color.rgb = RGBColor(0, 0, 255)

A run is a sequence of characters all sharing the same character formatting. To change character formatting within a paragraph, multiple runs must be used.




回答2:


there is easier way to change font:

 run.text.text_frame._set_font(font,size,bold,italic)


来源:https://stackoverflow.com/questions/24729098/text-color-in-python-pptx-module

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