使用Python将Word文档中的图片提取并生成PowerPoint幻灯片

在这篇博客中,我们将学习如何使用Python将Word文档中的图片提取出来并生成一个PowerPoint幻灯片。我们将借助wxPython、python-docx和python-pptx这三个强大的库来实现这一目标。以下是实现这个功能的完整过程。
C:\pythoncode\new\wordTOppt.py

所需库

首先,我们需要安装以下Python库:

  • wxPython:用于创建图形用户界面(GUI)。
  • python-docx:用于处理Word文档。
  • python-pptx:用于生成PowerPoint幻灯片。

你可以通过以下命令安装这些库:

pip install wxPython python-docx python-pptx
创建GUI

我们将使用wxPython创建一个简单的GUI,让用户选择一个Word文档,并点击按钮来执行图片提取和PPT生成的过程。以下是实现这个功能的代码:

import wx
import os
import docx
from pptx import Presentation
from pptx.util import Inches, Pt

class MyFrame(wx.Frame):
    def __init__(self, parent, title):
        super(MyFrame, self).__init__(parent, title=title, size=(600, 300))
        self.panel = wx.Panel(self)
        self.create_widgets()

    def create_widgets(self):
        vbox = wx.BoxSizer(wx.VERTICAL)
        self.file_picker = wx.FilePickerCtrl(self.panel, message="选择 Word 文档", wildcard="Word files (*.docx)|*.docx")
        vbox.Add(self.file_picker, 0, wx.ALL | wx.EXPAND, 5)
        self.extract_button = wx.Button(self.panel, label="提取并生成幻灯片")
        self.extract_button.Bind(wx.EVT_BUTTON, self.on_extract)
        vbox.Add(self.extract_button, 0, wx.ALL | wx.EXPAND, 5)
        self.panel.SetSizer(vbox)

    def on_extract(self, event):
        word_file_path = self.file_picker.GetPath()
        if not os.path.exists(word_file_path):
            wx.MessageBox("文件未找到!", "错误", wx.OK | wx.ICON_ERROR)
            return

        # Create images directory to store extracted images
        images_dir = os.path.join(os.path.dirname(word_file_path), 'images')
        if not os.path.exists(images_dir):
            os.makedirs(images_dir)

        # Extract images from Word document
        try:
            doc = docx.Document(word_file_path)
            for r_id, rel in doc.part.rels.items():
                if str(rel.target_ref).startswith('media') or str(rel.target_ref).startswith('embeddings'):
                    file_suffix = str(rel.target_ref).split('.')[-1:][0].lower()
                    if file_suffix not in ['png', 'jpg', 'jpeg', 'gif', 'bmp']:
                        continue
                    file_name = r_id + '_' + str(rel.target_ref).replace('/', '_')
                    file_path = os.path.join(images_dir, file_name)
                    with open(file_path, "wb") as f:
                        f.write(rel.target_part.blob)
                    print('Extracted image:', file_name)
        except Exception as e:
            wx.MessageBox(f"Error extracting images: {str(e)}", "Error", wx.OK | wx.ICON_ERROR)
            return

        # Create PowerPoint presentation from extracted images
        try:
            ppt = Presentation()
            slide_width = ppt.slide_width
            slide_height = ppt.slide_height
            for filename in os.listdir(images_dir):
                if filename.endswith((".png", ".jpg", ".jpeg", ".gif", ".bmp")):
                    image_path = os.path.join(images_dir, filename)
                    slide = ppt.slides.add_slide(ppt.slide_layouts[6])  # Use a blank slide layout
                    picture = slide.shapes.add_picture(image_path, Inches(0), Inches(0), height=slide_height)
                    
                    # Scale and center the picture
                    picture_width = picture.width
                    picture_height = picture.height
                    max_picture_width = slide_width - Inches(1)
                    max_picture_height = slide_height - Inches(1)
                    scale_ratio = min(max_picture_width / picture_width, max_picture_height / picture_height)
                    new_picture_width = int(picture_width * scale_ratio)
                    new_picture_height = int(picture_height * scale_ratio)
                    picture.left = (slide_width - new_picture_width) // 2
                    picture.top = (slide_height - new_picture_height) // 2
                    picture.width = new_picture_width
                    picture.height = new_picture_height

            ppt_file_path = os.path.splitext(word_file_path)[0] + '.pptx'
            ppt.save(ppt_file_path)
            wx.MessageBox(f"幻灯片生成成功!PPT 已保存到 {ppt_file_path}", "成功", wx.OK | wx.ICON_INFORMATION)
        except Exception as e:
            wx.MessageBox(f"Error creating PPT: {str(e)}", "Error", wx.OK | wx.ICON_ERROR)

if __name__ == '__main__':
    app = wx.App(False)
    frame = MyFrame(None, "Word to PPT Converter")
    frame.Show()
    app.MainLoop()

代码解析

初始化和创建GUI

我们首先创建了一个wxPython的框架(Frame),并在其中添加了一个面板(Panel)。然后,我们在面板上添加了文件选择器和按钮。

class MyFrame(wx.Frame):
    def __init__(self, parent, title):
        super(MyFrame, self).__init__(parent, title=title, size=(600, 300))
        self.panel = wx.Panel(self)
        self.create_widgets()
创建控件

我们使用了垂直布局(VBoxSizer),并在其中添加了文件选择器和按钮。

def create_widgets(self):
    vbox = wx.BoxSizer(wx.VERTICAL)
    self.file_picker = wx.FilePickerCtrl(self.panel, message="选择 Word 文档", wildcard="Word files (*.docx)|*.docx")
    vbox.Add(self.file_picker, 0, wx.ALL | wx.EXPAND, 5)
    self.extract_button = wx.Button(self.panel, label="提取并生成幻灯片")
    self.extract_button.Bind(wx.EVT_BUTTON, self.on_extract)
    vbox.Add(self.extract_button, 0, wx.ALL | wx.EXPAND, 5)
    self.panel.SetSizer(vbox)
提取图片

在用户选择Word文档并点击按钮后,我们提取其中的图片。我们遍历Word文档中的所有关系项,查找指向图片的关系,并将图片保存到 images 目录中。

def on_extract(self, event):
    word_file_path = self.file_picker.GetPath()
    if not os.path.exists(word_file_path):
        wx.MessageBox("文件未找到!", "错误", wx.OK | wx.ICON_ERROR)
        return

    images_dir = os.path.join(os.path.dirname(word_file_path), 'images')
    if not os.path.exists(images_dir):
        os.makedirs(images_dir)

    try:
        doc = docx.Document(word_file_path)
        for r_id, rel in doc.part.rels.items():
            if str(rel.target_ref).startswith('media'):
                file_suffix = str(rel.target_ref).split('.')[-1:][0].lower()
                if file_suffix not in ['png', 'jpg', 'jpeg', 'gif', 'bmp']:
                    continue
                file_name = r_id + '_' + str(rel.target_ref).replace('/', '_')
                file_path = os.path.join(images_dir, file_name)
                with open(file_path, "wb") as f:
                    f.write(rel.target_part.blob)
                print('Extracted image:', file_name)
    except Exception as e:
        wx.MessageBox(f"Error extracting images: {str(e)}", "Error", wx.OK | wx.ICON_ERROR)
        return
创建PPT文档

我们使用 python-pptx 创建一个新的PPT文档,并将提取的图片插入到幻灯片中。每张图片占据一张幻灯片,并居中显示。

try:
    ppt = Presentation()
    slide_width = ppt.slide_width
    slide_height = ppt.slide_height
    for filename in os.listdir(images_dir):
        if filename.endswith((".png", ".jpg", ".jpeg", ".gif", ".bmp")):
            image_path = os.path.join(images_dir, filename)
            slide = ppt.slides.add_slide(ppt.slide_layouts[6])  # Use a blank slide layout
            picture = slide.shapes.add_picture(image_path, Inches(0), Inches(0), height=slide_height)
            
            picture_width = picture.width
            picture_height = picture.height
            max_picture_width = slide_width - Inches(1)
            max_picture_height = slide_height - Inches(1)
            scale_ratio = min(max_picture_width / picture_width, max_picture_height / picture_height)
            new_picture_width = int(picture_width * scale_ratio)
            new_picture_height = int(picture_height * scale_ratio)
            picture.left = (slide_width - new_picture_width) // 2
            picture.top = (slide_height - new_picture_height) // 2
            picture.width = new_picture_width
            picture.height = new_picture_height

    ppt_file_path = os.path.splitext(word_file_path)[0] + '.pptx'
    ppt.save(ppt_file_path)
    wx.MessageBox(f"幻灯片生成成功!PPT 已保存到 {ppt_file_path}", "成功", wx.OK | wx.ICON_INFORMATION)
except Exception as e:
    wx.MessageBox

(f"Error creating PPT: {str(e)}", "Error", wx.OK | wx.ICON_ERROR)

效果如下:

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

总结

通过本文,你已经学会了如何使用Python提取Word文档中的图片并生成一个包含这些图片的PowerPoint幻灯片。wxPython为我们提供了一个用户友好的界面,python-docx使我们能够轻松地处理Word文档,而python-pptx则让我们能够方便地创建和操作PPT文档。希望这篇博客能对你有所帮助!如果你有任何问题或建议,欢迎留言讨论。

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 可以使用 python-docx 库来读取 word 文档并提取标题。可以先安装这个库: ``` pip install python-docx ``` 然后使用下面的代码来读取文档并提取标题: ```python import docx def extract_titles(filepath): doc = docx.Document(filepath) titles = [] for para in doc.paragraphs: if para.style.name.startswith('Heading'): titles.append(para.text) return titles titles = extract_titles('document.docx') print(titles) ``` 提取出来的标题可以通过生成目录的方式展示出来 ### 回答2: Python可以使用python-docx库来提取Word文档的标题,并生成目录。 首先,我们需要安装python-docx库。可以使用以下命令来安装: ``` pip install python-docx ``` 接下来,我们需要打开Word文档并读取其内容。可以使用以下代码来实现: ```python from docx import Document # 打开Word文档 doc = Document('example.docx') # 读取文档标题 titles = [] for paragraph in doc.paragraphs: if paragraph.style.name == 'Heading 1': titles.append(paragraph.text) # 输出标题 for title in titles: print(title) ``` 上述代码根据标题的样式名称为“Heading 1”来提取标题,如果需要提取其他样式的标题,只需相应地修改代码的样式名称即可。 接下来,我们可以使用提取到的标题来生成目录。可以使用以下代码来实现: ```python from docx import Document # 打开Word文档 doc = Document('example.docx') # 插入目录 doc.add_paragraph('目录', 'Heading 1') # 插入标题及页码 for paragraph in doc.paragraphs: if paragraph.style.name == 'Heading 1': doc.add_paragraph(paragraph.text, 'TOC Heading') doc.add_paragraph(str(doc.paragraphs.index(paragraph)+1), 'TOC Page Number') # 保存文档 doc.save('example_with_toc.docx') ``` 上述代码,我们首先插入一个标题为“目录”的段落,然后根据提取到的标题逐一插入到目录,并对应地添加页码。 最后,我们使用save方法保存生成的带有目录的Word文档。 以上就是使用PythonWord文档提取标题并生成目录的方法。通过使用python-docx库,我们可以方便地进行自动化处理,提高效率。 ### 回答3: Python可以使用Python-docx库来从Word文档提取标题并生成目录。 首先,我们需要安装Python-docx库,可以使用pip命令进行安装。在命令行输入以下命令: ``` pip install python-docx ``` 安装完成后,我们可以导入Python-docx库并加载Word文档。可以使用`Document()`函数来加载文档,传入Word文档的文件路径作为参数: ```python from docx import Document document = Document('路径/文档名.docx') ``` 接下来,我们可以使用`paragraphs`属性来获取文档的所有段落,然后判断每个段落是否是标题。通常,在Word文档,标题拥有不同的样式或带有特定的格式。因此,我们可以通过检查段落的样式或格式来判断是否是标题。 一种常见的方法是使用段落的`style`属性。如果一个段落的样式是标题样式,那么我们可以判断它是一个标题。可以通过`paragraph.style.name`来获取段落的样式名称。 然后,我们可以将提取到的标题添加到目录。可以创建一个空的列表来存储标题,并使用`add_heading()`函数将标题添加到目录。 下面是一个简单的示例代码,该代码使用Python-docx库从Word文档提取标题并生成目录: ```python from docx import Document def generate_table_of_contents(doc_path): document = Document(doc_path) table_of_contents = [] for paragraph in document.paragraphs: if paragraph.style.name.startswith('Heading'): table_of_contents.append(paragraph.text) document.add_heading(paragraph.text) document.save('目录.docx') ``` 上述代码的`generate_table_of_contents()`函数接受一个字符串参数`doc_path`,该参数为Word文档的路径。函数会逐个检查文档的段落,识别出标题并将其添加到目录。 最后,我们可以调用`generate_table_of_contents()`函数并传入Word文档的路径,以生成包含标题的目录。生成的目录将保存为一个新的Word文档文件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值