How to Add Attachments to PDF in Java

How to Add Attachments to PDF in Java

There are multiple ways to add/delete attachments to existing PDF documents. Sometimes you need to attach/embed various documents in a single PDF file. However, automating this task using a Java PDF library will always save you time and effort. In this blog post, you will learn how to add attachments to PDF in Java programmatically. By the end of this guide, you will be able to build a PDF manipulator for your business application.

You will go through the following sections:

Java PDF library installation

This rich-featured library offers a wide range of features to process and manipulate PDF files programmatically. However, you can download the API or install it using the following Maven configurations.

 <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>
    <classifier>jdk17</classifier>
</dependency>

How to add attachments to PDF in Java

Let’s write a code snippet that embeds an attachment into a PDF file programmatically.

The steps are:

  1. Create an object of the Document class and load the PDF file.
  2. Set up a new file to be added as an attachment by initializing an instance of the FileSpecification class.
  3. Add an attachment to the document’s attachment collection by invoking the add method.
  4. Call the save method to save the updated document.

Copy & paste the following code into your main file:

Delete attachments from a PDF file programmatically

In addition, this Java PDF library also lets you delete/remove attachments by offering methods.

Please follow the steps and the code snippet below:

  1. Instantiate an instance of the Document class and open a PDF document.
  2. Delete all attachments by calling the delete method.
  3. Save the updated file by invoking the save method.

Get a Free License

You can avail a free temporary license to try the API without evaluation limitations.

Summing up

We can end this blog post here. You have gone through how to add attachments to PDF in Java. Further, you also have learned how to delete attachments from a PDF file programmatically. Moreover, you may visit the documentation to know the other cool features of this Java PDF library.

Moreover, we suggest you follow our Getting Started guide.

Finally, conholdate.com is writing new blog posts. Therefore, please stay in touch for regular updates.

Ask a question

You can let us know about your questions or queries on our forum.

FAQs

Can you insert an attachment into a PDF?

You may follow this link to go through the steps and the code snippet that adds attachments in a PDF file programmatically.

See Also