4

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'
sanyassh
  • 8,100
  • 13
  • 36
  • 70
Pawan_Malviya
  • 53
  • 1
  • 4

2 Answers2

4

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
scanny
  • 26,423
  • 5
  • 54
  • 80
  • Thanks @scanny . This worked. You should include these as tips on the tutorials page. – Pawan_Malviya May 01 '19 at 09:52
  • Welcome to StackOverflow Pawan_Malviya, glad you got it working :) Don't neglect to accept this answer if it answered your question. That's how the StackOverflow economy works :) – scanny May 01 '19 at 16:38
-1

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')
umn
  • 431
  • 6
  • 17