I want to add a watermark to an existing PDF by using the following:
ITextSharp insert text to an existing pdf
The 3rd answer is working but if the PDF contains an image then the watermark is hidden behind it.
I want to add a watermark to an existing PDF by using the following:
ITextSharp insert text to an existing pdf
The 3rd answer is working but if the PDF contains an image then the watermark is hidden behind it.
For questions like this, please consult The Best iText Questions on StackOverflow. This book bundles hundreds of questions previously posted and answered on StackOverflow, including some answers from our closed issue tracker. This is such an answer that wasn't published on StackOverflow before:
If you have opaque shapes in your PDF (such as images, but also colored shapes), you need to add the Watermark on top of the existing content:
PdfContentByte canvas = pdfStamper.getOverContent(i);
Now the text will cover the images, but it may hide some important information. If you want to avoid this, you need to introduce transparency.
I have written a simple example that shows how this is done. It is called TransparentWatermark Let's take a look at the result:
First I add the text "This watermark is added UNDER the existing content" under the existing content. Part of the text is hidden (as you indicate in your question). Then I add the text "This watermark is added ON TOP OF the existing content" on top of the existing content. This may be sufficient, unless you fear that some crucial information will get lost by covering the existing content. In that case, take a look at how I add the text "This TRANSPARENT watermark is added ON TOP OF the existing content":
public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
PdfReader reader = new PdfReader(src);
int n = reader.getNumberOfPages();
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
PdfContentByte under = stamper.getUnderContent(1);
Font f = new Font(FontFamily.HELVETICA, 15);
Phrase p = new Phrase(
"This watermark is added UNDER the existing content", f);
ColumnText.showTextAligned(under, Element.ALIGN_CENTER, p, 297, 550, 0);
PdfContentByte over = stamper.getOverContent(1);
p = new Phrase("This watermark is added ON TOP OF the existing content", f);
ColumnText.showTextAligned(over, Element.ALIGN_CENTER, p, 297, 500, 0);
p = new Phrase(
"This TRANSPARENT watermark is added ON TOP OF the existing content", f);
over.saveState();
PdfGState gs1 = new PdfGState();
gs1.setFillOpacity(0.5f);
over.setGState(gs1);
ColumnText.showTextAligned(over, Element.ALIGN_CENTER, p, 297, 450, 0);
over.restoreState();
stamper.close();
reader.close();
}
Some extra tips and tricks:
saveState()
and restoreState()
when you change the graphics state. If you don't you may get undesirable effects such as other content that is affected by the changes you make (e.g. you don't want all the content to become transparent).