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

相关推荐
我命由我123453 小时前
Photoshop - Photoshop 工具栏(14)抓手工具
ui·职场和发展·pdf·求职招聘·职场发展·photoshop·美工
我命由我123453 小时前
PDFBox - PDFBox 加载 PDF 异常清单(数据为 null、数据为空、数据异常、文件为 null、文件不存在、文件异常)
java·服务器·后端·java-ee·pdf·intellij-idea·intellij idea
CHANG_THE_WORLD1 天前
PDFium导出pdf 图像
开发语言·c++·pdf
momo_al1 天前
Umi-OCR制作双层PDF
pdf·ocr
励志成为美貌才华为一体的女子1 天前
pdf解析工具---Miner-u 本地部署记录
学习·pdf
reasonsummer1 天前
【办公类-115-02】20251018信息员每周通讯上传之文字稿整理(PDF转docx没有成功)
python·pdf
top_designer1 天前
告别“静态”VI手册:InDesign与AE打造可交互的动态品牌规范
设计模式·pdf·交互·vi·工作流·after effects·indesign
2501_929382652 天前
MobiOffice解锁高级功能版 v15.9.57971 安卓手机doc, docx ppt, .pptx pdf办公软件
智能手机·pdf·powerpoint·wps
CodeCraft Studio2 天前
国产化PDF处理控件Spire.PDF教程:如何在 C# 中从 HTML 和 PDF 模板生成 PDF
pdf·c#·html·.net·spire.pdf·pdf文档开发·html创建模板pdf
E_ICEBLUE2 天前
高效压缩 PDF 文件大小(3 大实用的 Python 库)
python·pdf