假定你有一个很无聊的任务,需要将几十个 PDF 文件合并成一个 PDF 文件。 每一个文件都有一个封面作为第一页,但你不希望合并后的文件中重复出现这些封面。即使有许多免费的程序可以合并 PDF,很多也只是简单的将文件合并在一起。让我们来写一个 Python 程序,定制需要合并到 PDF 中的页面。总的来说,该程序需要完成:
- 找到当前工作目录中所有 PDF 文件。
- 按文件名排序,这样就能有序地添加这些 PDF。
- 除了第一页之外,将每个 PDF 的所有页面写入输出的文件。
从实现的角度来看,代码需要完成下列任务:
- 调用 os.listdir(),找到当前工作目录中的所有文件,去除掉非 PDF 文件。
- 调用 Python 的 sort()列表方法,对文件名按字母排序。
- 为输出的 PDF 文件创建 PdfFileWriter 对象。
- 循环遍历每个 PDF 文件, 为它创建 PdfFileReader 对象。
- 针对每个 PDF 文件,循环遍历每一页,第一页除外。
- 将页面添加到输出的 PDF。
- 将输出的 PDF 写入一个文件,名为 allminutes.pdf。
针对这个项目,打开一个新的文件编辑器窗口,将它保存为 combinePdfs.py。
第 1 步:找到所有 PDF 文件
首先,程序需要取得当前工作目录中所有带.pdf 扩展名的文件列表,并对它们排序。让你的代码看起来像这样:
#! python3
# combinePdfs.py - Combines all the PDFs in the current working directory into
# a single PDF
import PyPDF2, os
# Get all the PDF filenames.
pdfFiles = []
for filename in os.listdir('.'):
if filename.endswith('.pdf'):
pdfFiles.append(filename)
pdfFiles.sort(key=str.lower)
pdfWriter = PyPDF2.PdfFileWriter()
# TODO: Loop through all the PDF files.
# TODO: Loop through all the pages (except the first) and add them.
# TODO: Save the resulting PDF to a file.
在#!行和介绍程序做什么的描述性注释之后,代码导入了 os 和 PyPDF2 模块。os.listdir('.')调用将返回当前工作目录中所有文件的列表。代码循环遍历这个列表,将带有.pdf 扩展名的文件添加到 pdfFiles 中。然后,列表按照字典顺序排序,调用 sort()时带有 key/str.lower 关键字参数。代码创建了一个 PdfFileWriter 对象,保存合并后的 PDF 页面。最后,一些注释语句简要描述了剩下的程序。
打开每个 PDF 文件
现在,程序必须读取 pdfFiles 中的每个 PDF 文件。 在程序中加入以下代码:
#! python3
# combinePdfs.py - Combines all the PDFs in the current working directory into
# a single PDF
import PyPDF2, os
# Get all the PDF filenames.
pdfFiles = []
--snip--
# Loop through all the PDF files.
for filename in pdfFiles:
pdfFileObj = open(filename, 'rb')
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
# TODO: Loop through all the pages (except the first) and add them.
# TODO: Save the resulting PDF to a file.
针对每个 PDF 文件,循环内的代码调用 open(),以'rb'作为第二个参数,用读二进制的模式打开文件。 open()调用返回一个 File 对象,它被传递给 PyPDF2.PdfFileReader(),创建针对那个 PDF 文件的 PdfFileReader 对象。
添加每一页
针对每个 PDF 文件,需要循环遍历每一页,第一页除外。在程序中添加以下代码:
#! python3
# combinePdfs.py - Combines all the PDFs in the current working directory into
# a single PDF
import PyPDF2, os
--snip--
# Loop through all the PDF files.
for filename in pdfFiles:
--snip--
# Loop through all the pages (except the first) and add them.
for pageNum in range(1, pdfReader.numPages):
pageObj = pdfReader.getPage(pageNum)
pdfWriter.addPage(pageObj)
# TODO: Save the resulting PDF to a file.
for 循环内的代码将每个 Page 对象拷贝到 PdfFileWriter 对象。要记住,你需要跳过第一页。因为 PyPDF2 认为 0 是第一页,所以循环应该从 1 开始,然后向上增长到 pdfReader.numPages 中的整数,但不包括它。
保存结果
在这些嵌套的 for 循环完成后, pdfWriter 变量将包含一个 PdfFileWriter 对象,合并了所有 PDF 的页面。最后一步是将这些内容写入硬盘上的一个文件。在程序中添加以下代码:
#! python3
# combinePdfs.py - Combines all the PDFs in the current working directory into
# a single PDF.
import PyPDF2, os
--snip--
# Loop through all the PDF files.
for filename in pdfFiles:
--snip--
# Loop through all the pages (except the first) and add them.
for pageNum in range(1, pdfReader.numPages):
--snip--
# Save the resulting PDF to a file.
pdfOutput = open('allminutes.pdf', 'wb')
pdfWriter.write(pdfOutput)
pdfOutput.close()
向 open()传入'wb',以写二进制的模式打开输出 PDF 文件 allminutes.pdf。然后,将得到的 File 对象传给 write()方法,创建实际的 PDF 文件。调用 close()方法,结束程序。
类似程序的想法
能够利用其他 PDF 文件的页面创建 PDF 文件,这让你的程序能完成以下任务:
- 从 PDF 文件中截取特定的页面。
- 重新调整 PDF 文件中页面的次序。
- 创建一个 PDF 文件,只包含那些具有特定文本的页面。文本由 extractText()来确定。
完整代码
#! python3
# combinePdfs.py - Combines all the PDFs in the current working directory into
# a single PDF
import PyPDF2, os
# Get all the PDF filenames.
pdfFiles = []
for filename in os.listdir('.'):
if filename.endswith('.pdf'):
pdfFiles.append(filename)
pdfFiles.sort(key=str.lower)
pdfWriter = PyPDF2.PdfFileWriter()
# Loop through all the PDF files.
for filename in pdfFiles:
pdfFileObj = open(filename, 'rb')
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
# Loop through all the pages (except the first) and add them.
for pageNum in range(1, pdfReader.numPages):
pageObj = pdfReader.getPage(pageNum)
pdfWriter.addPage(pageObj)
# Save the resulting PDF to a file.
pdfOutput = open('allminutes.pdf', 'wb')
pdfWriter.write(pdfOutput)
pdfOutput.close()