Java を使用した透かし注釈

透かし注釈を使用すると、ページ上に再利用可能なオーバーレイコンテンツを配置しながら、アノテーションコレクションを通じて管理できます。

透かし注釈の追加

カスタムフォント設定と不透明度を持つテキスト透かし注釈が必要な場合に、この例をご使用ください。

  1. ソース PDF の Document を開いてください。
  2. WatermarkAnnotation を作成し、ページに追加してください。
  3. TextState、透かしテキスト、不透明度を設定し、ドキュメントを保存してください。
public static void watermarkAdd(Path inputFile, Path outputFile) {
    try (Document document = new Document(inputFile.toString())) {
        Page page = document.getPages().get_Item(1);

        WatermarkAnnotation watermarkAnnotation = new WatermarkAnnotation(
                page,
                new Rectangle(100, 100, 400, 200, true));

        page.getAnnotations().add(watermarkAnnotation);

        TextState textState = new TextState();
        textState.setForegroundColor(Color.getBlue());
        textState.setFontSize(25);
        textState.setFont(FontRepository.findFont("Arial"));

        watermarkAnnotation.setOpacity(0.5);
        watermarkAnnotation.setTextAndState(new String[]{"HELLO", "Line 1", "Line 2"}, textState);

        document.save(outputFile.toString());
    }
}

透かしアノテーションの取得

この例では、アノテーションコレクションをスキャンし、各透かしアノテーションの矩形を出力します。

  1. ソース PDF の Document を開いてください。
  2. 対象ページのアノテーションを反復処理してください。
  3. AnnotationType.Watermark でアノテーションをフィルタリングし、それらの矩形を出力してください。
public static void watermarkGet(Path inputFile) {
    try (Document document = new Document(inputFile.toString())) {
        for (Annotation a : document.getPages().get_Item(1).getAnnotations()) {
            if (a.getAnnotationType() == AnnotationType.Watermark) {
                System.out.println(a.getRect());
            }
        }
    }
}

透かしアノテーションの削除

既存の透かしアノテーションをドキュメントから削除する必要がある場合に、このアプローチを使用してください。

  1. ソース PDF の Document を開いてください。
  2. AnnotationType.Watermark のアノテーションを収集してください。
  3. 収集したアノテーションを削除し、出力ファイルを保存してください。
public static void watermarkDelete(Path inputFile, Path outputFile) {
    try (Document document = new Document(inputFile.toString())) {
        List<Annotation> toDelete = new ArrayList<>();
        for (Annotation a : document.getPages().get_Item(1).getAnnotations()) {
            if (a.getAnnotationType() == AnnotationType.Watermark) {
                toDelete.add(a);
            }
        }
        for (Annotation a : toDelete) {
            document.getPages().get_Item(1).getAnnotations().delete(a);
        }
        document.save(outputFile.toString());
    }
}

関連する注釈トピック