吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 2022|回复: 5
收起左侧

[Python 原创] 【Python】从 Word 文档中提取图片并生成 PPT

[复制链接]
zhzhx 发表于 2025-4-1 16:49
[Python] 纯文本查看 复制代码
from docx import Document
from pptx import Presentation
from pptx.util import Inches
from PIL import Image
import io
import os

# 指定包含 Word 文件的文件夹路径
folder_path = r"C:\Users\Administrator\Desktop\tt"  # 修改为你的文件夹路径

# 遍历文件夹中的所有 Word 文件
for filename in os.listdir(folder_path):
    if filename.endswith(".docx"):
        word_path = os.path.join(folder_path, filename)
        ppt_name = os.path.splitext(filename)[0] + ".pptx"
        ppt_path = os.path.join(folder_path, ppt_name)

        print(f"正在处理:{filename}")

        try:
            # 尝试读取Word文件
            doc = Document(word_path)

        except Exception as e:
            print(f"❌ 无法读取文件 {filename}: {e}")
            continue  # 跳过当前文件,处理下一个

        # 创建PPT演示文稿
        prs = Presentation()

        # 提取图片并插入PPT
        for para in doc.paragraphs:
            for run in para.runs:
                blip = run._r.find('.//a:blip', namespaces={'a': 'http://schemas.openxmlformats.org/drawingml/2006/main'})
                if blip is not None:
                    embed_id = blip.get('{[url]http://schemas.openxmlformats.org/officeDocument/2006/relationships[/url]}embed')
                    if embed_id and embed_id in run.part.related_parts:
                        image_part = run.part.related_parts[embed_id]
                        img_stream = io.BytesIO(image_part.blob)

                        # 打开图片
                        img = Image.open(img_stream)
                        img_width, img_height = img.size

                        # 创建PPT幻灯片
                        slide = prs.slides.add_slide(prs.slide_layouts[6])

                        # 设置PPT大小与图片尺寸一致
                        prs.slide_width = Inches(img_width / 100)
                        prs.slide_height = Inches(img_height / 100)

                        # 将图片添加到幻灯片
                        slide.shapes.add_picture(img_stream, 0, 0, width=Inches(img_width / 100), height=Inches(img_height / 100))

        # 保存PPT
        prs.save(ppt_path)
        print(f"✅ 生成PPT:{ppt_path}")

print("所有文件处理完成!🎯")

免费评分

参与人数 3吾爱币 +7 热心值 +3 收起 理由
苏紫方璇 + 5 + 1 欢迎分析讨论交流,吾爱破解论坛有你更精彩!
laozhang4201 + 1 + 1 谢谢@Thanks!
taoguo666 + 1 + 1 谢谢@Thanks!

查看全部评分

发帖前要善用【论坛搜索】功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

yxf515321 发表于 2025-4-1 19:49
sktao 发表于 2025-4-1 17:20
看着很简单啊   是不是能生产模板和格式那样的

应该是用ai写的,有需要的话,你可以根据你的需求,利用ai优化这段代码
qq123667 发表于 2025-4-1 22:07
crystalZ 发表于 2025-4-1 22:40
ma5635 发表于 2025-4-1 23:18
都有word了 直接自己整图片就是,难的是在需要合适的PPT模板
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - 52pojie.cn ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2026-10-24 03:15

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表