This article demonstrates how to delete attachments and annotation attachments in a PDF document using Spire.PDF for Java.
Delete Attachments
import com.spire.pdf.attachments.PdfAttachmentCollection;
public class DeleteAttachments {
public static void main(String[] args) {
//load a PDF document
PdfDocument doc = new PdfDocument();
doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Attachments.pdf");
//get the attachments collection, not containing annotation attachments
PdfAttachmentCollection attachments = doc.getAttachments();
//remove all attachments
attachments.clear();
//remove a specific attachment
//attachments.removeAt(0);
//save to file
doc.saveToFile("output/DeleteAttachments.pdf");
doc.close();
}
}
Delete Annotation Attachments
import com.spire.pdf.annotations.PdfAnnotation;
import com.spire.pdf.annotations.PdfAnnotationCollection;
import com.spire.pdf.annotations.PdfAttachmentAnnotationWidget;
public class DeleteAnnotationAttachments {
public static void main(String[] args) {
//load a PDF document
PdfDocument doc = new PdfDocument();
doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Attachments.pdf");
//loop through the pages
for (int i = 0; i < doc.getPages().getCount(); i++) {
//get the annotations collection
PdfAnnotationCollection annotationCollection = doc.getPages().get(i).getAnnotationsWidget();
//loop through the annotations
for (Object annotation: annotationCollection) {
//determine if an annotation is an instance of PdfAttachmentAnnotationWidget
if (annotation instanceof PdfAttachmentAnnotationWidget){
//remove the attachment annotation
annotationCollection.remove((PdfAnnotation) annotation);
}
}
}
//save to file
doc.saveToFile("output/DeleteAnnotationAttachments.pdf");
doc.close();
}
}
