C# iTextSharp 生成 PDF 目录:一级目录、二级目录和页面定位
使用 iTextSharp 库在 C# 中为 PDF 文件创建一级目录和二级目录,并添加页面定位功能,方便用户快速导航到特定内容。
步骤
-
安装 iTextSharp 库 首先,确保您已经安装了 iTextSharp 库。可以通过 NuGet 包管理器安装 iTextSharp。
-
创建新的 PDF 文档
using iTextSharp.text;
using iTextSharp.text.pdf;
// 创建新的 PDF 文档
Document document = new Document();
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream('output.pdf', FileMode.Create));
document.Open();
- 创建目录结构
// 创建一级目录
PdfOutline root = new PdfOutline(writer.DirectContent.RootOutline, new PdfDestination(PdfDestination.FIT), '目录');
// 创建二级目录
PdfOutline chapter1 = new PdfOutline(root, new PdfDestination(PdfDestination.FIT), '章节1');
PdfOutline section1 = new PdfOutline(chapter1, new PdfDestination(PdfDestination.FIT), '1.1 小节1');
PdfOutline section2 = new PdfOutline(chapter1, new PdfDestination(PdfDestination.FIT), '1.2 小节2');
PdfOutline chapter2 = new PdfOutline(root, new PdfDestination(PdfDestination.FIT), '章节2');
PdfOutline section3 = new PdfOutline(chapter2, new PdfDestination(PdfDestination.FIT), '2.1 小节1');
PdfOutline section4 = new PdfOutline(chapter2, new PdfDestination(PdfDestination.FIT), '2.2 小节2');
// 将目录添加到 PDF 文档
writer.DirectContent.AddOutline(root);
- 添加内容和定位
// 添加内容
document.Add(new Paragraph('这是章节1的内容。'));
// 添加定位
section1.Destination = new PdfDestination(PdfDestination.FIT, writer.GetVerticalPosition(true));
// 添加内容
document.NewPage();
document.Add(new Paragraph('这是章节2的内容。'));
// 添加定位
section3.Destination = new PdfDestination(PdfDestination.FIT, writer.GetVerticalPosition(true));
- 关闭文档
// 关闭文档
document.Close();
通过上述步骤,您可以在生成的 PDF 文档中创建一级目录和二级目录,并且可以通过点击目录项来定位到相应的页面。
原文地址: https://www.cveoy.top/t/topic/qlWH 著作权归作者所有。请勿转载和采集!