Remove Attachments from PDF in Java

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.

  1. Open the source PDF Document.
  2. Delete the attachment by its key from the embedded files collection.
  3. 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.

  1. Open the source PDF Document.
  2. Delete all items from the embedded files collection.
  3. 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());
    }
}