C#中使用iTextSharp的PdfOutline生成PDF的一级目录二级目录并且可以定位到当前是第几页
在C#中使用iTextSharp的PdfOutline生成PDF的一级目录和二级目录,并且可以定位到当前是第几页,可以按照以下步骤进行操作:
-
首先,确保已经安装了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();
- 创建一级目录和二级目录,并添加到PDF文档中。
// 创建一级目录
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/iFoD 著作权归作者所有。请勿转载和采集!