python处理pdf文件我们需要一个第三方库PyPDF2

PyPDF2是一个功能虽然不是很多,但却非常好用的第三方库,它提供了pdf文件的读写,拆分,合并等功能,使用pip命令进行安装。

安装PyPDF2

pip3 install PyPDF2

合并pdf文件代码

import os
from PyPDF2 import PdfFileMerger

target_path = '/Users/kwsy/Desktop'
pdf_lst = [f for f in os.listdir(target_path) if f.endswith('.pdf')]
pdf_lst = [os.path.join(target_path, filename) for filename in pdf_lst]

file_merger = PdfFileMerger()
for pdf in pdf_lst:
    file_merger.append(pdf)     # 合并pdf文件

file_merger.write("/Users/kwsy/Desktop/merge.pdf")

使用os.listdir方法获取制定目录下的所有pdf文件名称

使用os.path.join方法拼接成绝对路径

创建PdfFileMerger对象,这是专门用来合并pdf文件的对象

将所有文件append

最后,使用write方法将所有pdf文件写入到一个文件