Extract Attachments from a PDF - C# .NET 6

This tutorial shows how to extract attachments included inside a PDF file in a C# .NET 6 application using the LEADTOOLS SDK.

Overview  
Summary This tutorial covers how to extract PDF attachments and convert them to PNG files in a C# .NET 6 application.
Completion Time 15 minutes
Visual Studio Project Download tutorial project (1 KB)
Platform C# .NET 6 Console Application
IDE Visual Studio 2022
Runtime Target .NET 6 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 this 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.

The references needed depend upon the purpose of the project. References can be added via NuGet packages.

This tutorial requires the following NuGet package:

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 Program.cs. Add the following statements to the using block at the top of Program.cs.

C#
using System; 
using System.Collections.Generic; 
using System.IO; 
using Leadtools; 
using Leadtools.Caching; 
using Leadtools.Codecs; 
using Leadtools.Document; 
using Leadtools.Document.Converter; 
using Leadtools.Document.Writer; 

Add the following global variable to the Program class.

C#
static FileCache cache; 
static string OutputDir = "TARGET PATH FOR EXTRACTED ATTACHMENTS"; 

Create a new method inside Program.cs named ExtractPDFAttachments(). Call the method in the Main() method, under the InitLEAD call, as shown below.

C#
static void Main(string[] args) 
{ 
    try 
    { 
        if (!InitLEAD()) 
            Console.WriteLine("Error setting license"); 
        else 
            Console.WriteLine("License file set successfully"); 
 
        ExtractPDFAttachments(); 
    } 
    catch (Exception ex) 
    { 
        Console.WriteLine(ex.ToString()); 
    } 
} 

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

C#
static void ExtractPDFAttachments() 
{ 
    cache = new FileCache { CacheDirectory = "\\cache" }; 
 
    List<LEADDocument> documents = new List<LEADDocument>(); 
 
    if (!Directory.Exists(OutputDir)) 
        Directory.CreateDirectory(OutputDir); 
 
    LoadDocumentOptions options = new LoadDocumentOptions 
    { 
        Cache = cache, 
        LoadAttachmentsMode = DocumentLoadAttachmentsMode.AsAttachments 
    }; 
 
    LEADDocument document = DocumentFactory.LoadFromFile(@"FILE PATH TO PDF WITH ATTACHMENTS", options); 
 
    if (document.Pages.Count > 0) 
        documents.Add(document); 
 
    foreach (DocumentAttachment attachment in document.Attachments) 
    { 
        LoadAttachmentOptions attachmentOptions = new LoadAttachmentOptions { AttachmentNumber = attachment.AttachmentNumber, }; 
        LEADDocument loadDocument = document.LoadDocumentAttachment(attachmentOptions); 
        documents.Add(loadDocument); 
    } 
 
    ConvertDocuments(documents, RasterImageFormat.Png); 
} 

Inside the Program class, add a new method named ConvertDocuments(IEnumerable<LEADDocument> documents, RasterImageFormat imageFormat). This method will be called inside the ExtractPDFAttachments() method, as shown above. Add the code below to the ConvertDocuments() method to convert the PDF attachments to PNG files.

C#
static void ConvertDocuments(IEnumerable<LEADDocument> documents, RasterImageFormat imageFormat) 
{ 
    DocumentConverter converter = new DocumentConverter(); 
 
    foreach (LEADDocument document in documents) 
    { 
        string name = string.IsNullOrEmpty(document.Name) ? "DocumentAttachment" : document.Name; 
        string outputFile = Path.Combine(OutputDir, $"{name}.{RasterCodecs.GetExtension(imageFormat)}"); 
        int count = 1; 
        while (File.Exists(outputFile)) 
            outputFile = Path.Combine(OutputDir, $"{name}({count++}).{RasterCodecs.GetExtension(imageFormat)}"); 
 
        DocumentConverterJobData jobData = new DocumentConverterJobData 
        { 
            Document = document, 
            Cache = cache, 
            DocumentFormat = DocumentFormat.User, 
            RasterImageFormat = imageFormat, 
            RasterImageBitsPerPixel = 0, 
            OutputDocumentFileName = outputFile, 
        }; 
        DocumentConverterJob job = converter.Jobs.CreateJob(jobData); 
        converter.Jobs.RunJob(job); 
 
        if (job.Errors.Count > 0) 
            foreach (var error in job.Errors) 
                Console.WriteLine($"Error during conversion: {error.Error.Message}\n"); 
        else 
            Console.WriteLine($"Successfully Converted to {outputFile}...\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.

Note

Ensure that you have replaced the filepath placeholders with valid paths before running the project.

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 23.0.2024.5.22
Products | Support | Contact Us | Intellectual Property Notices
© 1991-2024 LEAD Technologies, Inc. All Rights Reserved.

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