通過Python處理 PDF 文件中的書籤

如何使用 Python以程式設計方式操作 PDF 中的書籤。

如何使用帶有 Python 庫的 PDF 文件中的書籤

為了在PDF檔中添加書籤,我們將使用[Aspose.PDF for.NET](https://products.aspose.com/pdf/net)API,這是一個功能豐富,功能強大且易於使用的文檔操作API,適用於 python-net 平臺。打開 [NuGet](https://www.nuget.org/packages/aspose.pdf) 包管理器,搜索“.PDF”並安裝。您也可以從程式包管理器主控台使用以下命令。

Python Package Manager Console

pip install aspose-pdf

通過Python使用書籤的步驟


您需要 [Aspose.PDF for .NET](https://releases.aspose.com/pdf/net) 在您的環境中嘗試代碼。

  1. 使用文件對象打開 PDF 文件。
  2. 建立書籤並定義其屬性。
  3. 將大綱專案集合添加到大綱集合。
  4. 再次儲存檔

<% bookmarks.code-block.text %>

將書籤加入到 PDF 文件 - Python。

<% bookmarks.code-block.subtitle %>

    def bookmark_add(self, infile, outfile):

        path_infile = self.dataDir + infile
        path_outfile = self.dataDir + outfile

        # Open document
        pdfDocument = Document(path_infile)

        # Create a bookmark object
        pdfOutline = OutlineItemCollection(pdfDocument.Outlines)
        pdfOutline.Title = "Test Outline"
        pdfOutline.Italic = True
        pdfOutline.Bold = True
        # Set the destination page number
        pdfOutline.Action = GoToAction(pdfDocument.Pages[1])
        # Add bookmark in the document's outline collection.
        pdfDocument.Outlines.Add(pdfOutline)

        # Save new output
        pdfDocument.Save(path_outfile)