如何在 Java 中使用注释

如何在 Java 中使用注释

本指南展示了如何使用针对 Java 的 Aspose.PDF 开源软件创建、计数、删除和扁平化 PDF 批注。您将学习如何添加小部件、自由文本和高亮批注,并使用 PdfAnnotationEditor 进行批量操作。

添加小部件批注

WidgetAnnotation 表示一个表单控件小部件。通过 AppearanceCharacteristics 设置边框颜色和标题。配置好批注后,将其添加到页面的批注集合中并保存文档:

try (Document doc = new Document()) {
    PageCollection pages = doc.getPages();
    Page page = pages.add();
    WidgetAnnotation w = new WidgetAnnotation(page, new Rectangle(50, 50, 150, 80));
    w.getCharacteristics().setBorder(Color.fromRgb(0, 0, 1));
    w.getCharacteristics().setCaption("Submit");
    page.getAnnotations().add(w);
    doc.save("widget.pdf");
}

添加自由文本批注

一个 FreeTextAnnotation 在页面的特定位置显示文本评论。默认外观定义了批注文本的字体、大小和颜色:

try (Document doc = new Document()) {
    PageCollection pages = doc.getPages();
    Page page = pages.add();
    DefaultAppearance da = new DefaultAppearance("Helv", 12, Color.BLACK);
    FreeTextAnnotation fta = new FreeTextAnnotation(page,
        new Rectangle(100, 300, 350, 350), da);
    fta.setContents("Review this section carefully.");
    page.getAnnotations().add(fta);
    doc.save("freetext.pdf");
}

添加高亮批注

HighlightAnnotation 在页面上可视化标记文本区域。使用覆盖要高亮文本的 Rectangle 来定位它,然后将其添加到注释集合中:

try (Document doc = new Document("input.pdf")) {
    PageCollection pages = doc.getPages();
    Page page = pages.get(1);
    HighlightAnnotation h = new HighlightAnnotation(page,
        new Rectangle(100, 200, 400, 220));
    page.getAnnotations().add(h);
    doc.save("highlighted.pdf");
}

统计页面上的注释

直接访问页面的注释集合以统计或遍历注释:

try (Document doc = new Document("input.pdf")) {
    PageCollection pages = doc.getPages();
    Page page = pages.get(1);
    int count = page.getAnnotations().size();
    System.out.println("Annotations on page 1: " + count);
}

按类型删除注释

使用 PdfAnnotationEditor 从文档中删除所有特定类型的注释。使用注释类型名称调用 deleteAnnotations(type),然后保存:

try (PdfAnnotationEditor editor = new PdfAnnotationEditor()) {
    editor.bindPdf("input.pdf");
    editor.deleteAnnotations("Highlight");
    editor.save("output.pdf");
}

展平注释

展平注释会将其永久合并到页面内容中,从而不再能作为独立对象进行编辑或删除:

try (PdfAnnotationEditor editor = new PdfAnnotationEditor()) {
    editor.bindPdf("annotated.pdf");
    editor.flattenAnnotations();
    editor.save("flat.pdf");
}

另请参阅

 中文