Java でアノテーションを扱う方法
Java でアノテーションを扱う方法
このガイドでは、Java向けのAspose.PDF FOSS を使用して 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");
}