使用 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());
}
}