import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;

import com.lowagie.text.Image;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;

public class PdfWaterMarker {

    public PdfWaterMarker() {
        super();
    }
    
    /**
     * Reads the pages of an existing PDF file, adds pagenumbers and a
     * watermark.
     * 
     * @param java.io.InputStream
     * @throws FileNotFoundException
     */
    public static byte[] addWatermark(byte[] bytes) {
        
        System.out.println("Add watermarks");
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            
            // we create a reader for a certain document
            PdfReader reader = new PdfReader(bytes);
            int n = reader.getNumberOfPages();
            
            // we create a stamper that will copy the document to a new file
            PdfStamper stamp = new PdfStamper(reader, bos);

            // adding stamp to each page
            int i = 0;
            PdfContentByte under;
            PdfContentByte over;
            Image img = Image.getInstance("resources/unofficial.gif");
            img.setAbsolutePosition(0, 0);
            while (i < n) {
                i++;
                // watermark under the existing page
                over = stamp.getUnderContent(i);
                over.addImage(img);
            }
            
            // closing PdfStamper will generate the new PDF file
            stamp.close();
            
        } catch (Exception de) {
            de.printStackTrace();
        }
        System.out.println("Done adding watermarks");
        return bos.toByteArray();
    }

}