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()

效果

相关推荐
kyle~10 分钟前
FastAPI --- 将业务能力以 API 的形式提供给外部系统
python·fastapi·前后端
aiotto资源分享30 分钟前
Python 写 JSON 文件,程序中途退出会留下什么?
java·python·json·jsondecodeerror
光电笑映1 小时前
TCP 为什么可靠?从三次握手、滑动窗口到拥塞控制全面拆解(上)
运维·服务器·网络·udp
梯度下降者1 小时前
Python信号量,条件变量,事件学习
python·条件变量·事件·信号量·线程通信
Vni2 小时前
华三双核心交换机IRF堆叠
网络·交换机·堆叠·华三
MSTcheng.2 小时前
【AI应用实战】用 FastAPI + SSE 做一个自己的 AI 聊天网页:流式输出、多轮对话与完整源码
人工智能·python·大模型·fastapi·sse·ai聊天助手
the局外人3 小时前
Python 实战检索优化:BM25、向量与重排
数据库·后端·python
__underline__3 小时前
冷门Python知识点006篇:Python 类体里的名字,能被"凭空造出来"
后端·python
15Moonlight3 小时前
Linux 网络(11):IO 多路转接(select /poll/epoll)
linux·网络
用户0332126663674 小时前
使用 Python 轻松移除 Excel 文档中的重复行
python·excel