获取、更新和扩展书签
以下代码片段也适用于 Aspose.PDF.Drawing 库。
获取书签
Document 对象的 OutlineCollection 集合包含 PDF 文件的所有书签。本文解释了如何从 PDF 文件中获取书签,以及如何获取特定书签所在的页面。
要获取书签,请循环遍历 OutlineCollection 集合,并获取 OutlineItemCollection 中的每个书签。OutlineItemCollection 提供对所有书签属性的访问。以下代码片段演示了如何从 PDF 文件中获取书签。
获取书签的页码
一旦您添加了书签,您可以通过获取与书签对象关联的目标 PageNumber 来找出它所在的页面。
.NET Core 3.1
Copy
private static void GetBookmarkPageNumber ( )
{
var dataDir = RunExamples . GetDataDir_AsposePdf_Bookmarks ();
using ( var bookmarkEditor = new Aspose . Pdf . Facades . PdfBookmarkEditor ())
{
bookmarkEditor . BindPdf ( dataDir + "GetBookmarks.pdf" );
Aspose . Pdf . Facades . Bookmarks bookmarks = bookmarkEditor . ExtractBookmarks ();
foreach ( var bookmark in bookmarks )
{
string strLevelSeparator = string . Empty ;
for ( int i = 1 ; i < bookmark . Level ; i ++)
{
strLevelSeparator += "----" ;
}
Console . WriteLine ( "{0}Title: {1}" , strLevelSeparator , bookmark . Title );
Console . WriteLine ( "{0}Page Number: {1}" , strLevelSeparator , bookmark . PageNumber );
Console . WriteLine ( "{0}Page Action: {1}" , strLevelSeparator , bookmark . Action );
}
}
}
.NET 8
Copy
private static void GetBookmarkPageNumber ( )
{
var dataDir = RunExamples . GetDataDir_AsposePdf_Bookmarks ();
using var bookmarkEditor = new Aspose . Pdf . Facades . PdfBookmarkEditor ();
bookmarkEditor . BindPdf ( dataDir + "GetBookmarks.pdf" );
Aspose . Pdf . Facades . Bookmarks bookmarks = bookmarkEditor . ExtractBookmarks ();
foreach ( var bookmark in bookmarks )
{
string strLevelSeparator = string . Empty ;
for ( int i = 1 ; i < bookmark . Level ; i ++)
{
strLevelSeparator += "----" ;
}
Console . WriteLine ( "{0}Title: {1}" , strLevelSeparator , bookmark . Title );
Console . WriteLine ( "{0}Page Number: {1}" , strLevelSeparator , bookmark . PageNumber );
Console . WriteLine ( "{0}Page Action: {1}" , strLevelSeparator , bookmark . Action );
}
}
从 PDF 文档中获取子书签
书签可以以层次结构组织,具有父书签和子书签。要获取所有书签,请循环遍历 Document 对象的 Outlines 集合。然而,要获取子书签,还需要循环遍历在第一次循环中获得的每个 OutlineItemCollection 对象中的所有书签。以下代码片段演示了如何从 PDF 文档中获取子书签。
更新 PDF 文档中的书签
要更新 PDF 文件中的书签,首先,通过指定书签的索引从 Document 对象的 OutlineColletion 集合中获取特定书签。一旦您将书签检索到 OutlineItemCollection 对象中,您可以更新其属性,然后使用 Save 方法保存更新后的 PDF 文件。以下代码片段演示了如何在 PDF 文档中更新书签。
更新 PDF 文档中的子书签
要更新子书签:
通过首先获取父书签,然后使用适当的索引值获取子书签,从 PDF 文件中检索您要更新的子书签。
使用 Save 方法保存更新后的 PDF 文件。
通过指定书签的索引,从 Document 对象的 OutlineCollection 集合中获取书签,然后通过指定该父书签的索引获取子书签。
以下代码片段演示了如何在 PDF 文档中更新子书签。
查看文档时展开书签
书签保存在 Document 对象的 OutlineItemCollection 集合中,该集合本身在 OutlineCollection 集合中。然而,我们可能需要在查看 PDF 文件时将所有书签展开。
为了实现这一要求,我们可以将每个大纲/书签项的打开状态设置为打开。以下代码片段演示了如何在 PDF 文档中将每个书签的打开状态设置为展开。