通過Python處理 PDF 文件中的附件

如何使用 Python以程式設計方式從 PDF 中獲取、添加、保存和刪除附件。

如何使用 Python for .NET 庫管理附件

為了在PDF檔中添加附件,我們將使用[Aspose.PDF用於.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處理 PDF 中的附件


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

  1. 建立新的 Python 專案。
  2. 添加對阿波斯.PDF DLL 的引用。
  3. 建立文件物件。
  4. 使用要新增的檔案和檔案描述建立檔案指定物件。
  5. 使用集合的 Add 方法將檔案指定物件添加到文件物件的嵌入檔集合中
  6. 保存 PDF 檔。

將附件添加到 PDF 文件。

    def attachment_add(self, infile, outfile):

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

        # Open document
        pdfDocument = Document(path_infile)

        # Setup new file to be added as attachment
        fileSpecification = FileSpecification(self.dataDir  + "test.txt", "Sample text file")

        # Add attachment to document's attachment collection
        pdfDocument.EmbeddedFiles.Add(fileSpecification)

        # Save new output
        pdfDocument.Save(path_outfile)