python-pptx 学习笔记 placeholder、Text

placeholder API

#1.访问placeholder
#通过idx访问
prs = Presentation()
slide = prs.slides.add_slide(prs.slide_layouts[8])
#获得idx,遍历
for shape in slide.placeholders:
print('%d %s' % (shape.placeholder_format.idx, shape.name))
#以字典的形式访问
slide.placeholders[2].name
#2.判断placeholder
#方式一:通过shape.shape_type,返回PLACEHOLDER (14)
#方式二:shape.is_placeholder
#3.在placeholder中插入内容
#插入图片等元素
placeholder.placeholder_format.type #判断类型
placeholder.insert_picture('my-image.png')
#其他元素
#参考:https://python-pptx.readthedocs.io/en/latest/user/text.html

Text API

#层级结构:text_frame->paragraph->run
#1.判断是否可以加入文本
shape.has_text_frame
#2.访问paragraphs
text_frame = shape.text_frame
text_frame.clear() # remove any existing paragraphs, leaving one empty one
p = text_frame.paragraphs[0]
p.text = paragraph_strs[0]
for para_str in paragraph_strs[1:]:
p = text_frame.add_paragraph()
p.text = para_str
#3.添加文本
shape.text = 'foobar'
# is equivalent to ...
text_frame = shape.text_frame
text_frame.clear()
p = text_frame.paragraphs[0]
run = p.add_run()
run.text = 'foobar'
#4.设置文本块格式
from pptx.util import Inches
from pptx.enum.text import MSO_ANCHOR, MSO_AUTO_SIZE
text_frame = shape.text_frame
text_frame.text = 'Spam, eggs, and spam'
text_frame.margin_bottom = Inches(0.08)
text_frame.margin_left = 0
text_frame.vertical_anchor = MSO_ANCHOR.TOP
text_frame.word_wrap = False
text_frame.auto_size = MSO_AUTO_SIZE.SHAPE_TO_FIT_TEXT
#5.设置段落格式
from pptx.enum.text import PP_ALIGN
paragraph_strs = [
'Egg, bacon, sausage and spam.',
'Spam, bacon, sausage and spam.',
'Spam, egg, spam, spam, bacon and spam.'
]
text_frame = shape.text_frame
text_frame.clear()
p = text_frame.paragraphs[0]
p.text = paragraph_strs[0]
p.alignment = PP_ALIGN.LEFT
for para_str in paragraph_strs[1:]:
p = text_frame.add_paragraph()
p.text = para_str
p.alignment = PP_ALIGN.LEFT
p.level = 1
#6.设置字体格式
from pptx.dml.color import RGBColor
from pptx.enum.dml import MSO_THEME_COLOR
from pptx.util import Pt
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
font.italic = None # cause value to be inherited from theme
font.color.theme_color = MSO_THEME_COLOR.ACCENT_1
#加入超链接
run.hyperlink.address = 'https://github.com/scanny/python-pptx'
#设置颜色
font.color.rgb = RGBColor(0xFF, 0x7F, 0x50)

posted on   朝朝暮Mu  阅读(1002)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示