使用 pypdf 给 PDF 添加目录书签

python 复制代码
"""
dir.txt的形式
第1章 计算机系统基础知识 1
1.1 嵌入式计算机系统概述 1
1.2 数据表示 4
1.2.1 进位计数制及转换 4
1.2.2 数值型数据的表示 6
第2章 嵌入式系统硬件基础知识 56
2.1 数字电路基础 56
2.1.1 信号特征 56
2.1.2 组合逻辑电路和时序逻辑电路 56
2.2 嵌入式微处理器基础 63
2.2.1 嵌入式微处理器的结构和类型 65
2.2.2 嵌入式微处理器的异常与中断 71
"""

import pypdf

# TODO 需要提前设置的变量
original_pdf_name = '嵌入式系统设计师教程__第2版.pdf'  # pdf文件名
directory_file_name = "dir.txt"  # 目录所在文件名
first_chapter_origin_num = 1  # 第一章在目录上的页码
first_chapter_actual_num = 10  # 第一章的页码

# TODO 以下内容无需更改
offset = first_chapter_actual_num - first_chapter_origin_num - 1  # 偏置

writer = pypdf.PdfWriter()  # 创建一个PdfWriter类
input1 = open(original_pdf_name, "rb")  # 打开需要添加书签的PDF
writer.append(input1)  # 将PDF读入writer中,然后进行书签的编辑

f = open(directory_file_name, 'r', encoding='utf8')  # 打开目录文件
lines = f.readlines()  # 读取目录的所有行
num_lines = len(lines)  # 标题的总个数

txt = []
bookmark_parent_0 = None
bookmark_parent_1 = None

for line in lines:
    line = line.strip()  # 去掉末尾的'\n'
    title = line.split(' ')  # 根据line中空格' '进行分割
    level = line.count('.')  # 有n个'.'就是n+1级标题

    page_title = title[0] + ' ' + title[1]
    page_num = int(title[-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_' + original_pdf_name, "wb")
writer.write(output)

# Close File Descriptors
writer.close()
output.close()

f.close()  # 关闭文件
print('f.closed=', f.closed)

更详细的pypdf使用参考

使用 Python 给 PDF 添加目录书签_python word转pdf按标题生成书签-CSDN博客https://blog.csdn.net/qq_35629563/article/details/133499112

相关推荐
菜鸟单飞12 小时前
介绍一款非常实用的PDF阅读软件!
windows·pdf·电脑
IDRSolutions_CN1 天前
如何在 PDF 文件中嵌入自定义数据
java·经验分享·pdf·软件工程·团队开发
企鹅侠客1 天前
开源免费文档翻译工具 可支持pdf、word、excel、ppt
人工智能·pdf·word·excel·自动翻译
近冬的阳光2 天前
PDF文档管理系统V2.0
pdf
Driver_tu2 天前
在windows10上基于Python部署marker,实现PDF转markdown文件(保姆级)
pdf
黄铎彦2 天前
使用GDI+、文件和目录和打印API,批量将图片按文件名分组打包成PDF
c++·windows·pdf
梅如你2 天前
IEEE官方期刊缩写查询pdf分享
pdf
jxf_jxfcsdn2 天前
python读取pdf文档
开发语言·python·pdf
蜗牛沐雨2 天前
如何生成美观且内容稳定的PDF文档:从基础到进阶的全方案解析
人工智能·pdf·tensorflow
Jamence2 天前
国产开源PDF解析工具MinerU
人工智能·pdf·aigc