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)