假定你有一个很无聊的任务,需要将几十个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 # 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页面❹。最后,一些注释语句简要描述了剩下的程序。
第2步:打开每个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(),以'wb'作为第二个参数,用读二进制的模式打开文件。open()调用返回一个 File 对象,它被传递给PyPDF2.PdfFileReader(),创建针对那个PDF文件的PdfFileReader对象。
第3步:添加每一页
针对每个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中的整数,但不包括它。
第4步:保存结果
在这些嵌套的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()方法,结束程序。
第5步:类似程序的想法
能够利用其他PDF文件的页面创建PDF文件,这让你的程序能完成以下任务:
- 从PDF文件中截取特定的页面。
- 重新调整PDF文件中页面的次序。
- 创建一个PDF文件,只包含那些具有特定文本的页面。文本由extractText()来确定。