Annotations

本指南展示如何使用 Annotation 类层次结构在 Aspose.PDF FOSS for Java 中添加、配置和删除 PDF 注释。您将学习创建小部件、自由文本、突出显示和圆形注释,并使用 PdfAnnotationEditor 将其扁平化或删除。

注释层次结构

抽象的 Annotation 类是所有 PDF 注释的基础。所有注释都位于 Page 上的 Rectangle 处,并通过 page.getAnnotations().add(annotation) 添加。

WidgetAnnotation

WidgetAnnotation 代表一个表单小部件。外观通过 AppearanceCharacteristics 控制,该接口提供 setBorder()、setBackground()、setRotate() 和 setCaption()。

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

FreeTextAnnotation

FreeTextAnnotation 在指定位置显示文本标注。它接受一个 DefaultAppearance 来设置注释文本的字体、大小和颜色。

DefaultAppearance da = new DefaultAppearance("Helv", 12, Color.BLACK);
FreeTextAnnotation fta = new FreeTextAnnotation(page,
    new Rectangle(50, 50, 200, 100), da);
fta.setContents("Review comment here");
page.getAnnotations().add(fta);

setCallout(double[][]) 为注释设置三点引线。getIntent() 返回注释的 FreeTextIntent 值。

标记注释

HighlightAnnotation 和 UnderlineAnnotation 使用四点标记文本跨度。getQuadPoints() 方法返回一个包含 8 个元素的数组,定义标记区域的四个角点。

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, 300, 220));
    page.getAnnotations().add(h);
    doc.save("highlighted.pdf");
}

CircleAnnotation 和 CaretAnnotation

CircleAnnotation 在给定的矩形内绘制椭圆;CaretAnnotation 在文本中标记插入点。两者都扩展自 Annotation,并共享相同的颜色和边框属性。

try (Document doc = new Document()) {
    PageCollection pages = doc.getPages();
    Page page = pages.add();
    CircleAnnotation circle = new CircleAnnotation(page, new Rectangle(100, 100, 200, 200));
    circle.setColor(Color.fromRgb(0, 0, 1));
    page.getAnnotations().add(circle);
    doc.save("circle.pdf");
}

扁平化注释

使用 PdfAnnotationEditor.flattenAnnotations() 将所有注释合并到页面内容流中,使其不可编辑。

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

按类型删除注释

使用 deleteAnnotations(type) 并提供注释类型名称,以删除绑定文档中每页的该类型的所有注释:

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

另请参阅

 中文