add or remove pdf attachments in java

PDF1 remains the dominant format for digital documents. In addition to its core capabilities, PDF supports embedded file attachments—similar to the files you attach to an email. This guide explains how to programmatically add, list, and delete PDF attachments using Java and the Aspose.PDF library.

Java API for PDF Attachments – Free Download

Aspose.PDF for Java2 is a powerful API that enables creation, editing, and manipulation of PDF documents directly from Java applications. It includes straightforward methods for adding and removing embedded files. You can either download the JAR file3 or integrate the library via Maven using the repository and dependency definitions below.

<repository>
    <id>AsposeJavaAPI</id>
    <name>Aspose Java API</name>
    <url>https://repository.aspose.com/repo/</url>
</repository>
<dependency>
    <groupId>com.aspose</groupId>
    <artifactId>aspose-pdf</artifactId>
    <version>20.10</version>
    <classifier>jdk17</classifier>
</dependency>

Extract PDF Attachment Information using Java

To list details of embedded files—such as name, description, MIME type, checksum, and modification date—follow these steps:

  1. Load the PDF with the Document4 class.
  2. Access the FileSpecification5 object via Document.getEmbeddedFiles().get_Item(int).
  3. Read the attachment properties from the FileSpecification instance.

The code snippet below demonstrates how to retrieve attachment metadata using Java.

Add an Attachment to PDF in Java

Adding a new file to a PDF involves these actions:

  1. Open the target PDF with the Document7 class.
  2. Create a FileSpecification8 object that points to the file you want to embed.
  3. Call Document.getEmbeddedFiles().add(FileSpecification)9 to attach the file.
  4. Save the updated PDF using Document.save(String)10.

The following example shows the complete process for embedding an attachment.

Remove Attachments from PDF in Java

You can delete a single attachment by name or remove all embedded files at once. Perform these steps:

  1. Load the PDF with the Document11 class.
  2. Use Document.getEmbeddedFiles().delete() to clear all attachments, or Document.getEmbeddedFiles().delete(String)13 to delete a specific file.
  3. Save the modified document with Document.save(String)14.

The code example below illustrates how to delete attachments programmatically.

Conclusion

This article covered the essential techniques for managing PDF attachments with Java. You now have step‑by‑step guidance and ready‑to‑run code for adding, extracting information, and removing embedded files using Aspose.PDF for Java. Explore additional features in the official documentation.

See Also