使用 Python 在 PDF 中创建书签

本主题介绍如何使用 Python 在 PDF 中创建书签。它包含设置环境的所有详细信息、步骤列表以及使用 Python 在 PDF 中插入书签的示例代码。您将学习如何为单个页面创建书签或将子书签添加到主书签。

使用 Python 为 PDF 添加书签的步骤

  1. 设置环境以使用 通过.NET 为 Python 提供 Aspose.PDF 创建书签
  2. 将源 PDF 文件加载到 Document 对象中以插入书签
  3. 通过设置标题创建新的书签实例
  4. 设置书签格式
  5. 使用 GoToAction() 方法设置目标页面
  6. 使用大纲集合中的append()方法添加书签
  7. Save 带有新书签的输出 PDF 文件

这些步骤描述了如何使用 Python 为 PDF 文档添加书签。加载源 PDF、创建书签、设置其参数,并定义单击此书签时针对特定页面的操作。最后,调用 outlines 集合中的 append() 方法添加新创建的书签并保存输出。

使用 Python 在 PDF 中添加书签的代码

import aspose.pdf as pdf
# Load License
license = pdf.License()
license.set_license("License.lic")
# Load the PDF file
pdf_document = pdf.Document("bookmark.pdf")
# Initialize a new bookmark instance
bookmark = pdf.OutlineItemCollection(pdf_document.outlines)
bookmark.title = "Sample Bookmark"
bookmark.italic = True
bookmark.bold = True
# Specify the destination page for the bookmark
bookmark.action = pdf.annotations.GoToAction(pdf_document.pages[1])
# Insert the bookmark into the outline collection of the document
pdf_document.outlines.append(bookmark)
# Save the modified PDF to the specified file
pdf_document.save("target_pdf.pdf")
print("Done")

此代码演示了如何使用 Python 向 PDF 添加书签。您可以重复书签创建过程,次数与要添加到 PDF 的书签数量相同。如果您想将书签作为子书签添加到书签中,则将子书签附加到主书签中,并将主书签附加到文档大纲集合中。

本文教我们如何在 PDF 中添加书签。有关在 PDF 中绘制线条,请参阅 使用 Python 在 PDF 上画线 上的文章。

 简体中文