Extract Attachments from a PDF - Console C#

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

Overview  
Summary This tutorial covers how to extract PDF attachments and convert them to PNG files in a C# Windows Console application.
Completion Time 30 minutes
Visual Studio Project Download tutorial project (3 KB)
Platform C# Windows Console Application
IDE Visual Studio 2017, 2019
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 - Console C# 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 you do not have that project, follow the steps in that tutorial to create it.

The references needed depend upon the purpose of the project. References can be added by one or the other of the following two methods (but not both).

If using NuGet references, this tutorial requires the following NuGet package:

If using local DLL references, the following DLLs are needed.

The DLLs are located at <INSTALL_DIR>\LEADTOOLS21\Bin\Dotnet4\x64:

For a complete list of which DLL files are required for your application, refer to Files to be Included in 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:

Note

Adding LEADTOOLS NuGet and local references and setting a license are covered in more detail in the Add References and Set a License tutorial.

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 = "Output"; 

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

C#
static void Main(string[] args) 
{ 
    try 
    { 
        SetLicense(); 
        ExtractPDFAttachments(); 
    } 
    catch (Exception ex) 
    { 
        Console.WriteLine(ex.ToString()); 
    } 
    Console.WriteLine("Press any key to exit..."); 
    Console.ReadKey(true); 
} 

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.

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