Search code examples
itextwatermark

ItextSharp - Add text watermark on separate lines


I am trying to add a watermak on a pdf file with itextsharp 5.1.2.0 .

I want the watermark to be in the center of the page, with a 45° angle, with a border around these lines.

Here is my code :

 for (int i = 1; i <= reader.NumberOfPages; i++)
{
    iTextSharp.text.Rectangle pageSize = reader.GetPageSizeWithRotation(i);

    PdfContentByte pdfPageContents;
    pdfPageContents = pdfStamper.GetOverContent(i);

    pdfPageContents.BeginText();
    PdfGState gstate = new PdfGState();
    gstate.FillOpacity = 0.4f;
    gstate.StrokeOpacity = 0.4f;
    pdfPageContents.SaveState();
    pdfPageContents.SetGState(gstate);

    BaseFont baseFont = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, Encoding.ASCII.EncodingName, false);

    pdfPageContents.SetRGBColorFill(255, 0, 0);

    double radians = Math.Atan2(pageSize.Height, pageSize.Width);
    float textAngle = radians * (180 / Math.PI);

    pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "Phrase 1 This is Phrase 2 and must be centered below phrase 1" , pageSize.Width / 2, pageSize.Height / 2, textAngle);
    //pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "Phrase 1", pageSize.Width / 2, pageSize.Height / 2, textAngle);
    //pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "This is Phrase 2 and must be centered below phrase 1", pageSize.Width / 2 + 20 , pageSize.Height / 2 - 20, textAngle);
}

This adds the watermark on one line.

I am able to have two lines with the commented code. What i dont like are the hardcoded values for the position for the second line. I am sure there must be a better way of achieving this.

Regarding the border i did not manage to add it around the lines.

If someone can help me with this case . Thanks


Solution

  • basically what I do for my project is as under... here font_size and style are the variables... also llx, lly, urx,ury are variable for the the corrdinates position and size.. in alignment variable, you can set the alignment easily.... for opacity your code will work fine(you can add state options)

                 Dim Font = New Font(arial, FONT_SIZE, STYLE, iTextSharp.text.Color.BLACK )
    
    
                dim text = GetRowValue(row, "CONTROL_MAP")
                Dim ct As ColumnText = New ColumnText(pdf_cb)
                ct.SetSimpleColumn(LLX, LLY, URX, URY, FONT_SIZE, ALIGNMENT)
                ct.SetText(New Paragraph(0, text, Font))
                ct.Go()