Skip to content

Instantly share code, notes, and snippets.

@aspose-com-gists
Last active July 1, 2021 05:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aspose-com-gists/b5f7f2262b678f17cf0d7b1e318d092e to your computer and use it in GitHub Desktop.
Save aspose-com-gists/b5f7f2262b678f17cf0d7b1e318d092e to your computer and use it in GitHub Desktop.
Add Text or Image Watermark in PDF using Java
// Load PDF document
Document doc = new Document("input.pdf");
// Create a background artifact
BackgroundArtifact background = new BackgroundArtifact();
// Specify the image for background artifact object
background.setBackgroundImage(new FileInputStream("logo.png"));
background.setOpacity(0.5);
background.setArtifactHorizontalAlignment(HorizontalAlignment.Center);
background.setArtifactVerticalAlignment(VerticalAlignment.Center);
// Add watermark to the first page of PDF
doc.getPages().get_Item(1).getArtifacts().add(background);
// Save watermarked PDF document
doc.save("watermark.pdf");
// Load PDF document
Document doc = new Document("input.pdf");
// Create a formatted text
FormattedText formattedText = new FormattedText("Confidential Document", java.awt.Color.RED, FontStyle.Courier, EncodingType.Identity_h, true, 40.0F);
// Create watermark artifact and set its properties
WatermarkArtifact artifact = new WatermarkArtifact();
artifact.setText(formattedText);
artifact.setArtifactHorizontalAlignment (HorizontalAlignment.Center);
artifact.setArtifactVerticalAlignment (VerticalAlignment.Center);
artifact.setRotation (25);
artifact.setOpacity (0.5);
artifact.setBackground (false);
// Add watermark to the first page of PDF
doc.getPages().get_Item(1).getArtifacts().add(artifact);
// Save watermarked PDF document
doc.save("watermark.pdf");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment