Extract Attachments from a PDF - Python

This tutorial shows how to extract attachments included inside a PDF file in a Python application using the LEADTOOLS SDK.

Overview  
Summary This tutorial covers how to extract PDF attachments and convert them to PNG files in a Python Console application.
Completion Time 30 minutes
Visual Studio Project Download tutorial project (2 KB)
Platform Python Console Application
IDE Visual Studio 2022
Runtime Target Python 3.10 or higher
Development License Download LEADTOOLS
Try it in another language

Required Knowledge

Get familiar with the basic steps of creating a project by reviewing the Add References and Set a License tutorial, before working on the Extract Attachments from a PDF - Python tutorial.

Create the Project and Add LEADTOOLS References

Start with a copy of the project created in the Add References and Set a License tutorial. If the project is not available, follow the steps in that tutorial to create it.

If you do not have that project, follow the steps in the relevant tutorial to create it.

The references needed depend upon the purpose of the project.

This tutorial requires the following .NET DLLs:

For a complete list of which DLL files are required for your application, refer to Files to be Included With Your Application.

Set the License File

The License unlocks the features needed for the project. It must be set before any toolkit function is called. For details, including tutorials for different platforms, refer to Setting a Runtime License.

There are two types of runtime licenses:

Add the PDF Attachment Extraction and Conversion Code

With the project created, the references added, and the license set, coding can begin.

In the Solution Explorer, open Project-Name.py and place the following references below the "Add references to LEADTOOLS" comment

# Add references to LEADTOOLS 
from leadtools import LibraryLoader 
LibraryLoader.add_reference("Leadtools") 
from Leadtools import * 
LibraryLoader.add_reference("Leadtools.Codecs") 
from Leadtools.Codecs import * 
LibraryLoader.add_reference("Leadtools.Caching") 
from Leadtools.Caching import * 
LibraryLoader.add_reference("Leadtools.Document") 
from Leadtools.Document import * 
LibraryLoader.add_reference("Leadtools.Document.Converter") 
from Leadtools.Document.Converter import * 
LibraryLoader.add_reference("Leadtools.Document.Writer") 
from Leadtools.Document.Writer import * 
 
from System import * 
from System.IO import * 
from System.Collections.Generic import * 

Create a new method inside Project-Name.py named extract_pdf_attachments(). Call the method in the main() method, under the set license call, as shown below.

def main(): 
 
    Support.set_license(os.path.join(DemosTools.get_root(), "C:/LEADTOOLS22/Support/Common/License")) 
 
    global output_dir 
    output_dir = r"TARGET PATH FOR EXTRACTED ATTACHMENTS" 
 
    global cache 
    cache = FileCache() 
    cache.CacheDirectory = "\\cache" 
 
    extract_pdf_attachments() 

Add the code below to the extract_pdf_attachments() method to extract the attachments from the given PDF.

def extract_pdf_attachments(): 
     
    documents = List[LEADDocument]() 
 
    if not (Directory.Exists(output_dir)): 
        Directory.CreateDirectory(output_dir) 
    options = LoadDocumentOptions() 
    options.Cache = cache 
    options.LoadAttachmentsMode = DocumentLoadAttachmentsMode.AsAttachments  
 
    document = DocumentFactory.LoadFromFile(r"FILE PATH TO PDF WITH ATTACHMENTS", options) 
 
    if (document.Pages.Count > 0): 
        documents.Add(document) 
    for attachment in document.Attachments: 
        attachment_options = LoadAttachmentOptions() 
        attachment_options.AttachmentNumber = attachment.AttachmentNumber 
        load_document = document.LoadDocumentAttachment(attachment_options) 
        documents.Add(load_document) 
 
    convert_documents(documents, RasterImageFormat.Png) 

Inside the Project-Name.py file, add a new method named convert_documents(documents, image_format). This method will be called inside the extract_pdf_attachments() method, as shown above. Add the code below to the convert_documents() method to convert the PDF attachments to PNG files.

def convert_documents(documents, image_format): 
 
    converter = DocumentConverter() 
 
    for document in documents: 
        name = "DocumentAttachment" if not document.Name else document.Name  
        output_file = Path.Combine(output_dir, f"{name}.{RasterCodecs.GetExtension(image_format)}") 
        count = 1 
        while (File.Exists(output_file)): 
            count += 1 
            output_file = Path.Combine(output_dir, f"{name}({count}).{RasterCodecs.GetExtension(image_format)}") 
         
        job_data = DocumentConverterJobData() 
        job_data.Document = document 
        job_data.Cache = cache 
        job_data.DocumentFormat = DocumentFormat.User 
        job_data.RasterImageFormat = image_format 
        job_data.RasterImageBitsPerPixel = 0 
        job_data.OutputDocumentFileName = output_file 
 
        job = converter.Jobs.CreateJob(job_data) 
        converter.Jobs.RunJob(job) 
 
        if (job.Errors.Count > 0): 
            for error  in job.Errors: 
                print(f"Error during conversion: {error.Error.Message} \n") 
        else: 
            print(f"Successfully converted to {output_file}... \n") 

Run the Project

Run the project by pressing F5, or by selecting Debug -> Start Debugging.

If the steps were followed correctly, the application runs and converts all the attachments in the given PDF file to separate PNG files.

Wrap-up

This tutorial showed how to extract PDF attachments using the LoadDocumentAttachment() method and convert them to raster images. Also, it covered how to use the LEADDocument, DocumentConverter, and LoadAttachmentOptions classes.

See Also

Help Version 22.0.2024.3.20
Products | Support | Contact Us | Intellectual Property Notices
© 1991-2023 LEAD Technologies, Inc. All Rights Reserved.

Products | Support | Contact Us | Intellectual Property Notices
© 1991-2023 LEAD Technologies, Inc. All Rights Reserved.