浅浅写一个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()

效果展示

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

相关推荐
小真zzz12 小时前
2025-2026年AI PPT工具排行榜:ChatPPT的全面领先与竞品格局解析
人工智能·ai·powerpoint·ppt·aippt
gc_229913 小时前
学习C#调用OpenXml操作word文档的基本用法(17:学习文档图片类)
c#·word·图片·openxml
一晌小贪欢13 小时前
Python 对象的“Excel 之旅”:使用 openpyxl 高效读写与封装实战
开发语言·python·excel·表格·openpyxl·python办公·读取表格
开开心心_Every13 小时前
手机端课程表管理工具:支持课程导入自定义
python·游戏·微信·django·pdf·excel·语音识别
weixin_4624462314 小时前
Python 实战:Tkinter 实现 ZIP 中 CSV 批量转换为 Excel(支持密码 + 编码自动识别 + 进度条)
python·excel·csv转xlsx
开开心心_Every14 小时前
视频无损压缩工具:大幅减小体积并保持画质
游戏·微信·pdf·excel·音视频·语音识别·tornado
开开心心_Every15 小时前
安卓语音转文字工具:免费支持实时转换视频
python·游戏·微信·django·pdf·excel·语音识别
Goona_16 小时前
PyQt+Excel学生信息管理系统,增删改查全开源
python·小程序·自动化·excel·交互·pyqt
2501_9307077816 小时前
使用C#代码在 Word 文档页面中添加装订线
开发语言·c#·word
miaobinfei16 小时前
pdf转word,图片文字转word(使用OCR工具)
pdf·ocr·word