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

效果展示

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

相关推荐
不写八个4 小时前
Python办公自动化教程(005):Word添加段落
开发语言·python·word
一个散步者的梦5 小时前
Excel常用函数
excel
bin915314 小时前
【EXCEL数据处理】000009 案列 EXCEL单元格数字格式。文本型数字格式和常规型数字格式的区别
大数据·前端·数据库·信息可视化·数据分析·excel·数据可视化
GEEKVIP16 小时前
如何修复变砖的手机并恢复丢失的数据
macos·ios·智能手机·word·手机·笔记本电脑·iphone
Eiceblue1 天前
Python保留数据删除Excel单元格的函数和公式
开发语言·python·excel
bin91531 天前
【EXCEL数据处理】000014 案例 EXCEL分类汇总、定位和创建组。附多个操作案例。
信息可视化·数据挖掘·数据分析·excel·数据可视化·数据图表·excel 数据分析
育种数据分析之放飞自我1 天前
GWAS分析中显著位点如何注释基因:excel???
linux·算法·excel
PowerBI学谦1 天前
Python in Excel 正式发布!
开发语言·python·excel
bin91531 天前
【EXCEL数据处理】000011 案列 EXCEL带有三角形图标的单元格转换,和文本日期格式转换。
大数据·数据库·信息可视化·数据挖掘·数据分析·excel·数据可视化
股票程序交易接口1 天前
股票接口api,如何用excel获得股票实时数据
excel·量化交易·股票api接口·股票量化接口·python股票接口·股票实时数据