Adding text as watermark using itext7 C#

3.2k views Asked by At

I am using the below code to add watermark to my pdf.

private void Merge(List<string> src, string dest)
    {
        iTextKernel.PdfWriter writer = new iTextKernel.PdfWriter(dest);
        iTextKernel.PdfDocument pdfDocument1 = new iTextKernel.PdfDocument(new iTextKernel.PdfReader(src[0]), writer);
        pdfDocument1.AddEventHandler(PdfDocumentEvent.END_PAGE, new WatermarkingEventHandler());

        for (int i = 1, max = src.Count; i < max; i++)
        {
            iTextKernel.PdfDocument pdfDocument2 = new iTextKernel.PdfDocument(new iTextKernel.PdfReader(src[i]));
            var pagesCount = pdfDocument2.GetNumberOfPages();
            pdfDocument2.CopyPagesTo(1, pagesCount, pdfDocument1);
            pdfDocument2.Close();
        }
        pdfDocument1.Close();
  protected class WatermarkingEventHandler : IEventHandler {

         public void HandleEvent(Event e) {
        PdfDocumentEvent docEvent = (PdfDocumentEvent) e;
        iTextKernel.PdfDocument pdfDoc = docEvent.GetDocument();
        iTextKernel.PdfPage page = docEvent.GetPage();
        iText.Kernel.Font.PdfFont font = null;
        try {
            font = PdfFontFactory.CreateFont(FontConstants.HELVETICA_BOLD);
        } catch (IOException ex) {
            //_log.Error(ex);
        }
        PdfCanvas canvas = new PdfCanvas(page.NewContentStreamBefore(), page.GetResources(), pdfDoc);
        new Canvas(canvas, pdfDoc, page.GetPageSize())
                .SetFontColor(iText.Kernel.Colors.DeviceGray.LIGHT_GRAY)
                .SetFontSize(60)
                .SetFont(font)
                .ShowTextAligned(new Paragraph("FOR YOUR RECORDS ONLY: DO NOT SUBMIT"), 298, 421, pdfDoc.GetPageNumber(page),
                        TextAlignment.CENTER, VerticalAlignment.MIDDLE, 45);
    }

But am getting the watermark only in the last page that too hidden under the contents. Could you please modify this code so that i could get the watermark on all the pages and shown over the contents.

1

There are 1 answers

2
Bruno Lowagie On

Please take a look at the iText 7 for C# jump-start tutorial, more specifically Chapter 5: Manipulating an existing PDF document. Scroll to the part where it says: "Adding a header, footer, and watermark" and look at the example:

PdfDocument pdfDoc = new PdfDocument(new PdfReader(src), new PdfWriter(dest));
Document document = new Document(pdfDoc);
Rectangle pageSize;
PdfCanvas canvas;
int n = pdfDoc.GetNumberOfPages();
for (int i = 1; i <= n; i++) {
    PdfPage page = pdfDoc.GetPage(i);
    pageSize = page.GetPageSize();
    canvas = new PdfCanvas(page);
    //Draw header text
}
pdfDoc.close();

As you can see, we only need one PdfDocument instance, but instead of passing only a PdfWriter, we also pass a PdfReader instance. We will read the file with path src and we will write to a file with path dest.

You want to add content to each page. This means that you have to loop over each page (from 1 to n). Get the PdfPage object for each page i and replace the line //Draw header text with whatever it is you want to do.

In your case, you add an image underneath the existing content. That is the normal thing to do, but you say that the watermark is covered by the existing content. That happens for instance when the actual content consists of images (e.g. scanned pages). If you add a watermark under the pages of a PDF that consists of scanned pages, you will never see the watermark.

In that case, you have to add the content on top of the existing content, but it is best to make the watermark transparent:

Paragraph p = new Paragraph("FOR YOUR RECORDS ONLY: DO NOT SUBMIT").SetFontSize(60);
canvas.SaveState();
PdfExtGState gs1 = new PdfExtGState().SetFillOpacity(0.2f);
canvas.SetExtGState(gs1);
document.ShowTextAligned(p, pageSize.GetWidth() / 2, pageSize.GetHeight() / 2, pdfDoc.GetPageNumber(page), TextAlignment.CENTER, VerticalAlignment.MIDDLE, 45);
canvas.RestoreState();

Note that in the tutorial, we are using pageSize.GetWidth() / 2 and pageSize.GetHeight() / 2 as coordinates, which means that we assume that the lower-left corner of the page has the coordinate (0, 0). That may not be the case. You may have to add the x-offset and the y-offset to that value.