Hi,
I am trying to add a watermark to an existing PDF file. For some reason, it appears correctly on top of text but clips behind any existing images in the PDF file.
My code is almost identical to the snippet on Add watermark to PDF|Aspose.PDF for Java
How can I make the watermark appear on top of text as well as images?
@petarian
Can you please share the sample PDF as well as the generated output for our reference so that we can also test the scenario in our environment and address it accordingly.
Sure. I am attaching two files. First, an Excel sheet was converted to PDF using the Aspose-cells-java and saved as test-original.pdf. Then, a watermark was added using Aspose-pdf-java and saved to test-with-watermark.pdf.
I can’t upload the Excel sheet to this forum, but I can send it to you through a download link if needed.
test-original.pdf (175.4 KB)
test-with-watermark.pdf (180.2 KB)
Here is another example of a PDF file with only text. For some reason, I am unable to add a watermark to this PDF as well.
Note that some other PDFs work fine.
NoWatermark.pdf (17.4 KB)
@petarian
We used below code snippet in our environment and obtained attached outputs. We could not find any issues with them. Can you please try to use the below code snippet?
Document doc = new Document(dataDir + "NoWatermark.pdf");
com.aspose.pdf.facades.FormattedText formattedText = new com.aspose.pdf.facades.FormattedText(
"Watermark", java.awt.Color.BLUE, com.aspose.pdf.facades.FontStyle.Courier,
com.aspose.pdf.facades.EncodingType.Identity_h, true, 72.0F);
for (int i = 1; i <= doc.getPages().size(); i++) {
WatermarkArtifact artifact = new WatermarkArtifact();
artifact.setText(formattedText);
// artifact.setArtifactHorizontalAlignment(HorizontalAlignment.Center);
// artifact.setArtifactVerticalAlignment(VerticalAlignment.Center);
Point waterMarkPos = new Point(200, 200);
artifact.setPosition(waterMarkPos);
artifact.setBackground(false);
artifact.setRotation(45);
artifact.setOpacity(0.5);
doc.getPages().get_Item(i).getArtifacts().add(artifact);
}
doc.save(dataDir + "NoWatermark_out.pdf");
Excellent. This code is working great.
The magic line making a difference was:
artifact.setBackground(false);
The code snippet on Add watermark to PDF|Aspose.PDF for Java uses “true” for the background, which I used and was causing problems.