问题:
尽管在 Python 中使用
Spire.Presentation
库,迭代每个 SmartArt 形状节点,并尝试修改字体属性,但 PowerPoint 演示文稿中的 SmartArt 形状内的字体并未按预期被替换。
任何人都可以提供见解或替代方法来使用 Python 和
Spire.Presentation
库成功替换 SmartArt 形状中的字体吗?
使用的库:Spire.Presentation
该库提供了在 Python 中处理 PowerPoint 演示文稿的功能。
方法:
使用
Spire.Presentation.
打开 PowerPoint 演示文稿
迭代演示文稿中的每张幻灯片。
对于每张幻灯片,迭代每个形状。
根据形状类型识别 SmartArt 形状。
访问每个 SmartArt 形状内的节点。 访问每个节点内的文本内容和字体属性。 检查是否需要更换字体。如果是这样,请将其替换为所需的字体。 保存修改后的演示文稿。
代码亮点:
使用 spire.presentation.Presentation 打开和操作 PowerPoint 演示文稿。 使用幻灯片属性访问幻灯片。 使用 Shapes 属性访问幻灯片中的形状。 使用形状类型识别 SmartArt 形状(例如 shape.shape_type == 24)。
使用节点属性访问 SmartArt 形状中的节点。 使用适当的属性访问节点内的文本内容和字体属性。 根据需要替换字体。 使用 saveToFile() 方法保存修改后的演示文稿。 结果:
脚本无法成功修改 PowerPoint 演示文稿中 SmartArt 形状内的字体。 字体不会替换为所需的字体。 修改后的演示文稿将保存并应用更改。
我用过的库有python-pptx、spire.presentation、pptx_ea_font,但还是无法更改SmartArt中的中文、英文、数字的字体。
答案:
经过几天的调试和咨询AI,我发现以下代码片段是有效的。
import comtypes.client
import tkinter as tk
from tkinter import filedialog
def select_powerpoint_file():
root = tk.Tk()
root.withdraw() # Hide the root window
file_path = filedialog.askopenfilename(
title="選擇 PowerPoint 文件", filetypes=[("PowerPoint 文件", "*.pptx")]
)
return file_path
def save_powerpoint_file_as():
root = tk.Tk()
root.withdraw() # Hide the root window
file_path = filedialog.asksaveasfilename(
title="另存 PowerPoint 文件", filetypes=[("PowerPoint 文件", "*.pptx")]
)
return file_path
def modify_smartart_font(powerpoint_file):
try:
powerpoint = comtypes.client.CreateObject("PowerPoint.Application")
powerpoint.Visible = True
presentation = powerpoint.Presentations.Open(powerpoint_file)
for slide in presentation.Slides:
for shape in slide.Shapes:
if shape.HasSmartArt:
smartart = shape.SmartArt
for node in smartart.AllNodes:
# Convert the Unicode text to a byte string using UTF-8 encoding
text_bytes = node.TextFrame2.TextRange.Text.encode('utf-8')
# Modify the font name to Microsoft JhengHei for both English and Chinese characters
node.TextFrame2.TextRange.Font.NameFarEast = "微軟正黑體"
node.TextFrame2.TextRange.Font.NameAscii = "微軟正黑體"
# Convert the byte string back to Unicode text using UTF-8 decoding
node.TextFrame2.TextRange.Text = text_bytes.decode('utf-8')
new_file_path = save_powerpoint_file_as()
presentation.SaveAs(new_file_path)
except Exception as e:
print("發生錯誤:", e)
finally:
if 'presentation' in locals():
presentation.Close()
if 'powerpoint' in locals():
powerpoint.Quit()
if __name__ == "__main__":
powerpoint_file = select_powerpoint_file()
if powerpoint_file:
modify_smartart_font(powerpoint_file)
else:
print("未選擇 PowerPoint 文件.")