Python 合并多个 PDF 文件并建立书签目录

今天在用 WPS 的 PDF 工具合并多个文件的时候,非常不给力,居然卡死了好几次,什么毛病?!

心里想,就这么点儿功能,居然收了我会员费都实现不了?不是吧......

只能自己来了,主要用了 pypdf 库,因为 PyPDF2 版本更新原因,一些类和函数已经过时,截止发文时以下是最新用法(赶紧收藏吧!!)

第一步,安装 pypdf

复制代码
pip install pypdf

第二步,具体实现

python 复制代码
import os
from pypdf import PdfWriter, PdfReader

# 指定路径
target_path = '/Users/jss/Desktop/abc'

# 过滤出以 .pdf 为后缀的文件
pdf_lst = [f for f in os.listdir(target_path) if f.endswith('.pdf')]

# 对文件名进行排序
sorted_files = sorted(pdf_lst)

# 输出排序后的文件名(测试查看是否正确)
# for file in sorted_files:
#     print(file)

# 按具体位置拼接文件名
pdf_lst = [os.path.join(target_path, filename) for filename in sorted_files]

# (测试查看是否正确)
# for file in pdf_lst: 
#     print(file)

# 记录页码
pdf_num = 0

# 获取输出流
file_merger = PdfWriter()

# 循环合并
for pdf in pdf_lst:
    # 提取文件名,用作书签目录
    pdf_title = pdf.split("/")[-1].split('.')[0]
    # 合并pdf文件
    file_merger.append(pdf, pdf_title)
    # 记录页数
    pdf_num += len(PdfReader(pdf).pages)
    
# 指定文件输出合并后文件
file_merger.write("/Users/jss/Desktop/merge.pdf")

# 关闭流
file_merger.close()

效果

相关推荐
金銀銅鐵11 小时前
[Python] 从《千字文》中随机挑选汉字
后端·python
cup1116 小时前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi0018 小时前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵20 小时前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf20 小时前
Agent 流程编排
后端·python·agent
copyer_xyf21 小时前
Agent RAG
后端·python·agent
copyer_xyf21 小时前
【RAG】向量数据库:milvus
后端·python·agent
copyer_xyf21 小时前
Agent 记忆管理
后端·python·agent
星云穿梭2 天前
用Python写一个带图形界面的学生管理系统——完整教程
python