Remove Attachments from PDF in Java
Contents
[
Hide
]
Attachments stored in a PDF document can be removed either individually or all at once through the EmbeddedFiles collection.
Remove a single attachment
Use this example when one named embedded file should be deleted from the PDF.
- Open the source PDF Document.
- Delete the attachment by its key from the embedded files collection.
- Save the updated output document.
public static void removeAttachment(Path inputFile, String attachmentName, Path outputFile) {
try (Document document = new Document(inputFile.toString())) {
document.getEmbeddedFiles().deleteByKey(attachmentName);
document.save(outputFile.toString());
}
}
Remove all attachments
Use this approach when the entire embedded file collection should be cleared.
- Open the source PDF Document.
- Delete all items from the embedded files collection.
- Save the cleaned output document.
public static void removeAllAttachments(Path inputFile, Path outputFile) {
try (Document document = new Document(inputFile.toString())) {
document.getEmbeddedFiles().delete();
document.save(outputFile.toString());
}
}