Spire.PDF中有PdfAttachment类和PdfAttachmentAnnotation类分别对应PDF中的附件和注释附件。本文介绍如何使用Spire.PDF for Java获取PDF文档中的附件和注释附件并进行删除。
删除附件
import com.spire.pdf.attachments.PdfAttachmentCollection;
public class DeleteAttachments {
public static void main(String[] args) {
//加载PDF文档
PdfDocument doc = new PdfDocument();
doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Attachments.pdf");
//获取附件集合(不包含注释附件)
PdfAttachmentCollection attachments = doc.getAttachments();
//删除所有附件
attachments.clear();
//删除指定附件
//attachments.removeAt(0);
//保存文档
doc.saveToFile("output/DeleteAttachments.pdf");
doc.close();
}
}
删除注释附件
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) {
//加载PDF文档
PdfDocument doc = new PdfDocument();
doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Attachments.pdf");
//遍历文档中的页
for (int i = 0; i < doc.getPages().getCount(); i++) {
//获取注释集合
PdfAnnotationCollection annotationCollection = doc.getPages().get(i).getAnnotationsWidget();
//遍历注释集合
for (Object annotation: annotationCollection) {
//判断注释是否为PdfAttachmentAnnotationWidget类型
if (annotation instanceof PdfAttachmentAnnotationWidget){
//删除注释附件
annotationCollection.remove((PdfAnnotation) annotation);
}
}
}
//保存文档
doc.saveToFile("output/DeleteAnnotationAttachments.pdf");
doc.close();
}
}