简体   繁体   中英

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.

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, eg 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, ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM