title: Add watermark to pdf using iText using ByteArrayOutputStream
body: <p>The pdf is stored in a database as a byte[].  I want to add a watermark to the pdf and store the stamped file as a byte[], also in the database.  This is a Grails application, so the code is in Groovy. Here it is:</p>
  
  <pre><code>def stampDocument(byte[] orig) {
      PdfReader pdfReader = new PdfReader(orig)
      ByteArrayOutputStream baos = new ByteArrayOutputStream()
      //baos.write(orig, 0, orig.size())
      PdfStamper pdfStamper = new PdfStamper(pdfReader, baos)
      com.itextpdf.text.Image image = com.itextpdf.text.Image.getInstance(new URL("http://localhost:8080/IDSG/assets/stamp.jpg"));
      image.setAbsolutePosition(65f, 10f);
      image.scalePercent(40f);
      int i = 1
      while(i &lt;= pdfReader.getNumberOfPages()){
          PdfContentByte content = pdfStamper.getUnderContent(i)
          content.addImage(image)
          i++
      }
      return baos.toByteArray()
  }
  </code></pre>
  
  <p>The problem is that the pdfStamper does not seem to take notice of the pdfReader.  Calling some methods (getFileLength() and getInfo()) on the pdfReader returns valid data, so the pdfReader seems to be OK.  Same with the image.</p>
  
  <p>If the commented code (baos.write(orig, 0, orig.size()) is uncommented the original file is saved as the stamped file, but without the watermark. It's a bit bigger than the original, but renders perfectly.</p>
  
  <p>With the code mentioned above commented out, like in the code example, the returned byte[] is much smaller than the original and not a valid pdf file.  </p>
  
  <p>This worked well with files on the disk. But I'm stumped here.  It seems only something small is needed.  Any help will be appreciated.  I've been battling with this for hours and searched the web.</p>