目录
将一份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代码库—修改文本框和图表字体为微软雅黑和1.5倍(常用)
以下代码更全面可以修改表格和图形的,但是不能修改图表的和文本框聚合的图形中的文字。
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
Dim oGroup As Shapes
Dim oChildShape As Shape
' 遍历演示文稿中的所有幻灯片
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 = "微软雅黑"
'.Size = 14
'.Color.RGB = RGB(255, 0, 0)
'.Bold = True
.Italic = False
.Underline = False
End With
' 行距1.5
oTxtRange.ParagraphFormat.SpaceWithin = 1.5
End If
' 如果形状是组合图形
If oShape.Type = msoGroup Then
' 直接遍历组合图形内的子形状
For i = 1 To oShape.GroupItems.Count
Set oChildShape = oShape.GroupItems.Item(i)
' 如果子形状包含文本框
If oChildShape.HasTextFrame Then
Set oTxtRange = oChildShape.TextFrame.TextRange
' 设置文本框中文本的字体属性
With oTxtRange.Font
.Name = "微软雅黑"
'.Size = 14
'.Color.RGB = RGB(255, 0, 0)
'.Bold = True
.Italic = False
.Underline = False
End With
' 行距1.5
oTxtRange.ParagraphFormat.SpaceWithin = 1.5
End If
Next i
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 = "微软雅黑"
'.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里
from pptx import Presentation
from docx import Document
def ppt_to_word(presentation_path, output_path):
# 打开PPT
presentation = Presentation(presentation_path)
# 创建Word文档
doc = Document()
# 遍历PPT中的每一张幻灯片
for slide in presentation.slides:
# 提取幻灯片的文本内容
slide_text = ""
for shape in slide.shapes:
if hasattr(shape, "text"):
slide_text += shape.text + " "
# 在Word文档中插入文本内容
doc.add_paragraph(slide_text)
# 保存Word文档
doc.save(output_path)
print("转化完毕")
if __name__ == '__main__':
#,以上代码仅针对PPT中的文本内容进行转换,其他类型的内容(如图片、表格等)不能转化,需要使用ocr
s=r"xx.pptx"
t=r"xx"
ppt_to_word(s, t)
三、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
的方式获取幻灯片的大小,然后按比例输入图片的大小。
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
四、合并文件夹下多个ppt
注意:
1、不能用pptx库来实现,会设计页面内容复制等,非常麻烦
使用win32com.client实现
2、使用new_ppt.SaveAs而不是Save 方法。Save 方法并不接受路径作为参数;它默认会在 PowerPoint 打开时指定的默认位置保存文件。
import win32com.client as win32
import os
import re
def merge_ppt(path:str):
"""
:param path: ppt所在文件路径
:return: None
"""
files = os.listdir(path)
Application = win32.gencache.EnsureDispatch("PowerPoint.Application")
Application.Visible = 1
new_ppt = Application.Presentations.Add()
for file in files:
abs_path = os.path.join(path, file)
exit_ppt = Application.Presentations.Open(abs_path)
print(abs_path)
page_num = exit_ppt.Slides.Count
exit_ppt.Close()
new_ppt.Slides.InsertFromFile(abs_path, new_ppt.Slides.Count, 1, page_num)
new_ppt.SaveAs(os.path.join(path, 'merged.pptx')) # 保存在C:\Users\Administrator\Documents\下
Application.Quit()
path=r"C:\xx"
merge_ppt(path)
五、PPT中插入形状中的图形—Python绘制复杂图形
1、通过在纸上手绘或者drawio中画系统框图,然后把图片传给多模态大模型
2、让大模型生成ppt图形Python代码
3、运行代码生成图形
1、插入矩形
from pptx import Presentation
from pptx.util import Inches, Pt
from pptx.enum.shapes import MSO_SHAPE
from pptx.dml.color import RGBColor
# 创建一个新的空白ppt
presentation = Presentation()
# 创建一个新的幻灯片
slide_layout = presentation.slide_layouts[0]
slide = presentation.slides.add_slide(slide_layout)
# 在幻灯片上添加一个矩形形状
left = top = Inches(1)
width = height = Inches(2)
shape = slide.shapes.add_shape(
MSO_SHAPE.RECTANGLE,
left, top, width, height
)
# 设置矩形形状的填充颜色和轮廓线颜色
fill = shape.fill
fill.solid()
fill.fore_color.rgb = RGBColor(0x00, 0x00, 0x00) # 黑色
line = shape.line
line.color.rgb = RGBColor(0xFF, 0x00, 0x00) # 红色
line.width = Pt(3) # 设置轮廓线的宽度
# 保存ppt文件
presentation.save('example.pptx')
2、使用VBA插入矩形—推荐
使用在需要16进制的颜色画多个框的时候。
生成 n个方框,高1,长5,填充色1abcd9,方框没有边框
Sub AddRectangles()
Dim pptSlide As Slide
Dim shp As Shape
Dim i As Integer
Dim leftPos As Single
Dim topPos As Single
Dim rectWidth As Single
Dim rectHeight As Single
Dim fillColor As Long
'方框的数量
n = 4
' 设置方框的宽度和高度
lg = 5 ' long方框的长
hg = 1 ' high方框的高
rectWidth = 5 * 28.35 ' 5英寸转换为EMUs(英制单位)
rectHeight = 1 * 28.35 ' 1英寸转换为EMUs(英制单位)
' 假设的十六进制颜色值
hexColor = "1ABCD9"
' 转换十六进制颜色为RGB
r = CDec("&H" & Left(hexColor, 2))
g = CDec("&H" & Mid(hexColor, 3, 2))
b = CDec("&H" & Right(hexColor, 2))
' 设置填充颜色的RGB值
fillColor = RGB(r, g, b) ' 1abcd9的RGB值
' 添加新幻灯片
Set pptSlide = ActivePresentation.Slides.Add(1, ppLayoutBlank)
' 设置方框的初始水平位置,这里假设从幻灯片左侧开始
leftPos_s = 100
' 设置方框的垂直位置,这里假设从幻灯片顶部开始
topPos = 100
' 循环添加10个方框
For i = 0 To n
' 设置方框的垂直位置,这里假设从幻灯片顶部开始,每个方框间隔10英寸
leftPos = i * rectWidth
' 加上初始位置
leftPos = leftPos + leftPos_s
' 在幻灯片上添加矩形形状
Set shp = pptSlide.Shapes.AddShape(msoShapeRectangle, leftPos, topPos, rectWidth, rectHeight)
' 设置填充颜色
With shp.Fill
.ForeColor.RGB = fillColor
.Visible = msoTrue
End With
' 设置线条颜色为蓝色,这里使用RGB颜色值
shp.Line.ForeColor.RGB = RGB(255, 255, 255)
Next i
End Sub
3、将矩形改为三维的
Sub ConvertRectanglesTo3D()
Dim slide As slide
Dim shape As shape
Dim iDepth As Integer ' 设定三维深度,可根据需要调整
' 选择要处理的幻灯片,这里以当前幻灯片为例
Set slide = Application.ActiveWindow.View.slide
' 设置三维深度
iDepth = 50 ' 示例值,可以根据需要调整
' 遍历幻灯片上的所有形状
For Each shape In slide.Shapes
' 检查形状是否为矩形
If shape.Type = msoShapeRectangle Then
' 应用三维格式
With shape.ThreeD
.Visible = True
.Depth = iDepth
' 可以根据需要调整其他三维属性,例如旋转角度等
End With
End If
Next shape
MsgBox "完成!所有矩形已转换为三维。"
End Sub
六、基础知识
1、prs.slide_layouts[6]指定幻灯片布局,其中slide_layouts[6]是第6种布局,是一个白板。