Pawan_Malviya
Pawan_Malviya

Reputation: 53

Inserting and formatting text in existing placeholder

I have a slide template that has a text placeholder. How do I insert and format text in that specific text placeholder ?

text_ph1 = slide1.placeholders[14]
text_ph2 = slide1.placeholders[15]

para1 = ['Text for para 1']
para2 = ['Text for para 2']

p = text_ph1.paragraphs[0]
run = p.add_run()
run.text = para1[0]

font = run.font
font.name = 'Calibri'
font.size = Pt(14)
font.bold = False
font.italic = None

AttributeError                            Traceback (most recent call last)
<ipython-input-205-ce3eb19a0d8b> in <module>
      2 text_frame.clear()  # not necessary for newly-created shape
      3 
----> 4 p = text_ph1.paragraphs[0]
      5 run = p.add_run()
      6 run.text = para1[0]

AttributeError: 'SlidePlaceholder' object has no attribute 'paragraphs'

Upvotes: 4

Views: 3806

Answers (2)

scanny
scanny

Reputation: 28863

A placeholder is a shape, mostly like any other auto-shape (rectangle, text-box, circle, etc.).

To access the text of the shape, use its .text_frame property to retrieve its TextFrame object. The TextFrame object has the paragraphs (not the shape directly) so something like this should work:

text_ph1 = slide1.placeholders[14]
text_ph1.text_frame.text = "Text for para 1"

If you then want to format the text you added, you'll find it in the first run of the first paragraph:

font = text_ph1.text_frame.paragraphs[0].runs[0].font
font.name = 'Calibri'
font.size = Pt(14)
font.bold = False
font.italic = False

Upvotes: 4

umn
umn

Reputation: 471

Hope I understood your question.

example:

from pptx import Presentation

prs = Presentation()
title_slide_layout = prs.slide_layouts[0]
slide = prs.slides.add_slide(title_slide_layout)
title = slide.shapes.title
subtitle = slide.placeholders[1]

title.text = "Text for para 1"
subtitle.text = "Text for para 2"

prs.save('test.pptx')

Upvotes: -1

Related Questions