Add Attachments to PDF in Java

To attach a file to a PDF, load the source document, create a FileSpecification, add it to the embedded file collection, and save the result.

Add an attachment to a PDF document

Use this example when an external file should be embedded into an existing PDF.

  1. Open the source PDF Document.
  2. Create a FileSpecification for the file you want to embed.
  3. Add the file specification to the EmbeddedFiles collection and save the updated document.
public static void addAttachments(Path inputFile, Path attachmentPath, Path outputFile) {
    try (Document document = new Document(inputFile.toString())) {
        FileSpecification fileSpecification = new FileSpecification(attachmentPath.toString(), "Sample text file");
        document.getEmbeddedFiles().add(attachmentPath.getFileName().toString(), fileSpecification);
        document.save(outputFile.toString());
    }
}