使用 Python 给 PDF 添加目录书签

0、库的选择——pypdf

原因:Python Version Support

Python

3.11

3.10

3.9

3.8

3.7

3.6

2.7

pypdf>=3.0

YES

YES

YES

YES

YES

YES

PyPDF2>=2.0

YES

YES

YES

YES

YES

YES

PyPDF2 1.20.0 - 1.28.4

YES

YES

YES

YES

YES

YES

PyPDF2 1.15.0 - 1.20.0

YES

我的版本

Python=3.6.13

pypdf=3.16.2

1、添加书签——方法add_outline_item的使用

# https://zhuanlan.zhihu.com/p/603340639
import pypdf  #
import syswk_in_file_name = 'PythonTutorial.pdf'
input1 = open(wk_in_file_name, "rb")  # 打开需要添加书签的PDF
writer = pypdf.PdfWriter()  # 创建一个PdfWriter类
writer.append(input1)  # 将PDF读入writer中,然后进行书签的编辑writer.add_outline_item(title='10', page_number=10, parent=None)  # 添加第一个书签
writer.add_outline_item(title='11', page_number=11, parent=None)  # 添加第二个书签# Write to an output PDF document
output = open('01_' + wk_in_file_name, "wb")  # 如果wk_out_file_name不存在,则创建一个
writer.write(output)  # 将添加书签后的PDF保存# Close File Descriptors
writer.close()
output.close()print('pypdf.__version__=', pypdf.__version__)
print('sys.version=', sys.version)pass

运行结果

2、添加子书签——参数parent的使用

# https://zhuanlan.zhihu.com/p/603340639
import pypdfwk_in_file_name = 'PythonTutorial.pdf'
writer = pypdf.PdfWriter()
input1 = open(wk_in_file_name, "rb")
writer.append(input1)parent_bookmark_0 = writer.add_outline_item(title='10', page_number=10, parent=None)  # 添加第一个书签
writer.add_outline_item(title='10_1', page_number=11, parent=parent_bookmark_0)  # 添加第一个书签的子书签
parent_bookmark_1 = writer.add_outline_item(title='11', page_number=20, parent=None)  # 添加第二个书签
writer.add_outline_item(title='11_1', page_number=21, parent=parent_bookmark_1)  # 添加第二个书签的子书签# Write to an output PDF document
output = open('02_'+wk_in_file_name, "wb")
writer.write(output)# Close File Descriptors
writer.close()
output.close()pass

运行结果

3、读取txt文件

# https://blog.csdn.net/kobeyu652453/article/details/106876829f = open('dir.txt', 'r', encoding='utf8')
# f = open('dir.txt', encoding='gbk', errors='ignore'), errors='ignore'
# f = open('dir.txt', encoding='gb18030', errors='ignore')
line1 = f.readline()  # 读取第一行,大文件readline# https://blog.csdn.net/andyleo0111/article/details/87878784
lines = f.readlines()  # 读取所有行,小文件readlines
num_lines = len(lines)  # 标题的总个数txt = []
for line in lines:txt.append(line.strip())print(line.strip())line.strip()  # 去掉末尾的'\n'line.split(' ')  # 根据line中' '进行分割line.count('.')  # 有n个'.'就是n+1级标题print(txt)
f.close()  # 关闭文件
print('f.closed=', f.closed)

 运行结果

D:\SoftProgram\JetBrains\anaconda3_202303\envs\py3_6_for_TimeSeries\python.exe E:\program\python\gitTemp\pdf\test\03_read_txt.py 
1 课前甜点 3
2 使用Python解释器 5
2.1 调用解释器 5
2.1.1 传入参数 6
2.1.2 交互模式 6
2.2 解释器的运行环境 6
2.2.1 源文件的字符编码 6
3 Python的非正式介绍 9
3.1 Python作为计算器使用 9
3.1.1 数字 9
3.1.2 字符串 11
3.1.3 列表 14
3.2 走向编程的第一步 15
4 其他流程控制工具 17
4.1 if语句 17
4.2 for语句 17
4.3 range()函数 18
4.4 break和continue语句,以及循环中的else子句 19
4.5 pass 语句 20
4.6 定义函数 20
4.7 函数定义的更多形式 22
4.8 小插曲:编码风格 29
['1 课前甜点 3', '2 使用Python解释器 5', '2.1 调用解释器 5', '2.1.1 传入参数 6', '2.1.2 交互模式 6', '2.2 解释器的运行环境 6', '2.2.1 源文件的字符编码 6', '3 Python的非正式介绍 9', '3.1 Python作为计算器使用 9', '3.1.1 数字 9', '3.1.2 字符串 11', '3.1.3 列表 14', '3.2 走向编程的第一步 15', '4 其他流程控制工具 17', '4.1 if语句 17', '4.2 for语句 17', '4.3 range()函数 18', '4.4 break和continue语句,以及循环中的else子句 19', '4.5 pass 语句 20', '4.6 定义函数 20', '4.7 函数定义的更多形式 22', '4.8 小插曲:编码风格 29']
f.closed= True进程已结束,退出代码0

4、从txt中读取目录与页码并写入PDF的书签

# https://blog.csdn.net/kobeyu652453/article/details/106876829
import pypdfwk_in_file_name = 'PythonTutorial.pdf'
writer = pypdf.PdfWriter()
input1 = open(wk_in_file_name, "rb")
writer.append(input1)f = open('dir.txt', 'r', encoding='utf8')
lines = f.readlines()  # 读取所有行
num_lines = len(lines)  # 标题的总个数txt = []
for line in lines:line = line.strip()  # 去掉末尾的'\n'pline = line.split(' ')  # 根据line中' '进行分割level = line.count('.')  # 有n个'.'就是n+1级标题if level == 0:bookmark_parent_0 = writer.add_outline_item(title=pline[0] + pline[1], page_number=int(pline[-1]), parent=None)elif level == 1:bookmark_parent_1 = writer.add_outline_item(title=pline[0] + pline[1], page_number=int(pline[-1]),parent=bookmark_parent_0)else:writer.add_outline_item(title=pline[0] + pline[1], page_number=int(pline[-1]), parent=bookmark_parent_1)# Write to an output PDF document
output = open('04_'+wk_in_file_name, "wb")
writer.write(output)# Close File Descriptors
writer.close()
output.close()f.close()  # 关闭文件
print('f.closed=', f.closed)

运行结果 

 5、添加偏置

# https://blog.csdn.net/kobeyu652453/article/details/106876829
import pypdfwk_in_file_name = 'PythonTutorial.pdf'
writer = pypdf.PdfWriter()
input1 = open(wk_in_file_name, "rb")
writer.append(input1)f = open('dir.txt', 'r', encoding='utf8')
lines = f.readlines()  # 读取所有行
num_lines = len(lines)  # 标题的总个数
offset = 5  # 添加偏置txt = []
bookmark_parent_0 = None
bookmark_parent_1 = Nonefor line in lines:line = line.strip()  # 去掉末尾的'\n'pline = line.split(' ')  # 根据line中' '进行分割level = line.count('.')  # 有n个'.'就是n+1级标题page_title = pline[0] + ' ' + pline[1]page_num = int(pline[-1]) + offsetif level == 0:bookmark_parent_0 = writer.add_outline_item(title=page_title, page_number=page_num, parent=None)elif level == 1:bookmark_parent_1 = writer.add_outline_item(title=page_title, page_number=page_num, parent=bookmark_parent_0)else:writer.add_outline_item(title=page_title, page_number=page_num, parent=bookmark_parent_1)print(line.strip())print(txt)# Write to an output PDF document
output = open('05_' + wk_in_file_name, "wb")
writer.write(output)# Close File Descriptors
writer.close()
output.close()f.close()  # 关闭文件
print('f.closed=', f.closed)

运行结果:

 

6、dir中没有页码的情况

# https://blog.csdn.net/kobeyu652453/article/details/106876829
import pypdfwk_in_file_name = 'PythonTutorial.pdf'
writer = pypdf.PdfWriter()
input1 = open(wk_in_file_name, "rb")
writer.append(input1)f = open('dir.txt', 'r', encoding='utf8')
lines = f.readlines()  # 读取所有行
num_lines = len(lines)  # 标题的总个数
offset = 5  # 添加偏置txt = []
bookmark_parent_0 = None
bookmark_parent_1 = Nonefor line in lines:line = line.strip()  # 去掉末尾的'\n'pline = line.split(' ')  # 根据line中' '进行分割level = line.count('.')  # 有n个'.'就是n+1级标题page_title = pline[0] + ' ' + pline[1]page_num = offsetif level == 0:bookmark_parent_0 = writer.add_outline_item(title=page_title, page_number=page_num, parent=None)elif level == 1:bookmark_parent_1 = writer.add_outline_item(title=page_title, page_number=page_num, parent=bookmark_parent_0)else:writer.add_outline_item(title=page_title, page_number=page_num, parent=bookmark_parent_1)print(line.strip())print(txt)# Write to an output PDF document
output = open('06_' + wk_in_file_name, "wb")
writer.write(output)# Close File Descriptors
writer.close()
output.close()f.close()  # 关闭文件
print('f.closed=', f.closed)

运行结果

参考

使用 python 给 PDF 添加目录书签_pypdf2.errors.deprecationerror: pdffilereader is d_Wreng我是002的博客-CSDN博客

python 操作合并pdf 文件并建立书签目录 - 知乎 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.xdnf.cn/news/147093.html

如若内容造成侵权/违法违规/事实不符,请联系一条长河网进行投诉反馈,一经查实,立即删除!

相关文章

1、【开始】【简介】Qlib:量化平台

【简介】1、Qlib:量化平台 简介框架简介 Qlib是一个面向AI的量化投资平台,旨在实现AI技术在量化投资中的潜力,赋能研究,并创造价值。 通过Qlib,用户可以轻松利用他们的想法来创建更好的量化投资策略。 框架 在模块层,Qlib 是由上述组件组成的平台。这些组件被设计为低耦…

Flutter笔记:关于应用程序中提交图片作为头像

Flutter笔记 关于应用程序中提交图片作为头像 作者:李俊才 (jcLee95):https://blog.csdn.net/qq_28550263 邮箱 :291148484163.com 本文地址:https://blog.csdn.net/qq_28550263/article/details/133418554…

多目标平衡黏菌算法(MOEOSMA)求解八个现实世界受约束的工程问题

目录 1 受约束的工程问题 1.1 减速器设计问题(Speed reducer design problem) 1.2 弹簧设计问题(Spring design problem) 1.3 静压推力轴承设计问题(Hydrostatic thrust bearing design problem) 1.4 振动平台设计问题(Vibrating platform design problem) 1.5 汽车侧面碰…

HTML——列表,表格,表单内容的讲解

文章目录 一、列表1.1无序(unorder)列表1.2 有序(order)列表1.3 定义列表 二、表格**2.1 基本的表格标签2.2 演示 三、表单3.1 form元素3.2 input元素3.2.1 单选按钮 3.3 selcet元素 基础部分点击: web基础 一、列表 …

做一个优秀的博士生,时间的付出是必要条件

*图片来自管理学季刊 时间的付出 所有成功的科学家一定具有的共同点,就是他们必须付出大量的时间和心血。这是一条真理。实际上,无论社会上哪一种职业,要想成为本行业中的佼佼者,都必须付出比常人多的时间。有时&…

数据结构——二叉树的基本概念及顺序存储(堆)

目录 一.前言 二.树概念及结构 2.1 树的概念 2.2 树的相关概念 2.3 树的表现 2.4 树在实际中的应用(表示文件系统的目录树结构) 三.二叉树的概念及结构 3.1 概念 3.2 特殊的二叉树 3.3 二叉树的性质 3.4 二叉树的存储结构 3.4.1 顺序存储 3…

深度学习笔记之线性代数

深度学习笔记之线性代数 一、向量 在数学表示法中,向量通常记为粗体小写的符号(例如,x,y,z)当向量表示数据集中的样本时,它们的值具有一定的现实意义。例如研究医院患者可能面临的心脏病发作风…

小谈设计模式(13)—外观模式

小谈设计模式(13)—外观模式 专栏介绍专栏地址专栏介绍 外观模式主要目的角色分析外观(Facade)角色子系统(Subsystem)角色客户端(Client)角色 工作原理核心思想总结简化接口解耦客户…

springboot和vue:九、v-for中的key+vue组件化开发

v-for中的key 目的 现在想要实现这样的一种效果&#xff0c;页面上存在初始姓名表单&#xff0c;同时存在输入框&#xff0c;输入姓名后点击添加按钮可以将新输入的姓名加入显示的姓名表单中。 代码 <!DOCTYPE html> <html lang"en"><head><…

8、Nacos服务注册服务端源码分析(七)

本文收录于专栏 Nacos 中 。 文章目录 前言确定前端路由CatalogController.listDetail()ServiceManager总结 前言 前文我们分析了Nacos中客户端注册时数据分发的设计链路&#xff0c;本文根据Nacos前端页面请求&#xff0c;看下前端页面中的服务列表的数据源于哪里。 确定前端…

【考研数学】高等数学第七模块 —— 曲线积分与曲面积分 | 3. 对面积的曲面积分(第一类曲面积分)

文章目录 二、曲面积分2.1 对面积的曲面积分&#xff08;第一类曲面积分&#xff09;2.1.1 问题引入 —— 曲面的质量2.1.2 对面积的曲面积分定义及性质2.1.3 对面积的曲面积分的计算法 写在最后 二、曲面积分 2.1 对面积的曲面积分&#xff08;第一类曲面积分&#xff09; 2…

【面试经典150 | 矩阵】螺旋矩阵

文章目录 写在前面Tag题目来源题目解读解题思路方法一&#xff1a;模拟方法二&#xff1a;按层模拟 写在最后 写在前面 本专栏专注于分析与讲解【面试经典150】算法&#xff0c;两到三天更新一篇文章&#xff0c;欢迎催更…… 专栏内容以分析题目为主&#xff0c;并附带一些对于…

C语言实例_调用SQLITE数据库完成数据增删改查

一、SQLite介绍 SQLite是一种轻量级的关系型数据库管理系统&#xff08;RDBMS&#xff09;&#xff0c;它是一个开源的、零配置的、服务器端的、自包含的、零管理的、事务性的SQL数据库引擎。它被广泛应用于嵌入式设备、移动设备和桌面应用程序等领域。 SQLite的特点包括&…

【Golang】数组 切片

【Golang】数组 && 切片 1、数组 基本概念 数组是一个由固定长度的特定类型元素组成的序列&#xff0c;一个数组可以由零个或多个元素组成 因为数组的长度是固定的&#xff0c;所以在Go语言中很少直接使用数组 数组初始化 //1、默认数组中的值是类型的默认值 var arr…

华为智能企业上网行为管理安全解决方案(2)

本文承接&#xff1a; https://blog.csdn.net/qq_37633855/article/details/133339254?spm1001.2014.3001.5501 重点讲解华为智能企业上网行为管理安全解决方案的部署流程。 华为智能企业上网行为管理安全解决方案&#xff08;2&#xff09; 课程地址方案部署整体流程组网规划…

ARM-day2

1、1到100累加 .text .global _start_start:MOV r0, #1ADD r1,r0, #1fun:ADD r0,r0,r1ADD r1,r1, #1cmp r1, #0x65moveq PC,LRbl funstop:b stop.end2、思维导图

Spring Boot的自动装配中的@ConditionalOnBean条件装配注解在Spring启动过程中,是如何保证处理顺序靠后的

前言 为什么Spring Boot条件注解那么多&#xff0c;而标题中是ConditionalOnBean呢&#xff1f; 因为&#xff0c;相比之下我们用的比较多的条件装配注解也就是ConditionalOnClass、ConditionalOnBean了&#xff0c;而ConditionalOnClass对顺序并不敏感&#xff08;说白了就是判…

uniapp app 导出excel 表格

直接复制运行 <template><view><button click"tableToExcel">导出一个表来看</button><view>{{ successTip }}</view></view> </template><script>export default {data() {return {successTip: }},metho…

2023年【道路运输企业安全生产管理人员】最新解析及道路运输企业安全生产管理人员考试技巧

题库来源&#xff1a;安全生产模拟考试一点通公众号小程序 道路运输企业安全生产管理人员最新解析参考答案及道路运输企业安全生产管理人员考试试题解析是安全生产模拟考试一点通题库老师及道路运输企业安全生产管理人员操作证已考过的学员汇总&#xff0c;相对有效帮助道路运…

JavaSE | 初识Java(五) | 方法的使用

方法就是一个代码片段&#xff0c; 类似于 C 语言中的 " 函数 "。 方法可以是我们代码逻辑更清晰&#xff0c;并且可以服用方法使代码更简洁 方法语法格式 // 方法定义 修饰符 返回值类型 方法名称([参数类型 形参 ...]){ 方法体代码; [return 返回值]; } 实例&…