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

Viewed 2599

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
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.

The font attribute can not be assigned directly in python-pptx. You can only assign attributes of the font attribute itself, like size, name, etc. That's why you get the AttributeError.

In general, if you want to replace text in a PowerPoint presentation while keeping the character formats, you need to replace the text on the run level because that is, where the character formats are ultimately stored (there is also a default font on paragraph level and another on text_frame level, and those are the ones used, if you assign the text at paragraph- or text_frame level).

The problem with replacing text in a PowerPoint presentation is, that any text can be distributed over any number of paragraph runs, thus looking for a specific text must be done on text_frame or paragraph level, but it must be replaced on run-level.

Using the package python-pptx-text-replacer installable through

python -m pip install python-pptx-text-replacer

will allow you to do that easily either on command line or using the class TextReplacer in that package in your own Python scripts.

Related