目录
将一份PPT的每一页字体、大小、是否加粗都统一,是一个常见需求。特别是字体统一是高频、热点需求。在python操控PPT常用库python-pptx中有一个bug,对字体的修改只能修改数字和英文字母,无法修改汉字。即 run.font.namet
属性只能修改英文和数字,并且 run.font.name
识别的也是英文和数字的名称。如文本框中英文和数字是'Arial'汉字是宋体,则会返回'Arial'。因为这个包,没有针对汉字的API,而且这个包很久没更新了,开发者提供了解决思路是修改office文件的底层xml来实现,修改xml中的a:ea的typeface属性,网上已经有人用 pptx_ea_font 这个包实现了该功能。
首先安装对应的包
pptx和docx的包为,注意不是pptx和docx
pip install python-pptx
pip install python-docx
pptx_ea_font 安装方法为
pip install pptx_ea_font
导入相应模块
from pptx import Presentation
import pptx_ea_font
from docx import Document
from pptx.util import Cm, Pt
一、修改PPT中每一页的字体
1、可以修改字体、大小、是否加粗
2、图形、图表、表格的汉字还不能修改,需要下一步增加该功能
函数如下:
#修改字体类型和大小
def change_ppt_font(ppt_file, new_font,new_size=None,bold=None):
# 打开PPT文件
presentation = Presentation(ppt_file)
# 循环遍历每个slide
for slide in presentation.slides:
# 循环遍历slide中的每个shape
for shape in slide.shapes:
# 检查shape类型是否为文本框
if shape.has_text_frame:
# 获取文本框中的文字
text_frame = shape.text_frame
for paragraph in text_frame.paragraphs:
for run in paragraph.runs:
# 修改字体
pptx_ea_font.set_font(run,new_font)
#以下方法只能修改数字和英文
#run.font.name = new_font
if new_size :
run.font.size = Pt(new_size)
if bold is not None:
run.font.bold = bold
# 保存修改后的PPT文件
new_ppt_file = ppt_file.replace(".pptx", "_new.pptx")
presentation.save(new_ppt_file)
print("字体修改完毕!")
以上代码只能修改文本框,如果要修改图形中的字体需要用VBA。alt+F11 插入模块,复制以下代码 按F5
代码来自 TomasZh
注意:以下代码依然不能修改 图表 chart中的文本
Sub SetAllFontToYahei()
''' set all fonts to 微软雅黑
Dim sld As Slide
Dim shp As Shape, chd As Shape
Dim i&, j&
For Each sld In ActivePresentation.Slides
i = i + 1
Debug.Print "Slide " & i
For Each shp In sld.Shapes
j = j + 1
Debug.Print vbTab & "Shape " & j
If shp.Type = msoGroup Then
For Each chd In shp.GroupItems
If chd.HasTextFrame Then
chd.TextFrame.TextRange.Font.Name = "微软雅黑"
chd.TextFrame.TextRange.Font.NameFarEast = "微软雅黑"
End If
Next
ElseIf shp.HasTextFrame Then
shp.TextFrame.TextRange.Font.Name = "微软雅黑"
shp.TextFrame.TextRange.Font.NameFarEast = "微软雅黑"
End If
Next
Next
MsgBox "Task completed!"
End Sub
二、将文本框中的字都放到word里
def extract_text_from_ppt(ppt_file, word_file):
# 打开PPT文件
presentation = Presentation(ppt_file)
# 创建新的Word文档
word_doc = Document()
# 循环遍历每个slide
for slide in presentation.slides:
# 循环遍历slide中的每个shape
for shape in slide.shapes:
# 检查shape类型是否为文本框
if shape.has_text_frame:
# 获取文本框中的文字
text_frame = shape.text_frame
for paragraph in text_frame.paragraphs:
# 提取文本到Word中
word_doc.add_paragraph(paragraph.text)
# 保存Word文档
word_doc.save(word_file)
print("文本提取完毕!")