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

效果展示

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

相关推荐
小咖自动剪辑9 小时前
Base64与图片互转工具增强版:一键编码/解码,支持多格式
人工智能·pdf·word·媒体
TracyDemo14 小时前
excel 透视图怎么进行删除透视图
excel
骆驼爱记录14 小时前
Excel邮件合并嵌入图片技巧
自动化·word·excel·wps·新人首发
avi911116 小时前
Unity Data Excel读取方法+踩坑记;和WPS Excel的一些命令
unity·游戏引擎·excel·wps·data
梦幻通灵17 小时前
Excel多个sheet合并透视表实现方案【持续更新】
excel
开开心心就好17 小时前
键盘映射工具改键位,绿色版设置后重启生效
网络·windows·tcp/ip·pdf·计算机外设·电脑·excel
恬淡如雪18 小时前
Excel接口测试自动化实战
爬虫·python·excel
大模型RAG和Agent技术实践18 小时前
突破RAG边界:构建能“读懂“PPT逻辑与图文的智能问答系统实战(附完整源代码)
大模型·powerpoint·智能问答·rag
盘古工具18 小时前
PPT怎么放映?新手也能快速上手
powerpoint
取个鸣字真的难18 小时前
简单快速的用 Claude Code 帮你创建 PPT 生成 Skills
vscode·powerpoint·ai编程