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

放肆的年华 提交于 2019-12-11 09:27:52

问题


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

回答1:


Text frame is consists of paragraphs and paragraphs is consists of runs. So you need to set text in run.

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.



来源:https://stackoverflow.com/questions/45247042/how-to-keep-original-text-formatting-of-text-with-python-powerpoint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!