使用Python合并多个pdf文件

342 阅读1分钟

PyPDF2 是一个功能虽然不是很多,但却非常好用的第三方库,它提供了pdf文件的读写,拆分,合并等功能.

  1. 使用os.listdir方法获取制定目录下的所有pdf文件名称
  2. 使用os.path.join方法拼接成绝对路径
  3. 创建PdfFileMerger对象,这是专门用来合并pdf文件的对象
  4. 将所有文件append
  5. 最后,使用write方法将所有pdf文件写入到一个文件

 

使用pip命令进行安装

pip install PyPDF2

 

运行代码

import os
from PyPDF2 import PdfFileMerger

target_path = 'D:\\test\\pdf'
pdf_lst = [f for f in os.listdir(target_path) if f.endswith('.pdf')]    #寻找该目录下所有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("D:\\test\\merge.pdf")