Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep original text formatting of text with python powerpoint?

I'd like to update the text within a textbox without changing the formatting. In other words, I'd like to keep the original formatting of the original text while changing that text

I can update the text with the following, but the formatting is changed completely in the process.

from pptx import Presentation
prs = Presentation("C:\\original_powerpoint.pptx")
sh = prs.slides[0].shapes[0]
sh.text_frame.paragraphs[0].text = 'MY NEW TEXT'
prs.save("C:\\new_powerpoint.pptx")

How can I update the text while maintaining the original formatting?

I've also tried the following:

from pptx import Presentation
prs = Presentation("C:\\original_powerpoint.pptx")
sh = prs.slides[0].shapes[0]
p = sh.text_frame.paragraphs[0]
original_font = p.font
p.text = 'NEW TEXT'
p.font = original_font

However I get the following error:

Traceback (most recent call last):
  File "C:\Codes\powerpoint_python_script.py", line 24, in <module>
    p.font = original_font
AttributeError: can't set attribute
like image 260
Chris Avatar asked Sep 15 '25 16:09

Chris


2 Answers

Text frame consists of paragraphs and paragraphs consists of runs. So you need to set text in run. enter image description here

Probably you have only one run and your code can be changed like that:

from pptx import Presentation
prs = Presentation("C:\\original_powerpoint.pptx")
sh = prs.slides[0].shapes[0]
sh.text_frame.paragraphs[0].runs[0].text = 'MY NEW TEXT'
prs.save("C:\\new_powerpoint.pptx")

Character formatting (font characteristics) are specified at the Run level. A Paragraph object contains one or more (usually more) runs. When assigning to Paragraph.text, all the runs in the paragraph are replaced with a single new run. This is why the text formatting disappears; because the runs that contained that formatting disappear.

like image 100
Ignis Avatar answered Sep 18 '25 06:09

Ignis


Use the petpptx package, this is an updated fork of python-pptx

python -m pip install petpptx

Saved previous font style

font_style= text_frame.paragraphs[0].runs[0].font
text_frame.clear()
run = text_frame.paragraphs[0].add_run()
run.font = font_style
run.text = "Hello World"

Copied font

font_style= text_frame.paragraphs[0].runs[0].font
text_frame.paragraphs[0].runs[1].font = deepcopy(font_style)

like image 24
Sergey Malygin Avatar answered Sep 18 '25 05:09

Sergey Malygin