Extract Attachments from a PDF - Java

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

Overview  
Summary This tutorial covers how to extract PDF attachments and convert them to PNG files in a Java application.
Completion Time 30 minutes
Project Download tutorial project (2 KB)
Platform Java Application
IDE Eclipse / IntelliJ
Runtime 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 - Java 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 that project is unavailable, follow the steps in that tutorial to create it.

The references needed depend upon the purpose of the project. References can be added by local .jar files located at <INSTALL_DIR>\LEADTOOLS22\Bin\Java.

For this project, the following references are needed:

For a complete list of which JAR files are required for your application, refer to Files to be Included with your Java 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 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.

Open the _Main.java class in the Package Explorer. Add the following statements to the import block at the top.

Java
import java.io.*; 
import java.nio.file.*; 
import java.util.ArrayList; 
 
import leadtools.*; 
import leadtools.codecs.*; 
import leadtools.document.*; 
import leadtools.document.converter.*; 
import leadtools.document.writer.*; 

Add the following global variable to the _Main class.

Java
private String outputDir; 

Inside the run() method, add the following to set the library path to where the C DLL files are located, as well as load the LEADTOOLS libraries that were previously imported.

Java
public static void main(String[] args) throws IOException  
{ 
	new _Main().run(args); 
} 
private void run(String[] args) { 
	try { 
		Platform.setLibPath("C:\\LEADTOOLS22\\Bin\\CDLL\\x64"); 
	    Platform.loadLibrary(LTLibrary.LEADTOOLS); 
	    Platform.loadLibrary(LTLibrary.CODECS); 
	    Platform.loadLibrary(LTLibrary.DOCUMENT); 
	    Platform.loadLibrary(LTLibrary.DOCUMENT_CONVERTER); 
	    Platform.loadLibrary(LTLibrary.DOCUMENT_WRITER); 
	    Platform.loadLibrary(LTLibrary.IMAGE_PROCESSING_CORE); 
			 
		SetLicense(); 
		ExtractPDFAttachments(); 
	}  
	catch(Exception ex) { 
		System.err.println(ex.getMessage()); 
		ex.printStackTrace(); 
	} 
} 

Add a new method to the _Main class named ExtractPDFAttachments(). Call this method inside the run() method below the call to the SetLicense() method, as shown above. Add the code to the ExtractPDFAttachments() method to extract the attachments from the given PDF.

Java
private void ExtractPDFAttachments() 
{ 
	ArrayList<LEADDocument> documents = new ArrayList<>(); 
 
	outputDir = "FILE PATH TO OUTPUT DIRECTORY"; 
	     
	File tempOutput = new File(outputDir); 
	if (!tempOutput.exists()) 
	    tempOutput.mkdir(); 
 
	LoadDocumentOptions options = new LoadDocumentOptions(); 
	options.setLoadAttachmentsMode(DocumentLoadAttachmentsMode.AS_ATTACHMENTS); 
 
	String loadFile = "FILE PATH TO PDF WITH ATTACHMENTS"; 
	LEADDocument document = DocumentFactory.loadFromFile(loadFile, options); 
 
	if (document.getPages().size() > 0) 
	    documents.add(document); 
 
	for (DocumentAttachment attachment : document.getAttachments()){ 
	    LoadAttachmentOptions attachmentOptions = new LoadAttachmentOptions(); 
	    attachmentOptions.setAttachmentNumber(attachment.getAttachmentNumber()); 
	    LEADDocument loadDocument = document.loadDocumentAttachment(attachmentOptions); 
	    documents.add(loadDocument); 
	} 
 
	ConvertDocuments(documents, RasterImageFormat.PNG); 
} 

Add a new method to the _Main class named ConvertDocuments(ArrayList<LEADDocument> documents, RasterImageFormat imageFormat). Call this method inside the ExtractPDFAttachments() method, as shown above. Add the code below to the ConvertDocuments() method to convert the PDF attachments to PNG files.

Java
private void ConvertDocuments(ArrayList<LEADDocument> documents, RasterImageFormat imageFormat) 
{ 
	DocumentConverter converter = new DocumentConverter(); 
 
	for (LEADDocument document : documents){ 
	    String name = (document.getName() == null || document.getName().isEmpty()) ? "DocumentAttachment" : document.getName(); 
	    String outputFile = Paths.get(outputDir, name + "." + RasterCodecs.getExtension(imageFormat)).toAbsolutePath().toString(); 
	        int count = 1; 
	        while ((new File(outputFile)).exists()) 
	            outputFile = Paths.get(outputDir, name + "(" + count++ + ")." + RasterCodecs.getExtension(imageFormat)).toAbsolutePath().toString(); 
 
	    DocumentConverterJobData jobData = new DocumentConverterJobData(); 
	    jobData.setDocument(document); 
	    jobData.setDocumentFormat(DocumentFormat.USER); 
	    jobData.setRasterImageFormat(imageFormat); 
	    jobData.setRasterImageBitsPerPixel(0); 
	    jobData.setOutputDocumentFileName(outputFile); 
 
	    DocumentConverterJob job = converter.getJobs().createJob(jobData); 
	    converter.getJobs().runJob(job); 
	         
	    if (job.getErrors().size() > 0) 
	        for(var error : job.getErrors()) 
	        	System.out.println("Error during conversion: " + error.getError().getMessage() + "\n"); 
	    else 
	        System.out.println("Successfully converted: " + outputFile + "\n"); 
	} 
} 

Run the Project

Run the project by pressing Ctrl + F11, or by selecting Run -> Run.

If the steps were followed correctly, the application extracts the PDF attachments and converts them to raster PNG files.

Wrap-up

This tutorial showed how to extract PDF attachments using the loadDocumentAttachment() method and converts 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.