惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Hugging Face - Blog
Hugging Face - Blog
宝玉的分享
宝玉的分享
G
Google Developers Blog
T
Tailwind CSS Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
V
V2EX
V
Visual Studio Blog
博客园 - Franky
S
SegmentFault 最新的问题
Jina AI
Jina AI
爱范儿
爱范儿
The Cloudflare Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
D
DataBreaches.Net
C
Check Point Blog
月光博客
月光博客
P
Proofpoint News Feed
T
The Blog of Author Tim Ferriss
罗磊的独立博客
H
Hackread – Cybersecurity News, Data Breaches, AI and More
MongoDB | Blog
MongoDB | Blog
The GitHub Blog
The GitHub Blog
Y
Y Combinator Blog
Martin Fowler
Martin Fowler

博客园 - 外科手术医生

AI带来学习的困惑,无法改变大脑学习的方式 一篇最近很火的文章,同时也是一个搬砖少年 国内经济指标关系 mac充当服务器使用 Spring-AI开发之旅 MACD秒解 历史的车轮 spring ai提示词 纳瓦尔宝典-总结内容 小龙虾的skills哪里找? JMeter压测使用 Git仓库ssh不同环境配置 成功没有奇迹,只有积累----Bruce Lee 为什么要⽤ Foundry git命令下,mac环境下载依赖相关报错问题解决方案 数据分析/数据挖掘/机器学习---- 必读书目(转) 简单高效的语言 OSI模型-一图胜千言 dubbo分布式系统 JVM解剖 线程池 集合类 concurrent之CAS concurrent之volatile 架构师之路 责任链设计模式 Junit框架分析 线程详解 计划自己的时间
添加pdf的目录
外科手术医生 · 2026-06-18 · via 博客园 - 外科手术医生

#!/usr/bin/env python

# -*- coding: utf-8 -*-

"""

PDF目录添加工具

从txt文件读取目录信息并添加到PDF文件中

"""

import re

import sys

import glob

import os

from PyPDF2 import PdfReader, PdfWriter

def parse_toc_from_txt(txt_file):

    """

    从txt文件解析目录信息

    """

    toc_items = []

    with open(txt_file, 'r', encoding='utf-8') as f:

        lines = f.readlines()

    for line in lines:

        line = line.strip()

        if not line or line == '目录正文':

            continue

        # 匹配格式:章节名称 + 点号 + 页码

        match = re.match(r'(.+?)\s*[\.。]+\s*(\d+)\s*$', line)

        if match:

            title = match.group(1).strip()

            page_num = int(match.group(2))

            toc_items.append((title, page_num))

    return toc_items

# 起始页偏移量(第一章从第8页开始,目录中写的是第1页,所以偏移量为7)

START_PAGE_OFFSET = 7

def find_pdf_file():

    """自动查找当前目录的PDF文件(排除output文件)"""

    pdf_files = glob.glob('*.pdf')

    # 排除output文件

    pdf_files = [f for f in pdf_files if 'output' not in f.lower()]

    return pdf_files[0] if pdf_files else None

def add_bookmarks_to_pdf(pdf_file, output_file, toc_items):

    """

    为PDF添加书签/目录

    """

    reader = PdfReader(pdf_file)

    writer = PdfWriter()

    # 复制所有页面

    for page in reader.pages:

        writer.add_page(page)

    # 添加书签

    for title, page_num in toc_items:

        # PDF页码从0开始,加上起始页偏移量

        pdf_page_index = page_num - 1 + START_PAGE_OFFSET

        if pdf_page_index < 0:

            pdf_page_index = 0

        elif pdf_page_index >= len(reader.pages):

            pdf_page_index = len(reader.pages) - 1

        writer.add_outline_item(title, pdf_page_index)

    # 保存输出文件

    with open(output_file, 'wb') as f:

        writer.write(f)

    print(f"成功添加 {len(toc_items)} 个目录项")

    print(f"输出文件: {output_file}")

def main():

    """主函数"""

    # 默认文件名

    txt_file = '目录.txt'

    output_file = 'output_with_toc.pdf'

    # 自动查找PDF文件

    pdf_file = find_pdf_file()

    if not pdf_file:

        print("错误: 当前目录未找到PDF文件")

        return

    # 命令行参数支持

    if len(sys.argv) >= 2:

        txt_file = sys.argv[1]

    if len(sys.argv) >= 3:

        output_file = sys.argv[2]

    print(f"读取目录文件: {txt_file}")

    print(f"读取PDF文件: {pdf_file}")

    print(f"输出文件: {output_file}")

    print("-" * 50)

    # 解析目录

    toc_items = parse_toc_from_txt(txt_file)

    if not toc_items:

        print("警告: 未找到任何目录项")

        return

    print(f"找到 {len(toc_items)} 个目录项:")

    for i, (title, page) in enumerate(toc_items, 1):

        print(f"  {i}. {title} - 第{page}页")

    print("-" * 50)

    # 添加书签到PDF

    add_bookmarks_to_pdf(pdf_file, output_file, toc_items)

if __name__ == '__main__':

    main()