This article guides how to add an attachment to PDF in Java. It has information to set the development environment, a list of steps to develop the program, and a runnable sample code to add attachment in PDF in Java. You can run the sample code in any of the environments supporting Java environment without installing any other third-party tool or software like Adobe Acrobat.
Steps to Embed Attachment in PDF in Java
- Configure the IDE to add Aspose.PDF for Java to embed attachments
- Instantiate the FileSpecification to set the attachment file name and introduction
- Load the source PDF file with the Document class object where an attachment is to be added
- Use the getEmbeddedFiles() to access the collection and add the new attachment using the FileSpecification object
- Save the output PDF file with embedded attachments
These steps describe the process to insert attachment in PDF in Java. In the first step, a FileSpecification object is created that requires the attachment file name and the description. Finally, the source PDF file is loaded into the Document and getEmbeddedFiles().add() method is called to add the attachment to PDF by setting the key and FileSpecification object.
Code to Insert File in PDF in Java
The aforementioned code demonstrates the process of how to attach a file to a PDF in Java. The FileSpecification class object is used to link an Excel file to it along with the description however you may add any type of file here. Note that EmbeddedFiles collection class not only supports adding an attachment but you may also delete an attachment by name or key, check if an embedded file exists or not, and find a file by name.
This article has taught us how to add attachments to PDF in Java. If you want to learn the process to add graphical objects to a PDF file for instance a circle, refer to the article on how to add circle in PDF using Java.