Python-pptx - Autoshape 上的文本参数(字体、大小、位置)

标签 python powerpoint python-pptx

如何设置形状的字体、文字大小?

一个对象而不是两个单独的对象(形状和文本,如何使用形状运行)

只是不知道如何在自选图形对象的 Textframe 实例上设置参数。

from pptx import Presentation
from pptx.enum.shapes import MSO_SHAPE
from pptx.enum.dml import MSO_THEME_COLOR
from pptx.enum.text import MSO_ANCHOR, MSO_AUTO_SIZE
from pptx.util import Inches, Pt

prs = Presentation('Input.pptx')
slide_layout = prs.slide_layouts[2]
slide = prs.slides.add_slide(slide_layout)
shape = slide.shapes
#Title
shape.title.text = "Title of the slide"
# Shape position
left = Inches(0.5)
top = Inches(1.5)
width = Inches(2.0)
height = Inches(0.2)

box = shape.add_shape(MSO_SHAPE.RECTANGLE, left, top, width, height)
#Fill
fill = box.fill
line = box.line
fill.solid()
fill.fore_color.theme_color = MSO_THEME_COLOR.ACCENT_2
line.color.theme_color = MSO_THEME_COLOR.ACCENT_2
# How can I set font, size of text for the shape ?
# One Object for instead two seperate ones
#box_text.font.bold = True

# Text position
t_left = Inches(0.5)
t_top = Inches(1.4)
t_width = Inches(2.0)
t_height = Inches(0.4)
#Text
txBox = slide.shapes.add_textbox(t_left, t_top, t_width,t_height)
tf = txBox.text_frame.paragraphs[0]
tf.vertical_anchor = MSO_ANCHOR.TOP
tf.word_wrap = False
tf.margin_top = 0
tf.auto_size = MSO_AUTO_SIZE.SHAPE_TO_FIT_TEXT
run = tf.add_run()
run.text = "Text on the Shape"
font = run.font
font.name = 'Calibri'
font.size = Pt(18)
font.bold = True
font.italic = None  # cause value to be inherited from theme
font.color.theme_color = MSO_THEME_COLOR.ACCENT_5
prs.save('Out.pptx')

最佳答案

如果你想在一个形状中使用非默认的字符格式(字体),你需要在运行级别进行操作;这就是字符格式存在的地方,并且几乎是运行而不仅仅是段落的全部原因。

举个简单的例子:

from pptx.util import Pt
from pptx.enum.shapes import MSO_SHAPE

shape = shapes.add_shape(MSO_SHAPE.RECTANGLE, left, top, width, height)
text_frame = shape.text_frame
text_frame.clear()  # not necessary for newly-created shape

p = text_frame.paragraphs[0]
run = p.add_run()
run.text = 'Spam, eggs, and spam'

font = run.font
font.name = 'Calibri'
font.size = Pt(18)
font.bold = True

通过向段落添加更多运行,例如,您可以在正常格式的单词等句子中添加粗体单词等。

更多详情及周边:http://python-pptx.readthedocs.io/en/latest/user/text.html#applying-character-formatting

关于Python-pptx - Autoshape 上的文本参数(字体、大小、位置),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45633385/

相关文章:

java - 如何使用 apache POI 复制包含图表的幻灯片?

Python 继承 - 您可以在父级中设置默认值吗?

c# - PPT 幻灯片对象调整大小后捕捉事件

vba - 如何自动进行 PowerPoint 拼写检查?

python - 如何使用 pptx python 库更改 PPT 幻灯片上项目符号列表的缩进

python-pptx:如何重新定位图片占位符?

python - Azure数据工厂管道: Creating pipelines with Python: Authentication (via az cli)

python - 将 Pandas 列转换为日期时间

python - 使用python将文本文件转换为html文件

python ppt在图表中查找和替换