使用python将多份pdf文件合并

道锋潜鳞
2021-09-16 / 0 评论 / 93 阅读 / 正在检测是否收录...

为了搞定这件事情,没少百度,下载了软件,或者使用在线工具,折腾很久才能搞定。

刚想使用WPS来合并,结果给我弹出这样的:

怎么可能有那闲钱开通哪

不过,想起来python有这样一个库,倒是可以帮忙实现这样的需求。于是抱着开源以及能省就省的精神,使用 PyPDF2 这个写了一个简短的小脚本

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

pip3 install PyPDF2

示例代码如下,会在当前运行目录下寻找pdf后缀的文件来合并,建议使用的时候新建一个文件夹并且将文件用序号命名顺序。

import os
from PyPDF2 import PdfFileMerger

target_path = os.getcwd()
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]
print(pdf_lst)

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

file_merger.write("merge.pdf")

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

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

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

4.对象将所有文件append

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

0

评论 (0)

取消