
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
- Extract PDF Attachment Information using Java
- Add an Attachment to PDF in Java
- Remove Attachments from PDF in Java
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:
- Load the PDF with the
Document4 class. - Access the
FileSpecification5 object viaDocument.getEmbeddedFiles().get_Item(int). - Read the attachment properties from the
FileSpecificationinstance.
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:
- Open the target PDF with the
Document7 class. - Create a
FileSpecification8 object that points to the file you want to embed. - Call
Document.getEmbeddedFiles().add(FileSpecification)9 to attach the file. - 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:
- Load the PDF with the
Document11 class. - Use
Document.getEmbeddedFiles().delete()to clear all attachments, orDocument.getEmbeddedFiles().delete(String)13 to delete a specific file. - 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.