Search code examples
javapdfitextwatermark

Add watermark to pdf java iText


I want to add a image or text watermark to pdf file. I found some examples online, but my case is a little bit different.

I have an existing pdf template which is already populated with dynamic data and converted to byte[]. This generated bytes are later exported to pdf.

I would like to add the watermark to that generated bytes. Something like:

byte[] addWatermark(byte[] generatedBytes){
  byte[] bytesWithWatermark;

  //add watermark to bytes

  return bytesWithWatermark;
}

I just can't seem to figure out how to do this with iText.


Solution

  • You say you already have examples for applying watermarks using iText. As you already have a PDF, you should use code from an example that adds watermarks to existing PDFs. This should be an example that works with a PdfReader / PdfStamper pair, e.g. those here, which all have the structure

    PdfReader reader = new PdfReader(SOME_SOURCE);
    PdfStamper stamper = new PdfStamper(reader, SOME_TARGET_STREAM);
    [... add watermark to all pages in stamper ...]
    stamper.close();
    reader.close();
    

    To make these example fit into your addWatermark method, simply use your byte[] instead of SOME_SOURCE and a ByteArrayOutputStream instead of SOME_TARGET_STREAM:

    byte[] addWatermark(byte[] generatedBytes) {
        try (ByteArrayOutputStream target  = new ByteArrayOutputStream()) {
            PdfReader reader = new PdfReader(generatedBytes);
            PdfStamper stamper = new PdfStamper(reader, target);
            [... add watermark to all pages in stamper ...]
            stamper.close();
            reader.close();
            return target.toByteArray();
        }
    }
    

    PS As you used only the tag and not the tag , I assumed you were looking for a solution for iText 5.5.x. But the same principle as applied here, i.e. using your byte[] as source argument and a ByteArrayOutputStream as target argument, will also allow you to make iText 7.x examples fit into your method frame.