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

相关推荐
AI导出鸭2 小时前
Claude的LaTeX生成PDF文件复制后数学公式乱码,怎样修改?专业用户首选“AI导出鸭”
人工智能·pdf·ai导出鸭
qyyyyy5701 天前
外文 PDF 怎么整理成 Markdown?从翻译、内容提取到 RAG 知识库导入
自然语言处理·pdf·erlang·机器翻译·零知识证明
AI导出鸭2 天前
Perplexity的LaTeX生成PDF文件复制后数学公式乱码,怎样修改?AI导出鸭苹果版的技术拆解与批量之道
人工智能·pdf·ai导出鸭
SpaceAIGlobal2 天前
AI PPT生成工具哪些支持PDF文档导入?
人工智能·ai·pdf·powerpoint·办公
Xxtaoaooo2 天前
极空间部署Stirling PDF:搭建自托管PDF工具箱并实现远程访问
pdf·cpolar·stirling pdf
SamChan902 天前
对比 4 种主流 PDF 文档解析方案:PyMuPDF vs pdfplumber vs Apache PDFBox vs 大模型 OCR
python·ai·pdf·ocr·apache·机器翻译
AI刀刀3 天前
Kimi 文档导出格式错乱、排版丢失、导出报错?AI 导出鸭一键智能适配,稳定输出规范 Word、PDF,高效解决各类导出难题
人工智能·pdf·word·ai导出鸭
Ai-_Man3 天前
豆包智能体把对话批量导出为Word或PDF的正确顺序
人工智能·ai·小程序·pdf·word
SamChan903 天前
FastAPI+Celery+Redis搭建企业级PDF翻译异步任务系统
redis·后端·python·pdf·wpf·fastapi
SamChan904 天前
用Playwright端到端测试PDF翻译功能:Web自动化测试实战
前端·python·ai·pdf·wpf