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

相关推荐
一个懒鬼3 小时前
Edge浏览器打开PDF文件显示空白(每次需要等上一会)
windows·pdf
Lauren_Lu13 小时前
pdf 不是扫描件,但却无法搜索关键词【问题尝试解决未果记录】
pdf
Python猫1 天前
付费专栏·Python潮流周刊电子书合集(epub、pdf、markdown)下载
python·计算机·pdf·电子书·资料
JackieZhengChina1 天前
用python清除PDF文件中的水印(Adobe Acrobat 无法删除)
pdf
geovindu1 天前
vue3: pdf.js 3.4.120 using javascript
开发语言·javascript·vue.js·pdf
TextIn智能文档云平台2 天前
PDF文档解析新突破:图表识别、公式还原、手写字体处理,让AI真正读懂复杂文档!
图像处理·人工智能·算法·自然语言处理·pdf·ocr
old_power2 天前
【Python】PDF文件处理(PyPDF2、borb、fitz)
python·pdf
belldeep2 天前
vite:npm 安装 pdfjs-dist , PDF.js View 预览功能示例
javascript·pdf·pdfjs-dist·pdf.worker
dtzly2 天前
若依定制pdf生成实战
pdf
令狐少侠20112 天前
ai之pdf解析rapidOCR 的两种底层依赖PaddlePaddle 和ONNXRuntime
人工智能·ai·pdf