用Python将Office文档(Word、Excel、PowerPoint)批量转换为PDF

在处理不同格式的Office文档(如Word、Excel和PowerPoint)时,将其转换为PDF格式是常见的需求。这种转换不仅确保了文件在不同设备和操作系统间的一致性显示,而且有助于保护原始内容不被轻易修改,非常适合于正式报告、提案或资料归档等场景。通过使用Python,开发者可以编写简洁高效的脚本来自动完成这些任务,满足企业或个人对于文档管理的需求。本文将介绍如何使用Python代码实现Word、Excel和PowerPoint文档到PDF文件的批量转换 ,同时提供用Python将Office文档合并转换为PDF的方法。

文章目录

本文所使用的方法需要用到Spire.Office for Python,PyPI:pip install spire.office

将Word、Excel和PowerPoint文档批量分别转换为PDF文档

我们可以通过判断文档的文件后缀名,然后将对应的文档分别用Document类(Word)、Workbook类(Excel)和Presentation类(PowerPoint)的LoadFromFile方法载入,再分别使用SaveToFile(string: fileName, FileFormat.PDF)方法转换并保存为PDF文档,从而实现Office文档到PDF文件的批量转换。以下是详细操作步骤:

  1. 导入所需模块。
  2. 定义要处理的文件夹路径,获取指定类型的文件并排序。
  3. 创建一个PdfDocument对象。
  4. 遍历文件列表的文件,根据后缀名判断文件类型。
  5. 根据文件类型创建DocumentWorkbookPresentation对象。
  6. 使用LoadFromFile方法载入文档。
  7. 使用SaveToFile方法将文档转换为PDF并保存。
  8. 释放资源。

代码示例

python 复制代码
from spire.pdf import PdfDocument
from spire.doc import Document
from spire.xls import Workbook
from spire.presentation import Presentation
from spire.doc import FileFormat as wFileFormat
from spire.xls import FileFormat as eFileFormat
from spire.presentation import FileFormat as pFileFormat
import os

# 定义要处理的文件夹路径
folderPath = "Documents/"
# 获取所有指定类型的文件并排序
extensions = [".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx"]
files = sorted([os.path.join(folderPath, f) for f in os.listdir(folderPath) if f.lower().endswith(tuple(extensions))])

# 创建一个PdfDocument对象
pdf = PdfDocument()

# 遍历文件列表
for file in files:
    extension = os.path.splitext(file)[1].lower()
    if extension in [".doc", ".docx"]:
        # 创建Document对象
        doc = Document()
        # 载入Word文档
        doc.LoadFromFile(file)
        # 将Word文档转换为PDF
        doc.SaveToFile(f"output/Documents/{os.path.basename(file)}.pdf", wFileFormat.PDF)
        doc.Close()
    if extension in [".xls", ".xlsx"]:
        # 创建Workbook对象
        workbook = Workbook()
        # 载入Excel文件
        workbook.LoadFromFile(file)
        # 将Excel文件转换为PDF
        workbook.SaveToFile(f"output/Documents/{os.path.basename(file)}.pdf", eFileFormat.PDF)
        workbook.Dispose()
    if extension in [".ppt", ".pptx"]:
        # 创建Presentation对象
        presentation = Presentation()
        # 载入PowerPoint文件
        presentation.LoadFromFile(file)
        # 将PowerPoint文件转换为PDF
        presentation.SaveToFile(f"output/Documents/{os.path.basename(file)}.pdf", pFileFormat.PDF)
        presentation.Dispose()

# 关闭PdfDocument对象
pdf.Close()

结果

将Word、Excel、PowerPoint和PDF文档合并转换为单个PDF

除了批量分别转换Office文档外,我们还可以将各种类型的文档合并转换到同一个PDF文件中。以下是操作步骤:

  1. 导入所需模块。
  2. 定义要处理的文件夹路径,获取指定类型的文件并排序。
  3. 创建一个PdfDocument对象pdf用于储存最终PDF文档。
  4. 创建一个新的PdfDocument对象temPdf和一个临时PDF文档地址用于转换出的临时PDF文档。
  5. 遍历文件列表的文件,根据后缀名判断文件类型。
  6. 根据文件类型创建DocumentWorkbookPresentation对象,并使用LoadFromFile方法载入文档。
  7. 使用SaveToFile方法将文档转换为PDF并保存到临时PDF路径。
  8. 使用temPdf.LoadFromFile()方法载入临时PDF,并使用pdf.AppendPage(temPdf)将其页面插入到最终PDF中。
  9. 处理完成后,使用pdf.SaveToFile()方法保存最终PDF文档。
  10. 清理临时文件并释放资源。

代码示例

python 复制代码
from spire.pdf import PdfDocument
from spire.doc import Document
from spire.xls import Workbook
from spire.presentation import Presentation
from spire.doc import FileFormat as wFileFormat
from spire.xls import FileFormat as eFileFormat
from spire.presentation import FileFormat as pFileFormat

import os

# 指定要处理的文件夹路径
folderPath = 'Documents/'
# 获取所有指定类型的文件并排序
extensions = ['.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx']
files = sorted([os.path.join(folderPath, f) for f in os.listdir(folderPath) if f.lower().endswith(tuple(extensions))])

# 创建一个PdfDocument对象
pdf = PdfDocument()
# 创建一个临时PDF和一个Stream对象
temPdf = PdfDocument()
temPdfPath = 'temp.pdf'

# 遍历文件列表
for file in files:
    extension = os.path.splitext(file)[1].lower()

    if extension in ['.doc', '.docx']:
        # 加载Word文档
        doc = Document()
        doc.LoadFromFile(file)
        # 保存为临时PDF
        doc.SaveToFile(temPdfPath, wFileFormat.PDF)
        # 载入临时PDF并将其页面添加到最终PDF中
        temPdf.LoadFromFile(temPdfPath)
        pdf.AppendPage(temPdf)
        doc.Close()  # 显式关闭文档

    elif extension in ['.xls', '.xlsx']:
        # 加载Excel工作簿
        workbook = Workbook()
        workbook.LoadFromFile(file)
        # 保存为临时PDF
        workbook.SaveToFile(temPdfPath, eFileFormat.PDF)
        # 载入临时PDF并将其页面添加到最终PDF中
        temPdf.LoadFromFile(temPdfPath)
        pdf.AppendPage(temPdf)
        workbook.Dispose()  # 显式关闭工作簿

    elif extension in ['.ppt', '.pptx']:
        # 加载PowerPoint演示文稿
        presentation = Presentation()
        presentation.LoadFromFile(file)
        # 保存为临时PDF
        presentation.SaveToFile(temPdfPath, pFileFormat.PDF)
        # 载入临时PDF并将其页面添加到最终PDF中
        temPdf.LoadFromFile(temPdfPath)
        pdf.AppendPage(temPdf)
        presentation.Dispose()  # 显式关闭演示文稿

    elif extension == '.pdf':
        # 如果已经是PDF,则直接载入并将其页面添加到最终PDF中
        temPdf.LoadFromFile(file)
        pdf.AppendPage(temPdf)

# 保存最终PDF
outputPath = "output/CombinedPDF.pdf"
pdf.SaveToFile(outputPath)

# 清理临时文件
if os.path.exists('temp.pdf'):
    os.remove('temp.pdf')

# 释放资源
pdf.Close()
temPdf.Close()

结果

本文演示了如何使用Python将Word、Excel和PowerPoint文档批量分别转换为PDF文档,以及将它们合并转换为单个PDF。Spire.Office for Python还支持进行许多其他格式的转换,请前往官网了解。

申请免费License

相关推荐
扯淡的闲人5 分钟前
多语言编码Agent解决方案(2)-后端服务实现
开发语言·python·深度学习
蒋星熠8 分钟前
深度学习实战指南:从神经网络基础到模型优化的完整攻略
人工智能·python·深度学习·神经网络·机器学习·卷积神经网络·transformer
烦躁的大鼻嘎25 分钟前
【Linux】深入Linux多线程架构与高性能编程
linux·运维·服务器·开发语言·c++·ubuntu
野生的编程萌新28 分钟前
【C++深学日志】C++编程利器:缺省参数、函数重载、引用详解
c语言·开发语言·c++
Slaughter信仰31 分钟前
深入理解Java虚拟机:JVM高级特性与最佳实践(第3版)第十三章知识点问答(15题)
java·开发语言·jvm
万粉变现经纪人38 分钟前
如何解决pip安装报错ModuleNotFoundError: No module named ‘cuml’问题
python·scrapy·beautifulsoup·pandas·ai编程·pip·scipy
IT学长编程40 分钟前
计算机毕业设计 基于Hadoop豆瓣电影数据可视化分析设计与实现 Python 大数据毕业设计 Hadoop毕业设计选题【附源码+文档报告+安装调试
大数据·hadoop·python·django·毕业设计·毕业论文·豆瓣电影数据可视化分析
java1234_小锋1 小时前
Scikit-learn Python机器学习 - 分类算法 - K-近邻(KNN)算法
python·算法·机器学习
大翻哥哥1 小时前
Python上下文管理器进阶指南:不仅仅是with语句
前端·javascript·python
小柯J桑_1 小时前
C++之特殊类设计
java·开发语言·c++