将一份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中每一页的字体
Python修改
1、可以修改字体、大小、是否加粗
2、图形、图表、表格的汉字还不能修改,需要下一步增加该功能
函数如下:
def change_ppt_font(ppt_file, new_font,new_size=None,bold=None,line_spacing=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:
if line_spacing is not None:
paragraph.line_spacing = line_spacing
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("字体修改完毕!")
以上代码只能修改文本框,因为图形是个msogroup对象。如果要修改图形中的字体需要用VBA。alt+F11 插入模块,复制以下代码 按F5
代码来自网上已有代码的整合。
注意:以下代码依然不能修改 图表 chart中的文本
VBA修改,修改文本框和图表字体为微软雅黑(常用)
Sub SetTextFontToYahei()
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
End Sub
Sub ChangeTableFontInAllSlides()
Dim oSlide As Slide
Dim oShape As Shape
Dim oTable As Table
Dim oRow As Row
Dim oCell As Cell
Dim oTxtRange As TextRange
On Error Resume Next
For Each oSlide In ActivePresentation.Slides
For Each oShape In oSlide.Shapes
If oShape.HasTable Then ' 处理表格中的文本
Set oTable = oShape.Table
For Each oRow In oTable.Rows
For Each oCell In oRow.Cells
If oCell.Shape.HasTextFrame Then
Set oTxtRange = oCell.Shape.TextFrame.TextRange
With oTxtRange.Font
'──────────────────────────────
'修改为您所需的字体名称
.Name = "微软雅黑"
'.Size = 20 修改为您所需的字体大小
'.Color.RGB = RGB(255, 0, 0) 修改为您所需的字体颜色
'.Bold = True 修改为您所需的是否加粗
'.Italic = False 修改为您所需的是否倾斜
'.Underline = False 修改为您所需的是否有下划线
'──────────────────────────────
End With
End If
Next oCell
Next oRow
End If
Next oShape
Next oSlide
MsgBox "文本框和图表修改完成"
End Sub
VBA代码库
以下代码更全面可以修改表格和图形的,但是不能修改图表的和文本框聚合的图形中的文字。文章来源:https://www.toymoban.com/news/detail-716039.html
Sub ChangeFontInAllSlides()
Dim oSlide As Slide
Dim oShape As Shape
Dim oTable As Table
Dim oRow As Row
Dim oCell As Cell
Dim oTxtRange As TextRange
On Error Resume Next
For Each oSlide In ActivePresentation.Slides
For Each oShape In oSlide.Shapes
If oShape.HasTextFrame Then ' 处理文本框中的文本
Set oTxtRange = oShape.TextFrame.TextRange
With oTxtRange.Font
'──────────────────────────────
.Name = "Arial" ' 修改为您所需的字体名称
.Size = 20 ' 修改为您所需的字体大小
.Color.RGB = RGB(255, 0, 0) ' 修改为您所需的字体颜色
.Bold = True ' 修改为您所需的是否加粗
.Italic = False ' 修改为您所需的是否倾斜
.Underline = False ' 修改为您所需的是否有下划线
'──────────────────────────────
End With
End If
If oShape.HasTable Then ' 处理表格中的文本
Set oTable = oShape.Table
For Each oRow In oTable.Rows
For Each oCell In oRow.Cells
If oCell.Shape.HasTextFrame Then
Set oTxtRange = oCell.Shape.TextFrame.TextRange
With oTxtRange.Font
'──────────────────────────────
.Name = "Arial" ' 修改为您所需的字体名称
.Size = 20 ' 修改为您所需的字体大小
.Color.RGB = RGB(255, 0, 0) ' 修改为您所需的字体颜色
.Bold = True ' 修改为您所需的是否加粗
.Italic = False ' 修改为您所需的是否倾斜
.Underline = False ' 修改为您所需的是否有下划线
'──────────────────────────────
End With
End If
Next oCell
Next oRow
End If
Next oShape
Next oSlide
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("文本提取完毕!")
三、PPT插入图片和修改位置
1、Python PPT插入图片 —推荐
1、使用get_image_list(img_dir)
函数获取PPT文件路径列表,方便对列表操作以控制插入PPT的图片的顺序,如对列表进行翻转、排序等,可以让图片反序、按一定序列插入PPT。
2、使用create_ppt_with_images
函数将图片插入PPT,其中slide.shapes.add_picture(img_file, left, top, width, height)
代码进行插入,img_file是要插入的图片, left, top, width, height是插入的坐标和大小,left, top表示插入位置,手工设定。 width, height是插入图片的大小,可以手工设定也可以通过 width ,height = prs.slide_width, prs.slide_height
的方式获取幻灯片的大小,然后按比例输入图片的大小。文章来源地址https://www.toymoban.com/news/detail-716039.html
import os
from pptx import Presentation
from pptx.util import Inches
def get_image_list(img_dir):
"""
读取文件夹中的图片文件名并返回一个列表。
"""
img_files = os.listdir(img_dir)
img_path = [os.path.join(img_dir, f) for f in img_files if f.endswith('.jpg') or f.endswith('.png')] # 你可以根据需要修改这里,只选择你需要的图片格式
return img_path
def create_ppt_with_images(img_list, output_ppt_path):
"""
将给定的图片列表按顺序插入到一个新的PPT演示文稿中。
"""
prs = Presentation()
for i, img_file in enumerate(img_list):
slide = prs.slides.add_slide(prs.slide_layouts[6]) # 使用标题和内容布局,你可以根据需要选择其他布局
# 设置图片位置和大小,使其铺满整个幻灯片
left = top = 0
width ,height = prs.slide_width, prs.slide_height
pic = slide.shapes.add_picture(img_file, left, top, width, height)
prs.save(output_ppt_path)
if __name__ == '__main__':
# 请将 'path_to_your_images' 替换为你的图片文件夹路径,将 'output.pptx' 替换为你想要保存PPT的路径和文件名
path_img=r"xx"
path_out=r"output.pptx"
list_img=get_image_list(path_img)
create_ppt_with_images(list_img,path_out)
2、VBA PPT插入图片
Sub InsertPicturesToPPT()
Dim sld As Slide
Dim shp As Shape
Dim i, count, numPicturePerSlide, curSlide As Long
Dim slideWidth, slideHeight As Single
Dim autoAddSlide As Boolean
curSlide = ActiveWindow.View.Slide.SlideIndex
'用这个变量设置每页 PPT 要插入的图片数量
numPicturePerSlide = 1
'用这个变量设置是否在页数不足时自动添加新的 PPT 页来插入所有选中的图片,设置为 False 来取消该功能
autoAddSlide = True
fd = Split(FileDialogOpen, vbLf)
If Left(fd(0), 1) = "-" Then
Debug.Print "Canceled"
Exit Sub
End If
slideWidth = ActivePresentation.PageSetup.slideWidth
slideHeight = ActivePresentation.PageSetup.slideHeight
If autoAddSlide Then
If (ActivePresentation.Slides.count - curSlide + 1) * numPicturePerSlide < UBound(fd) - LBound(fd) + 1 Then
total = Int((UBound(fd) - LBound(fd) + 1) / numPicturePerSlide - ActivePresentation.Slides.count + curSlide - 1 + 0.5)
For i = ActivePresentation.Slides.count + 1 To ActivePresentation.Slides.count + total
' 在末尾添加空白页
'ActivePresentation.Slides.Add i, ppLayoutBlank
' 在当前页之后添加空白页
' ActivePresentation.Slides.Add curSlide, ppLayoutBlank
' ActivePresentation.Slides(curSldie - 1).Select
' 在当前页之后复制当前页
ActivePresentation.Slides(curSlide).Duplicate
Next i
End If
End If
count = 0
For Each sld In ActivePresentation.Slides
' 跳过隐藏的 PPT 页,并跳过在当前页之前的页
Debug.Print sld.SlideIndex & " >= " & curSlide
If sld.SlideShowTransition.Hidden = msoFalse And sld.SlideIndex >= curSlide Then
If count + LBound(fd) > UBound(fd) Then
' No picture to insert
Exit For
End If
For i = 1 To numPicturePerSlide
If count + LBound(fd) <= UBound(fd) Then
Set shp = sld.Shapes.AddPicture( _
FileName:=fd(count + LBound(fd)), _
LinkToFile:=msoFalse, _
SaveWithDocument:=msoTrue, _
Left:=0, _
Top:=0, _
Width:=-1, _
Height:=-1 _
)
With shp
.LockAspectRatio = msoTrue ' 锁定纵横比
'.ScaleHeight 0.75, msoTrue
.Left = slideWidth / numPicturePerSlide * i - .Width / 2
.Top = (slideHeight - .Height) / 2
'.ZOrder msoSendToBack ' 将图片设置为最底层
End With
count = count + 1
Else
Exit For
End If
Next i
End If
Next sld
'MsgBox "Processing finished. Inserted (" & count & ") pictures in total"
MsgBox "插入图片完成,共插入 " & count & " 张图片"
End Sub
Function FileDialogOpen() As String
#If Mac Then
' 默认路径
mypath = MacScript("return (path to desktop folder) as String")
sMacScript = "set applescript's text item delimiters to "","" " & vbNewLine & _
"try " & vbNewLine & _
"set theFiles to (choose file of type {""png"", ""jpg"", ""jpeg"", ""svg"", ""tiff"", ""gif""}" & _
"with prompt ""请选择一个或多个要插入的图片"" default location alias """ & _
mypath & """ multiple selections allowed true)" & vbNewLine & _
"set applescript's text item delimiters to """" " & vbNewLine & _
"on error errStr number errorNumber" & vbNewLine & _
"return errorNumber " & vbNewLine & _
"end try " & vbNewLine & _
"repeat with i from 1 to length of theFiles" & vbNewLine & _
"if i = 1 then" & vbNewLine & _
"set fpath to POSIX path of item i of theFiles" & vbNewLine & _
"else" & vbNewLine & _
"set fpath to fpath & """ & vbNewLine & _
""" & POSIX path of item i of theFiles" & vbNewLine & _
"end if" & vbNewLine & _
"end repeat" & vbNewLine & _
"return fpath"
FileDialogOpen = MacScript(sMacScript)
#Else
With Application.FileDialog(msoFileDialogOpen)
.AllowMultiSelect = True
.Title = "请选择要一个或多个要插入的图片"
.Filters.Add "图片", "*.png; *.jpg; *.jpeg; *.svg; *.tiff; *.gif", 1
If .Show = -1 Then
FileDialogOpen = ""
For i = 1 To .SelectedItems.count
If i = 1 Then
FileDialogOpen = .SelectedItems.Item(i)
Else
FileDialogOpen = FileDialogOpen & vbLf & .SelectedItems.Item(i)
End If
Next
Else
FileDialogOpen = "-"
End If
End With
#End If
End Function
3、PPT中图片修改位置
Sub test()
'获取所有ppt页面
For Each currentSlide In ActivePresentation.Slides '循环每个页面
For Each shp In currentSlide.Shapes
'type = 13是图片 17是文本框
If shp.Type = 13 Then
shp.Top = 10 '设置top位置
shp.Left = 10 '设置left位置
shp.Height = 10000 '设置图片高度位置
shp.Width = 600
End If
Next shp
Next currentSlide
End Sub
到了这里,关于使用Python批量修改PPT字体和提取全部文字到word的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!