Created
April 2, 2025 16:24
-
-
Save WaterLemons2k/a7b64ae704d0031d7e700441d41523ac to your computer and use it in GitHub Desktop.
Replace text fonts in pptx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from pptx import Presentation | |
| def replace_font_in_text_frame(text_frame, old_font, new_font): | |
| for paragraph in text_frame.paragraphs: | |
| for run in paragraph.runs: | |
| if run.font.name == old_font: | |
| run.font.name = new_font | |
| def replace_font_in_pptx(pptx_file, old_font, new_font, output): | |
| # 打开PPT文件 | |
| presentation = Presentation(pptx_file) | |
| # 替换幻灯片中的字体 | |
| for slide in presentation.slides: | |
| for shape in slide.shapes: | |
| if shape.has_text_frame: | |
| replace_font_in_text_frame(shape.text_frame, old_font, new_font) | |
| # 替换母版中的字体 | |
| for slide_master in presentation.slide_master.shapes: | |
| if slide_master.has_text_frame: | |
| replace_font_in_text_frame(slide_master.text_frame, old_font, new_font) | |
| for slide_layout in presentation.slide_master.slide_layouts: | |
| for shape in slide_layout.shapes: | |
| if shape.has_text_frame: | |
| replace_font_in_text_frame(shape.text_frame, old_font, new_font) | |
| # 保存修改后的PPT | |
| presentation.save(output) | |
| # 使用示例 | |
| input = "input.pptx" | |
| output = "output.pptx" | |
| old_font = "微软雅黑" | |
| new_font = "思源黑体 CN" | |
| replace_font_in_pptx(input, old_font, new_font, output) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment