通过 Python 处理 PDF 文档中的附件

如何使用 Python 以编程方式从 PDF 中获取、添加、保存和删除附件。

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

为了在 PDF 文件中添加附件,我们将使用 Aspose.PDF for .NET API,这是一款功能丰富、功能强大且易于使用的适用于 python-net 平台的文档处理 API。打开 NuGet 软件包管理器,搜索 aspose.pdf 然后安装。您也可以从软件包管理器控制台使用以下命令。

Python Package Manager Console

pip install aspose-pdf

通过 Python 处理 PDF 格式的附件


你需要 Aspose.PDF for .NET 才能在你的环境中试用代码。

1.创建一个新的 Python 项目。 1.添加对 Aspose.PDF DLL 的引用。 1.创建文档对象。 1.使用要添加的文件和文件描述创建一个 FileSpecification 对象。 1.使用集合的 Add 方法将 FileSpecification 对象添加到 Document 对象的 EmbeddedFiles 集合中 1.保存 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)