Add Attachments to PDF in Java
Contents
[
Hide
]
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.
- Open the source PDF Document.
- Create a FileSpecification for the file you want to embed.
- Add the file specification to the
EmbeddedFilescollection 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());
}
}