浅浅写一个Word、PowerPoint、Excel文档转PDF工具

前言

最近在搞知识库,需要把各种 Word、PowerPoint、Excel 文件转换成 PDF 文件,不然 Word 中的表格中的文字提取会出现一些问题;使用 Office 或者 WPS 将大量文件转换成 PDF 需要频繁重复打开文件,点击保存为PDF,然后再关闭,非常繁琐。所以就简单的写了下面的 Python 程序来帮助我转化。

代码

下面的程序需要使用开源 Office 工具 ------ libreoffice,安装该工具后才能使用下面的命令行才能使用 libreoffice 中的 PDF 转化功能将文档转化。

python 复制代码
import os
import subprocess
from pathlib import Path
from tkinter import Tk, filedialog, messagebox


def convert_to_pdf(input_file):
    try:
        # Get the directory of the input file
        input_dir = os.path.dirname(input_file)

        # Prepare output file path
        output_file = os.path.join(input_dir, Path(input_file).stem + '.pdf')

        # Convert to PDF using LibreOffice
        subprocess.run(['soffice', '--headless', '--convert-to', 'pdf', input_file, '--outdir', input_dir],
                       check=True)
        print(f"Converted {input_file} to {output_file}")
        return output_file
    except Exception as e:
        print(f"Error converting file {input_file}: {e}")
        return None


def select_files_and_convert():
    # Supported file extensions
    supported_extensions = [  ('files', '*.doc;*.docx;*.ppt;*.pptx;*.xls;*.xlsx'),
        ('Word files', '*.doc;*.docx'),
    ('PowerPoint files', '*.ppt;*.pptx'),
    ('Excel files', '*.xls;*.xlsx')]

    # Create Tkinter root window
    root = Tk()
    root.withdraw()  # Hide the root window

    # Open file dialog to select files
    files = filedialog.askopenfilenames(title="Select files to convert", filetypes=supported_extensions)

    if not files:
        messagebox.showinfo("No files selected", "No files were selected for conversion.")
        return

    # Convert selected files
    for file in files:
        output_file = convert_to_pdf(file)
        if output_file:
            # messagebox.showinfo("Success", f"Converted {file} to {output_file}")
            print(f"Converted {file} to {output_file}")        
        else:
            # messagebox.showerror("Error", f"Failed to convert {file}")
            print(f"Failed to convert {file}")


def main():
    select_files_and_convert()


if __name__ == "__main__":
    main()

效果展示

效果大致如下,点击运行后,就会弹出选择框,批量选择文件后,就会开始转化。

相关推荐
AI导出鸭PC端12 小时前
告别导出难题:AI 导出鸭助力 Claude 输出 excel 一站式实现
人工智能·ai·excel·豆包·ai导出鸭
许彰午13 小时前
75_Python自动化办公之Word与PDF
python·自动化·word
开开心心_Every13 小时前
带OCR识别的电子发票打印工具
运维·自动化·ocr·电脑·powerpoint·音视频·lua
绎奇PPT13 小时前
青拔申报全套服务丨文案逻辑梳理+高端PPT设计
信息可视化·powerpoint·ppt
Am-Chestnuts14 小时前
DeepSeek 表格如何导出 Word/Excel:Markdown 表格、CSV 与 DS随心转方案对比
word·excel
城数派15 小时前
2000-2026年我国省市县三级逐月NDVI数据(Shp/Excel格式)
excel
Am-Chestnuts15 小时前
AI 公式复制到 Word 乱码怎么办:LaTeX 转 Word 与 DS随心转方案对比
人工智能·word
Ar-Sr-Na1 天前
工作路演PPT处理,交给Workbuddy
人工智能·powerpoint·workbuddy开发者分享季
RZhLyRaHv1 天前
LangChain教程-4、构建简易智能 PPT 生成器
人工智能·langchain·powerpoint
许彰午1 天前
74_Python自动化办公之Excel操作
python·自动化·excel