Extract Attachments from PDF via Python

Extract Attachments from PDF document. Use Aspose.PDF for Python for .NET to modify PDF files programmatically

How to Extract Attachments Using Python for .NET Library

In order to extract Attachments in PDF file, we’ll use Aspose.PDF for .NET API which is a feature-rich, powerful and easy to use document manipulation API for python-net platform. Open NuGet package manager, search for Aspose.PDF and install. You may also use the following command from the Package Manager Console.

Python Package Manager Console

pip install aspose-pdf

Extract Attachments from PDF Python


You need Aspose.PDF for Python via .NET to try the code in your environment.

  1. Get embedded files collection.
  2. Get count of the embedded files.
  3. Loop through the collection to get all the attachments.
  4. Check if parameter object contains the parameters.
  5. Get the Attachment and write to file or stream.

Extract Attachment from PDF document

 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