使用 Python 创建 PDF 目录

本主题涉及 使用 Python 在 PDF 中创建目录的过程。它涵盖了建立开发环境的详细信息、步骤列表以及使用 Python 在 PDF 中添加目录的工作代码。您还将了解目录的配置,包括超链接、文本以及与 PDF 文件中不同页面的连接。

使用 Python 将目录添加到 PDF 的步骤

  1. 将环境设置为 通过 .NET 使用 Aspose.PDF for Python 以添加目录
  2. 访问示例 PDF Document 并在开头插入一个页面以添加目录
  3. 创建 TocInfo 和 TextFragment 类的实例以设置目录标题
  4. 设置目录的标题文本
  5. 遍历所有 PDF 页面以添加相应的 TOC 标题
  6. 在每次迭代期间设置目标页面、其坐标和标题文本
  7. 保存生成的 PDF 文件,首页上包含 TOC

上述步骤展示了 **使用 Python 创建可点击的 PDF 目录的过程。访问源 PDF 文件,在文档开头添加一个页面来保存目录,并使用 TocInfo 和 TextFragment 的实例来设置 TOC 的特征。对于加载的 PDF 文档中的每个页面,在目录中插入一个超链接,设置其文本并链接到所需页面。

使用 Python 将可点击目录添加到 PDF 的代码

import aspose.pdf as pdf
# Set the source directory path
filePath = "C://Words//"
# Load the license in your application to create TOC in PDF
pdf.License().set_license(filePath + "Conholdate.Total.Product.Family.lic")
# Open the sample PDF document file from the disk
pdfDoc = pdf.Document(filePath + "Sample.pdf")
# Insert a page for table of contents
pageTOC = pdfDoc.pages.insert(1)
# Instantiate an object of TocInfo for TOC information
tocInfo = pdf.TocInfo()
# Create an object of TextFragment for setting TOC title
title = pdf.text.TextFragment("Table Of Contents")
title.text_state.font_size = 20
# Set the title for Table of contents
tocInfo.title = title
pageTOC.toc_info = tocInfo
# Generate a list of strings for TOC
tocTitles = []
# Get count of pages in the PDF
count = pdfDoc.pages.length
for j in range(0, count):
tocTitles.insert(j, "Page "+ str(j + 1))
i = 0
while i < count:
# Instantiate an object of the Heading class
heading = pdf.Heading(1)
heading.toc_page = pageTOC
# Set the destination page for the heading object
heading.destination_page = pdfDoc.pages[i + 1]
# Set the destination coordinates for TOC item
heading.top = pdfDoc.pages[i +1].rect.height
# Set TOC item text
textSegment = pdf.text.TextSegment()
textSegment.text = tocTitles[i]
segments = heading.segments.append(textSegment)
# Add heading to the TOC page
pageTOC.paragraphs.add(heading)
i += 1
# Save document with TOC
pdfDoc.save("outputwithToc.pdf")
print ("Opeartion finished successfully")

此示例演示如何使用 Python 在 PDF 中添加目录。在本示例中,目录内容是通过使用页码生成字符串列表来手动生成的。但是,您可以解析文件内容并将其设置为类似于标准目录,其中在 TOC 内使用 PDF 内容的标题,并将它们与 PDF 文件中所需的内容链接。

本主题教会了我们如何使用 Python 创建 PDF 目录。如果您有兴趣在 PDF 文件的内容中添加超链接,请参阅有关 如何使用Python在PDF中添加超链接 的文章。

 简体中文