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

從 PDF Python中提取附件


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

  1. 抓取嵌入檔案集合。
  2. 抓取嵌入檔案的計數。 迴圈訪問集合以獲取所有附件。
  3. 檢查參數物件是否包含參數。
  4. 取得附件並寫入檔或流。

將附件提取到 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