Watermark on pdf not working properlly

426 views Asked by At

I am creating pdf using itextsharp. Now I want to add watermark on each pages I tried method on

public override void OnStartPage(PdfWriter wr, iTextSharp.text.Document doc)

Now watermark is coming but if pdf page containing image then its hiding watermark

public class itsevent : PdfPageEventHelper
{
    string watermarkText = string.Empty;
    public itsevent(string watermark)
    {
        watermarkText = watermark;
    } 

    public override void OnStartPage(PdfWriter wr, iTextSharp.text.Document doc)
    {
        float fontSize = 80;
        float xPosition = 300;
        float yPosition = 300;
        float angle = 45;
        PdfContentByte u = wr.DirectContentUnder;
        PdfGState gs = new PdfGState();
        u.SaveState();
        u.SetGState(gs);
        BaseFont baseFont =BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
        u.BeginText();
        u.SetColorFill(iTextSharp.text.pdf.CMYKColor.LIGHT_GRAY);
        u.SetFontAndSize(baseFont, fontSize);
        u.ShowTextAligned(PdfContentByte.ALIGN_CENTER, watermarkText, xPosition, yPosition, angle);
        u.EndText();
        under.RestoreState();
    } 
}

itsevent ev = new itsevent("watermark");
pdfW.PageEvent = ev;
doc.Open();
2

There are 2 answers

9
JunaidKirkire On
0
mkl On

Which PdfContentByte to use

You use wr.DirectContentUnder which is for adding content under the normally added content:

PdfContentByte u = wr.DirectContentUnder;

Thus, obviously an image in the normal content will cover the watersign. Use wr.DirectContent instead.

Which page event to use

You are adding the watermark in OnStartPage; iText developers recommend against doing so. Instead do that in OnEndPage.

How to improve the looks

You might want to apply transparency by setting the fill opacity of PdfGState gs.