Extract Attachments from PDF in Java

This article demonstrates how to extract attachments from a PDF document using Spire.PDF for Java.

The example PDF document:

Extract Attachments from PDF in Java

import com.spire.pdf.PdfDocument;
import com.spire.pdf.attachments.PdfAttachmentCollection;

import java.io.*;

public class ExtractAttachments {
    public static void main(String[] args) throws IOException {
        //Load the PDF document
        PdfDocument pdf = new PdfDocument();
        pdf.loadFromFile("AddAttachments.pdf");

        //Get the attachment collection of the PDF document
        PdfAttachmentCollection attachments = pdf.getAttachments();

        //Loop through the collection and extract each attachment in the PDF document
        for (int i = 0; i < attachments.getCount(); i++) {
            File file = new File("Attachments/"+attachments.get(i).getFileName());
            OutputStream output = new FileOutputStream(file);

            BufferedOutputStream bufferedOutput = new BufferedOutputStream(output);

            bufferedOutput.write(attachments.get(i).getData());
            bufferedOutput.close();
        }
    }
}

Output:

Extract Attachments from PDF in Java