Work with Attachments in PDF via Java

How to Get, Add, Save, and Delete Attachments from PDF programmatically with Java

How to Manage Attachments Using Java Library

In order to add Attachments, we’ll use Aspose.PDF for Java API which is a feature-rich, powerful and easy to use conversion API for Java platform. You can download its latest version directly from Maven and install it within your Maven-based project by adding the following configurations to the pom.xml.

Repository

<repository>
    <id>AsposeJavaAPI</id>
    <name>Aspose Java AP</name>
    <url>https://releases.aspose.com/java/repo/</url>
</repository>

Dependency

<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-pdf</artifactId>
<version>version of aspose-pdf API</version>
</dependency>

Work with Attachments in PDF via Java


You need Aspose.PDF for Java to try the code in your environment.

  1. Create a new Java project.
  2. Add a reference to Aspose.PDF DLL.
  3. Create a Document object.
  4. Create a FileSpecification object with the file you are adding, and file description.
  5. Add the FileSpecification object to the Document object’s EmbeddedFiles collection, with the collection’s Add method
  6. Save the PDF file.

Adding Attachment to PDF document


// Open a document
Document pdfDocument = new Document(_dataDir+"input.pdf");
// Set up a new file to be added as attachment
FileSpecification fileSpecification = 
  new FileSpecification("sample.txt", "Sample text file");
// Add an attachment to document's attachment collection
pdfDocument.getEmbeddedFiles().add(fileSpecification);
// Save the updated document
pdfDocument.save("output.pdf");