Annotations en filigrane utilisant Java
Contents
[
Hide
]
Les annotations en filigrane vous permettent de placer du contenu de superposition réutilisable sur une page tout en le gérant via la collection d’annotations.
Ajouter une annotation en filigrane
Utilisez cet exemple lorsque vous avez besoin d’une annotation de filigrane de texte avec des paramètres de police et une opacité personnalisés.
- Ouvrez le PDF source Document.
- Créez une WatermarkAnnotation et ajoutez-la à la page.
- Configurez le TextState, le texte du filigrane et l’opacité, puis enregistrez le document.
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());
}
}
Obtenir des annotations en filigrane
Cet exemple analyse la collection d’annotations et affiche le rectangle de chaque annotation en filigrane.
- Ouvrez le PDF source Document.
- Parcourez les annotations sur la page cible.
- Filtrez les annotations par AnnotationType.
Watermarket affichez leurs rectangles.
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());
}
}
}
}
Supprimer les annotations en filigrane
Utilisez cette approche lorsque les annotations de filigrane existantes doivent être supprimées du document.
- Ouvrez le PDF source Document.
- Collectez les annotations de type AnnotationType.
Watermark. - Supprimez les annotations collectées et enregistrez le fichier de sortie.
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());
}
}