使用C#代码在 PDF 中创建目录

目录在提升文档的可读性和可导航性方面起着至关重要的作用。它为读者提供了文档结构的清晰概览,使他们能够快速定位并访问感兴趣的特定章节或信息。对于较长的文档(例如报告、书籍或学术论文)而言,这一点尤为重要,因为读者可能需要多次返回特定的章节或部分进行查阅。

本文将介绍如何使用 Spire.PDF for .NET 在 C# 和 VB.NET 中创建 PDF 文档的目录。

安装 Spire.PDF for .NET

首先,需要将 Spire.PDF for .NET 包中包含的 DLL 文件添加为 .NET 项目的引用。

这些 DLL 文件可以通过以下链接下载,或通过 NuGet 安装。

cs 复制代码
PM> Install-Package Spire.PDF

在 C# 和 VB.NET 中创建 PDF 目录

目录通常包括目录标题(例如 "Table of Contents")、目录内容、页码,以及可点击跳转到对应页面的交互动作。

使用 Spire.PDF for .NET 创建 PDF 目录时,可以按照以下步骤进行:

  1. 初始化 PdfDocument 类的实例。

  2. 使用 PdfDocument.LoadFromFile() 方法加载 PDF 文档。

  3. 通过 PdfDocument.Pages.Count 属性获取文档的页数。

  4. 使用 PdfDocument.Pages.Insert(0) 方法在文档开头插入一个新页面作为目录页。

  5. 使用 PdfPageBase.Canvas.DrawString() 方法在该页面上绘制目录标题、目录内容和页码。

  6. 通过 PdfActionAnnotation 类创建跳转动作,并使用 PdfNewPage.Annotations.Add() 方法将这些动作添加到页面中。

  7. 使用 PdfDocument.SaveToFile() 方法保存生成的结果文档。

示例代码如下:

cs 复制代码
using Spire.Pdf;
using Spire.Pdf.Actions;
using Spire.Pdf.Annotations;
using Spire.Pdf.General;
using Spire.Pdf.Graphics;
using System;
using System.Drawing;

namespace TableOfContents
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //初始化 PdfDocument 类的实例
            PdfDocument doc = new PdfDocument();
            //加载 PDF 文档
            doc.LoadFromFile("Sample.PDF");

            //获取文档的页数
            int pageCount = doc.Pages.Count;

            //在文档开头插入一个新页面作为目录页
            PdfPageBase tocPage = doc.Pages.Insert(0);

            //在新页面上绘制目录标题
            string title = "Table of Contents";
            PdfTrueTypeFont titleFont = new PdfTrueTypeFont(new Font("Arial", 20, FontStyle.Bold));
            PdfStringFormat centerAlignment = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
            PointF location = new PointF(tocPage.Canvas.ClientSize.Width / 2, titleFont.MeasureString(title).Height + 10);
            tocPage.Canvas.DrawString(title, titleFont, PdfBrushes.CornflowerBlue, location, centerAlignment);

            //在新页面上绘制目录内容
            PdfTrueTypeFont titlesFont = new PdfTrueTypeFont(new Font("Arial", 14));
            String[] titles = new String[pageCount];
            for (int i = 0; i < titles.Length; i++)
            {
                titles[i] = string.Format("This is page {0}", i + 1);
            }
            float y = titleFont.MeasureString(title).Height + 10;
            float x = 0;

            //在新页面上绘制目标页的页码
            for (int i = 1; i <= pageCount; i++)
            {
                string text = titles[i - 1];
                SizeF titleSize = titlesFont.MeasureString(text);

                PdfPageBase navigatedPage = doc.Pages[i];

                string pageNumText = (i + 1).ToString();
                SizeF pageNumTextSize = titlesFont.MeasureString(pageNumText);
                tocPage.Canvas.DrawString(text, titlesFont, PdfBrushes.CadetBlue, 0, y);
                float dotLocation = titleSize.Width + 2 + x;
                float pageNumlocation = tocPage.Canvas.ClientSize.Width - pageNumTextSize.Width;
                for (float j = dotLocation; j < pageNumlocation; j++)
                {
                    if (dotLocation >= pageNumlocation)
                    {
                        break;
                    }
                    tocPage.Canvas.DrawString(".", titlesFont, PdfBrushes.Gray, dotLocation, y);
                    dotLocation += 3;
                }
                tocPage.Canvas.DrawString(pageNumText, titlesFont, PdfBrushes.CadetBlue, pageNumlocation, y);

                //为目录页中的文本添加可点击的跳转动作
                location = new PointF(0, y);
                RectangleF titleBounds = new RectangleF(location, new SizeF(tocPage.Canvas.ClientSize.Width, titleSize.Height));
                PdfDestination Dest = new PdfDestination(navigatedPage, new PointF(-doc.PageSettings.Margins.Top, -doc.PageSettings.Margins.Left));
                PdfActionAnnotation action = new PdfActionAnnotation(titleBounds, new PdfGoToAction(Dest));
                action.Border = new PdfAnnotationBorder(0);
                (tocPage as PdfNewPage).Annotations.Add(action);
                y += titleSize.Height + 10;
            }

            //保存生成的 PDF 文档
            doc.SaveToFile("AddTableOfContents.pdf");
            doc.Close();
        }
    }
}

申请临时许可证

如果您希望去除生成文档中的评估提示信息,或解除功能限制,请申请一份为期 30 天的试用许可证。

相关推荐
Muyuan19986 小时前
27.RAG 系统中的上下文充分性判断:从 Chunk 数量、FAISS 距离到 LLM Relevance Gate
python·django·pdf·fastapi·faiss
开开心心就好11 小时前
近200个工具的电脑故障修复合集
安全·智能手机·pdf·电脑·consul·memcache·1024程序员节
其实秋天的枫12 小时前
2026年初中英语大纲词汇表1600词
经验分享·pdf
开开心心_Every13 小时前
轻量级PDF阅读器,仅几M大小打开秒开
linux·运维·服务器·安全·macos·pdf·phpstorm
福大大架构师每日一题14 小时前
ragflow v0.25.1 最新版发布:API 统一、PDF 解析性能大幅优化、连接器删除同步全面增强,更新要点一次看懂
pdf·ragflow
cosinmz2 天前
图片太多太乱怎么整理?分享一个我最近常用的图片转 PDF方法
经验分享·小程序·pdf
其实秋天的枫2 天前
2026年新高考英语大纲词汇表3500个电子版PDF(含正序版、乱序版和默写版)
经验分享·pdf
lijfrank2 天前
MacOS 下 VS Code + LaTeX + Skim 双向同步配置
vscode·macos·pdf·latex·mactex
程序员的记录2 天前
AI 实战 - 文档处理(pdf/work/md/txt...)
pdf
Muyuan19982 天前
22.让 RAG Agent 更像真实产品:聊天页面优化、PDF 上传、知识库重建与检索片段展示
python·django·pdf·fastapi