使用 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 sys

wk_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 pypdf

wk_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/106876829

f = 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 pypdf

wk_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 pypdf

wk_in_file_name = '嵌入式系统设计师教程__第2版.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)  # 标题的总个数
first_chapter_origin_num=1
first_chapter_actual_num=10
offset = 10-1  # 添加偏置

txt = []
bookmark_parent_0 = None
bookmark_parent_1 = None

for 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]) + offset

    if 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 pypdf

wk_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 = None

for 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 = offset

    if 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 文件并建立书签目录 - 知乎

Python学习手册(第3版).pdf本书包括:   类型和操作——深入讨论Python主要的内置对象类型:数字、列表和字典等。   语句和语法——在Python中输入代码来建立并处理对象,以及Python一般的语法模型。   函数——Python基本的面向过程工具,用于组织代码和重用。   模块——封装语句、函数以及其他工具,从而可以组织成较大的组件。   类和OOP——Python可选的面向对象编程工具,可用于组织程序代码从而实现定制和重用。   异常和工具——异常处理模型和语句,并介绍编写更大程序的开发工具。 《Python学习手册(第3版)》讲述了:Python可移植、功能强大、易于使用,是编写独立应用程序和脚本应用程序的理想选择。无论你是刚接触编程或者刚接触Python,通过学习《Python学习手册(第3版)》,你可以迅速高效地精通核心Python语言基础。读完《Python学习手册(第3版)》,你会对这门语言有足够的了解,从而可以在你所从事的任何应用领域中使用它。, 《Python学习手册(第3版)》是作者根据过去10年用于教学而广为人知的培训课程的材料编写而成的。除了有许多详实说明和每章小结之外,每章还包括一个头脑风 暴:这是《Python学习手册(第3版)》独特的一部分,配合以实用的练习题和复习题,让读者练习新学的技巧并测试自己的理解程度。, 《Python学习手册(第3版)》包括:, 类型和操作——深入讨论Python主要的内置对象类型:数字、列表和字典等。, 语句和语法——在Python中输入代码来建立并处理对象,以及Python一般的语法模型。, 函数——Python基本的面向过程工具,用于组织代码和重用。, 模块——封装语句、函数以及其他工具,从而可以组织成较大的组件。, 类和OOP——Python可选的面向对象编程工具,可用于组织程序代码从而实现定制和重用。, 异常和工具——异常处理模型和语句,并介绍编写更大程序的开发工具。, 讨论Python 3.0。, 《Python学习手册(第3版)》让你对Python语言有深入而完整的了解,从而帮助你理解今后遇到的任何Python应用程序实例。如果你准备探索Google和YouTube为什么选中了Python,《Python学习手册(第3版)》就是你入门的最佳指南。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值