通过 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

从 PDF 中提取附件 Python


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

1.获取嵌入式文件集合。 1.获取嵌入文件的计数。 1.循环浏览集合以获取所有附件。 1.检查参数对象是否包含参数。 1.获取附件并写入文件或流。

将附件提取到 PDF 文档。

 def attachment_extract(self, infile):

        path_infile = self.dataDir + infile

        # Open document
        pdfDocument = Document(path_infile)

        # Get embedded files collection
        embeddedFiles = pdfDocument.EmbeddedFiles

        # Get count of the embedded files
        print ( "Total files : %d " % (embeddedFiles.Count))

        count = 1

        # Loop through the collection to get all the attachments

        for fileSpecification in embeddedFiles:
            print("Name: " + fileSpecification.Name)
            print("Description: " + fileSpecification.Description)
            print("Mime Type: " + fileSpecification.MIMEType)

            # Check if parameter object contains the parameters
            if (fileSpecification.Params != None):
                print("CheckSum: " + fileSpecification.Params.CheckSum)
                print("Creation Date: " + fileSpecification.Params.CreationDate)
                print("Modification Date " + fileSpecification.Params.ModDate)
                print("Size: " + fileSpecification.Params.Size)

                # Get the attachment and write to file or stream
                File.WriteAllBytes(self.dataDir + count + "_out" + ".txt", fileSpecification.Contents)

                count+=1