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

效果展示

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

相关推荐
Evan芙10 小时前
用fping编写脚本扫描10.0.0.0/24网段在线主机
linux·运维·网络·excel
CodeCraft Studio12 小时前
纯前端文档编辑组件——Spire.WordJS全新发布
前端·javascript·word·office·spire.wordjs·web文档编辑·在线文档编辑器
风萧萧199912 小时前
Java:PPT转图片
java·python·powerpoint
dagouaofei15 小时前
年终总结PPT用AI最快生成
人工智能·python·powerpoint
SamDeepThinking15 小时前
基于CompletableFuture的主子任务并行处理架构实战:多渠道账单并发导入性能提升5倍的技术方案
java·后端·excel
SamDeepThinking15 小时前
88MB Excel文件导致系统崩溃?看我如何将内存占用降低
java·excel
伟贤AI之路15 小时前
原创分享:Markdown 转 Word 工具,一键导出Word/PDF文档
pdf·word·markdown·markdown转
爱吃山竹的大肚肚16 小时前
使用 poi-tl 生成 Word 文档并上传到 Minio
word
EAIReport16 小时前
AI自动生成PPT报告产品技术实现与应用案例
人工智能·powerpoint
ChrisitineTX16 小时前
警惕数据“陷阱”:Python 如何自动发现并清洗 Excel 中的异常值?
开发语言·python·excel