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

推荐订阅源

K
Kaspersky official blog
Engineering at Meta
Engineering at Meta
D
DataBreaches.Net
Stack Overflow Blog
Stack Overflow Blog
Microsoft Security Blog
Microsoft Security Blog
Y
Y Combinator Blog
B
Blog RSS Feed
GbyAI
GbyAI
P
Proofpoint News Feed
aimingoo的专栏
aimingoo的专栏
MyScale Blog
MyScale Blog
D
Docker
阮一峰的网络日志
阮一峰的网络日志
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Recorded Future
Recorded Future
美团技术团队
The Register - Security
The Register - Security
V
Visual Studio Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
T
Tailwind CSS Blog
爱范儿
爱范儿
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
T
The Blog of Author Tim Ferriss
博客园 - 司徒正美
量子位
B
Blog
F
Fortinet All Blogs
Martin Fowler
Martin Fowler
博客园 - 【当耐特】
MongoDB | Blog
MongoDB | Blog
A
About on SuperTechFans
I
InfoQ
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
有赞技术团队
有赞技术团队
雷峰网
雷峰网
大猫的无限游戏
大猫的无限游戏
J
Java Code Geeks
L
LangChain Blog
Latest news
Latest news
S
SegmentFault 最新的问题
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Blog — PlanetScale
Blog — PlanetScale
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Cisco Talos Blog
Cisco Talos Blog
F
Full Disclosure
C
Cisco Blogs
D
Darknet – Hacking Tools, Hacker News & Cyber Security
W
WeLiveSecurity
T
Tenable Blog
T
Tor Project blog

博客园 - 外科手术医生

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()