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

效果

相关推荐
Hylan_J2 小时前
【VSCode】MicroPython环境配置
ide·vscode·python·编辑器
莫忘初心丶2 小时前
在 Ubuntu 22 上使用 Gunicorn 启动 Flask 应用程序
python·ubuntu·flask·gunicorn
失败尽常态5235 小时前
用Python实现Excel数据同步到飞书文档
python·excel·飞书
2501_904447745 小时前
OPPO发布新型折叠屏手机 起售价8999
python·智能手机·django·virtualenv·pygame
青龙小码农5 小时前
yum报错:bash: /usr/bin/yum: /usr/bin/python: 坏的解释器:没有那个文件或目录
开发语言·python·bash·liunx
小冷爱学习!5 小时前
华为动态路由-OSPF-完全末梢区域
服务器·网络·华为
大数据追光猿5 小时前
Python应用算法之贪心算法理解和实践
大数据·开发语言·人工智能·python·深度学习·算法·贪心算法
Leuanghing5 小时前
【Leetcode】11. 盛最多水的容器
python·算法·leetcode
技术小齐5 小时前
网络运维学习笔记 016网工初级(HCIA-Datacom与CCNA-EI)PPP点对点协议和PPPoE以太网上的点对点协议(此处只讲华为)
运维·网络·学习
xinxiyinhe6 小时前
如何设置Cursor中.cursorrules文件
人工智能·python