Java を使用した透かし注釈
Contents
[
Hide
]
透かし注釈を使用すると、ページ上に再利用可能なオーバーレイコンテンツを配置しながら、アノテーションコレクションを通じて管理できます。
透かし注釈の追加
カスタムフォント設定と不透明度を持つテキスト透かし注釈が必要な場合に、この例をご使用ください。
- ソース PDF の Document を開いてください。
- WatermarkAnnotation を作成し、ページに追加してください。
- 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());
}
}
透かしアノテーションの取得
この例では、アノテーションコレクションをスキャンし、各透かしアノテーションの矩形を出力します。
- ソース PDF の Document を開いてください。
- 対象ページのアノテーションを反復処理してください。
- 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());
}
}
}
}
透かしアノテーションの削除
既存の透かしアノテーションをドキュメントから削除する必要がある場合に、このアプローチを使用してください。
- ソース PDF の Document を開いてください。
- AnnotationType.
Watermarkのアノテーションを収集してください。 - 収集したアノテーションを削除し、出力ファイルを保存してください。
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());
}
}