使用Python進行批量操作PPT的示例詳解
將一份PPT的每一頁字體、大小、是否加粗都統(tǒng)一,是一個常見需求。特別是字體統(tǒng)一是高頻、熱點需求。在python操控PPT常用庫python-pptx中有一個bug,對字體的修改只能修改數(shù)字和英文字母,無法修改漢字。即 run.font.namet屬性只能修改英文和數(shù)字,并且 run.font.name識別的也是英文和數(shù)字的名稱。如文本框中英文和數(shù)字是’Arial’漢字是宋體,則會返回’Arial’。因為這個包,沒有針對漢字的API,而且這個包很久沒更新了,開發(fā)者提供了解決思路是修改office文件的底層xml來實現(xiàn),修改xml中的a:ea的typeface屬性,網(wǎng)上已經(jīng)有人用 pptx_ea_font 這個包實現(xiàn)了該功能。
首先安裝對應的包
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、圖形、圖表、表格的漢字還不能修改,需要下一步增加該功能
函數(shù)如下:
def change_ppt_font(ppt_file, new_font,new_size=None,bold=None,line_spacing=None): # 打開PPT文件 presentation = Presentation(ppt_file) # 循環(huán)遍歷每個slide for slide in presentation.slides: # 循環(huán)遍歷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) #以下方法只能修改數(shù)字和英文 #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 ' 直接遍歷組合圖形內(nèi)的子形狀 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
二、PPT轉(zhuǎn)Word—將文本框中的字都放到word里
from pptx import Presentation from docx import Document def extract_text_from_shape(shape): text = "" if hasattr(shape, "text"): text += shape.text + " " elif shape.shape_type == 6: # 6 corresponds to GROUP_SHAPE for subshape in shape.shapes: text += extract_text_from_shape(subshape) return text def ppt_to_word(presentation_path, output_path): # 打開PPT presentation = Presentation(presentation_path) # 創(chuàng)建Word文檔 doc = Document() # 遍歷PPT中的每一張幻燈片 for slide in presentation.slides: # 提取幻燈片的文本內(nèi)容 slide_text = "" for shape in slide.shapes: slide_text += extract_text_from_shape(shape) # 在Word文檔中插入文本內(nèi)容 doc.add_paragraph(slide_text) # 保存Word文檔 doc.save(output_path) if __name__ == '__main__': s = r"" t = r"" ppt_to_word(s, t)
三、PPT插入圖片和修改位置
1、Python PPT插入圖片 —推薦
1、使用get_image_list(img_dir)函數(shù)獲取PPT文件路徑列表,方便對列表操作以控制插入PPT的圖片的順序,如對列表進行翻轉(zhuǎn)、排序等,可以讓圖片反序、按一定序列插入PPT。
2、使用create_ppt_with_images函數(shù)將圖片插入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')] # 你可以根據(jù)需要修改這里,只選擇你需要的圖片格式 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]) # 使用標題和內(nèi)容布局,你可以根據(jù)需要選擇其他布局 # 設置圖片位置和大小,使其鋪滿整個幻燈片 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 要插入的圖片數(shù)量 numPicturePerSlide = 1 '用這個變量設置是否在頁數(shù)不足時自動添加新的 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 '循環(huán)每個頁面 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庫來實現(xiàn),會設計頁面內(nèi)容復制等,非常麻煩
使用win32com.client實現(xiàn)
2、使用new_ppt.SaveAs而不是Save 方法。Save 方法并不接受路徑作為參數(shù);它默認會在 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繪制復雜圖形
- 通過在紙上手繪或者drawio中畫系統(tǒng)框圖,然后把圖片傳給多模態(tài)大模型
- 讓大模型生成ppt圖形Python代碼
- 運行代碼生成圖形
1、插入矩形
from pptx import Presentation from pptx.util import Inches, Pt from pptx.enum.shapes import MSO_SHAPE from pptx.dml.color import RGBColor # 創(chuàng)建一個新的空白ppt presentation = Presentation() # 創(chuàng)建一個新的幻燈片 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、將矩形改為三維的
Sub ConvertRectanglesTo3D() Dim slide As slide Dim shape As shape Dim iDepth As Integer ' 設定三維深度,可根據(jù)需要調(diào)整 ' 選擇要處理的幻燈片,這里以當前幻燈片為例 Set slide = Application.ActiveWindow.View.slide ' 設置三維深度 iDepth = 50 ' 示例值,可以根據(jù)需要調(diào)整 ' 遍歷幻燈片上的所有形狀 For Each shape In slide.Shapes ' 檢查形狀是否為矩形 If shape.Type = msoShapeRectangle Then ' 應用三維格式 With shape.ThreeD .Visible = True .Depth = iDepth ' 可以根據(jù)需要調(diào)整其他三維屬性,例如旋轉(zhuǎn)角度等 End With End If Next shape MsgBox "完成!所有矩形已轉(zhuǎn)換為三維。" End Sub
3、畫系統(tǒng)框圖
from pptx import Presentation from pptx.util import Inches, Pt from pptx.enum.shapes import MSO_SHAPE from pptx.dml.color import RGBColor from pptx.enum.text import PP_ALIGN def hex_to_rgb(hex_color): """Converts a hex color string to an RGBColor object.""" hex_color = hex_color.lstrip('#') return RGBColor(*tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))) def single_line(presentation, slide, box_contents, box_height, total_length, start_position, color,fontname= 'Microsoft YaHei' ): # 設置方框的總長度和高度 total_length_in = Inches(total_length) box_height_in = Inches(box_height) # 計算每個方框的寬度 num_boxes = len(box_contents) box_width_in = total_length_in / num_boxes # 設置線條顏色為白色 line_color = RGBColor(255, 255, 255) # 判斷顏色輸入類型并轉(zhuǎn)換為RGBColor if isinstance(color, str) and color.startswith('#'): fill_color = hex_to_rgb(color) elif isinstance(color, (tuple, list)) and len(color) == 3: fill_color = RGBColor(*color) else: raise ValueError("Invalid color format") # 設置起始位置 start_left = Inches(start_position[0]) start_top = Inches(start_position[1]) # 循環(huán)添加方框 for i, content in enumerate(box_contents): # 計算當前方框的位置 left = start_left + i * box_width_in top = start_top # 在幻燈片上添加矩形形狀 shape = slide.shapes.add_shape( MSO_SHAPE.RECTANGLE, left, top, box_width_in, box_height_in ) # 設置填充顏色 fill = shape.fill fill.solid() fill.fore_color.rgb = fill_color # 設置線條顏色 line = shape.line line.color.rgb = line_color line.width = Pt(1) # 添加文本到方框內(nèi)并設置居中對齊 if content: tf = shape.text_frame p = tf.paragraphs[0] p.text = content p.alignment = PP_ALIGN.CENTER # 添加字體設置 run = p.runs[0] font = run.font font.name =fontname # 設置字體為微軟雅黑 #font.size = Pt(14) # 可以根據(jù)需要調(diào)整字體大小 # 創(chuàng)建多行矩形 #rectangle_rows 配置字典, step = 0.2每行之間的間隔是0.2英寸 def multi_line(rectangle_rows, step,output_filename='example.pptx'): presentation = Presentation() slide_layout = presentation.slide_layouts[6] slide = presentation.slides.add_slide(slide_layout) y_offset = 0 for row_id, row_config in rectangle_rows.items(): start_position = (row_config['start_position'][0], row_config['start_position'][1] - y_offset) single_line(presentation, slide, row_config['box_contents'], row_config['box_height'], row_config['total_length'], start_position, row_config['color']) y_offset += row_config['box_height'] + step print("確保無同文件路徑PPT打開") presentation.save(output_filename) if __name__ == "__main__": # 定義一個字典,用于存儲每一行的配置, """ #1表示是第一行 1: { # 每個矩形內(nèi)顯示的內(nèi)容列表 'box_contents': ['Box 1', 'Box 2', 'Box 3', 'Box 4'], # 每個矩形的高度(單位通常是英寸) 'box_height': 0.8, # 整行矩形的總長度(單位通常是英寸),這決定了矩形的寬度和它們之間的間距 'total_length': 8, # 該行第一個矩形的起始位置坐標(x, y),單位是英寸 # x坐標是水平方向的位置,y坐標是垂直方向的位置 'start_position': (1.4, 1.4), # 矩形的填充顏色,使用十六進制顏色代碼 'color': '#1ABC9C' # 這是一種淺綠色 }, """ rectangle_rows ={ 1: { 'box_contents': ['Box 1', 'Box 2', 'Box 3', 'Box 4'], 'box_height': 0.8, 'total_length': 8, 'start_position': (1, 4.8), 'color': '#1ABC9C' }, 2: { 'box_contents': ['Box 1', 'Box 2', 'Box 3', 'Box 4', 'Box 5'], 'box_height': 0.8, 'total_length': 8, 'start_position': (1, 4.8), 'color': '#00cc99' }, 3: { 'box_contents': ['Box 1', 'Box 2', 'Box 3', 'Box 4', 'Box 5'], 'box_height': 0.8, 'total_length': 8, 'start_position': (1, 4.8), 'color': '#009dc4' }, 4: { 'box_contents': ['Box 1', 'Box 2', 'Box 3', 'Box 4', 'Box 5'], 'box_height': 0.8, 'total_length': 8, 'start_position': (1, 4.8), 'color': '#0d98ba' }, 5: { 'box_contents': ['Box 1', 'Box 2', 'Box 3', 'Box 4', 'Box 5'], 'box_height': 0.8, 'total_length': 8, 'start_position': (1, 4.8), 'color': '#00c5cd' }, 6: { 'box_contents': ['Box 1', 'Box 2', 'Box 3', 'Box 4', 'Box 5'], 'box_height': 0.8, 'total_length': 8, 'start_position': (1, 4.8), 'color': '#00ced1' } } #每行的間隔 step = 0.05 multi_line(rectangle_rows, step ,output_filename='系統(tǒng)框圖.pptx')
六、PPT修改標題文本框的格式
用母版修改最合適,但是母版修改完之后總有部分框不改變格式,通感python 定位標題文本框
判斷標題的邏輯為:獲取第一個文本框且位于頂端(距離頂端小于頁面的1/20)。
from pptx import Presentation from pptx.util import Pt from pptx.enum.text import PP_ALIGN from pptx.dml.color import RGBColor def modify_ppt_title_format(ppt_path, font_name, font_size, font_color): """ 修改PPT文件中所有幻燈片標題的格式。 參數(shù): ppt_path (str): PPT文件的路徑。 font_name (str): 標題字體。 font_size (int): 字號。 font_color (tuple): 顏色RGB值。 """ # 打開現(xiàn)有的PPT文件 presentation = Presentation(ppt_path) # 獲取幻燈片的高度 slide_height = presentation.slide_height top_threshold = slide_height / 20 # 定義頂端的閾值 # 遍歷每一張幻燈片 for slide in presentation.slides: # 查找標題形狀(通常第一個形狀是標題) if slide.shapes: first_shape = slide.shapes[0] if first_shape.has_text_frame and first_shape.text.strip(): # 確保形狀有文本框并且不為空 # 檢查第一個形狀是否位于頂端 if first_shape.top < top_threshold: text_frame = first_shape.text_frame if len(text_frame.paragraphs) > 0: # 確保段落存在 paragraph = text_frame.paragraphs[0] # 假設標題是第一個段落 # 修改文本內(nèi)容(可選) # paragraph.text = "新的標題" # 如果需要修改標題文本,取消注釋這行 # 設置字體大小、顏色等屬性 for run in paragraph.runs: font = run.font font.name = font_name # 更改字體 font.size = Pt(font_size) # 更改字號 font.color.rgb = RGBColor(*font_color) # 設置顏色 # 設置對齊方式(可選) paragraph.alignment = PP_ALIGN.CENTER # 居中對齊 # 保存修改后的PPT到一個新的文件 modified_ppt_path = 'modifiedppt.pptx' presentation.save(modified_ppt_path) print(f"PPT已保存至:{modified_ppt_path}") PATH=r" " # 示例調(diào)用 modify_ppt_title_format(PATH, font_name='Arial', font_size=36, font_color=(0, 0, 0))
七、基礎知識
1、prs.slide_layouts[6]指定幻燈片布局,其中slide_layouts[6]是第6種布局,是一個白板。
以上就是使用Python進行批量操作PPT的示例詳解的詳細內(nèi)容,更多關(guān)于Python操作PPT的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python協(xié)程操作之gevent(yield阻塞,greenlet),協(xié)程實現(xiàn)多任務(有規(guī)律的交替協(xié)作執(zhí)行)用法詳解
這篇文章主要介紹了Python協(xié)程操作之gevent(yield阻塞,greenlet),協(xié)程實現(xiàn)多任務(有規(guī)律的交替協(xié)作執(zhí)行)用法,結(jié)合實例形式較為詳細的分析了協(xié)程的功能、原理及gevent、greenlet實現(xiàn)協(xié)程,以及協(xié)程實現(xiàn)多任務相關(guān)操作技巧,需要的朋友可以參考下2019-10-10Python實現(xiàn)關(guān)鍵路徑和七格圖計算詳解
這篇文章主要為大家詳細介紹了如何利用Python實現(xiàn)關(guān)鍵路徑和七格圖計算,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起了解一下2023-03-03