You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用iTextSharp修改PDF书签 移除各级书签文本末尾空格

使用iTextSharp去除PDF三级书签末尾空格

要批量清理PDF各级(包括三级)书签末尾的空格,核心思路是递归遍历整个书签树,对每个书签的标题执行去除末尾空格的操作,再将修改后的书签写回PDF。以下是具体实现步骤和代码:

实现步骤

  • 用PdfReader加载目标PDF文件
  • 通过PdfStamper获取可编辑的书签树
  • 递归遍历所有层级的书签(一级、二级、三级)
  • 对每个书签的标题调用TrimEnd()方法去除末尾空格
  • 保存修改后的PDF文件

完整代码示例

using System;
using System.Collections.Generic;
using iTextSharp.text.pdf;

class PdfBookmarkTrimmer
{
    static void Main(string[] args)
    {
        string inputPdfPath = @"C:\YourInputFile.pdf";
        string outputPdfPath = @"C:\YourOutputFile.pdf";

        // 加载原PDF
        using (PdfReader reader = new PdfReader(inputPdfPath))
        {
            // 创建PdfStamper用于修改书签
            using (PdfStamper stamper = new PdfStamper(reader, new System.IO.FileStream(outputPdfPath, System.IO.FileMode.Create)))
            {
                // 获取书签根节点
                List<Dictionary<string, object>> outlines = reader.GetOutlines();
                
                // 递归处理所有层级书签
                ProcessBookmarks(outlines);
                
                // 将修改后的书签写入输出PDF
                stamper.Outlines = outlines;
            }
        }
        
        Console.WriteLine("书签末尾空格清理完成!");
    }

    // 递归处理各级书签
    static void ProcessBookmarks(List<Dictionary<string, object>> bookmarks)
    {
        if (bookmarks == null || bookmarks.Count == 0)
            return;

        foreach (var bookmark in bookmarks)
        {
            // 修改书签标题:去除末尾空格
            if (bookmark.ContainsKey("Title"))
            {
                string originalTitle = bookmark["Title"].ToString();
                bookmark["Title"] = originalTitle.TrimEnd();
            }

            // 处理子级书签(包括三级)
            if (bookmark.ContainsKey("Kids"))
            {
                List<Dictionary<string, object>> childBookmarks = (List<Dictionary<string, object>>)bookmark["Kids"];
                ProcessBookmarks(childBookmarks);
            }
        }
    }
}

注意事项

  • 确保已通过NuGet安装iTextSharp包(Install-Package iTextSharp)
  • 如果原PDF是加密的,需要先调用reader.Unlock("password")解锁后再处理
  • 处理前建议备份原PDF文件,避免意外修改导致数据丢失

内容的提问来源于stack exchange,提问作者Nature Lover

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 01:25:24