Search code examples
javaitextwatermark

How to add watermark to TIFF image using itext 2.1.7 in java


I want to print out a tiff image with watermark.So, firstly i convert tiff image to pdf and add watermark to generated pdf.But the watermark doesn't appear in final pdf. Is there any advice to print out a tiff image with watermark. Any help will be appreciated. This is my code.

public class TiffToPdf {
private static int TEXT_TILT_ANGLE = 25;
private static Color MEDIUM_GRAY = new Color(242,17,72);
private static int PRIMARY_FONT_SIZE = 50;
private static String tif = "C:/Sample.tif";
private static String pdf = "C:/Sample.pdf";
private static String watermarkpdf = "C:/Watermark.pdf"

public static void main(String[] args) throws Exception {
    convert(tif, pdf);
    File watermark = new File(watermarkpdf);
    OutputStream outputStream = new FileOutputStream(watermark);
    addWaterMark(pdf, outputStream, "This is Sample WaterMark");
}

public static File convert(String tif, String pdf) {
    File pdfFile = null;
    String imgeFilename = tif;
    Document document = new Document();
    try {
        PdfWriter writer = PdfWriter.getInstance(
                document,
                new FileOutputStream(pdf));
        writer.setStrictImageSequence(true);
        Image image;
        document.open();
        RandomAccessFileOrArray ra = new RandomAccessFileOrArray(imgeFilename);
        int pagesTif = TiffImage.getNumberOfPages(ra);
        for (int i = 1; i <= pagesTif; i++) {
            image = TiffImage.getTiffImage(ra, i);
            image.scaleAbsolute(PageSize.A4.getWidth(), PageSize.A4.getHeight());
            document.setMargins(0, 0, 0, 0);
            document.newPage();
            document.add(image);
        }
        pdfFile = new File(pdf);
        document.close();
    } catch (Exception ex) {
        //do nothing
    }
    return pdfFile;
}

public static void addWaterMark(String pdfFile,OutputStream outputStream, String watermark) throws Exception{
    PdfReader reader = new PdfReader(pdfFile);
    int numPages = reader.getNumberOfPages();
    // Create a stamper that will copy the document to the output
    // stream.
    PdfStamper stamp = new PdfStamper(reader, outputStream);
    int page=1;

    BaseFont baseFont = 
        BaseFont.createFont(BaseFont.HELVETICA_BOLDOBLIQUE,
            BaseFont.WINANSI, BaseFont.EMBEDDED);

    float width;
    float height;

    while (page <= numPages) {
        PdfContentByte cb = stamp.getOverContent(page);
        height = reader.getPageSizeWithRotation(page).getHeight() / 2;
        width = reader.getPageSizeWithRotation(page).getWidth() / 2;

        cb = stamp.getUnderContent(page);
        cb.saveState();
        cb.setColorFill(MEDIUM_GRAY);

        // Primary Text
        cb.beginText();
        cb.setFontAndSize(baseFont, PRIMARY_FONT_SIZE);
        cb.showTextAligned(Element.ALIGN_CENTER, watermark, width,
                height, TEXT_TILT_ANGLE);
        cb.endText();
        cb.restoreState();

        page++;
    }

    stamp.close();
}

}


Solution

  • Many things are wrong with your code. For instance: you say that the watermark doesn't appear in your final PDF, but if you looked closer, you'd see that a watermark is indeed added, but it is covered by an opaque image (the TIFF you added in a previous go).

    Look at your code. First you define cb as the layer that covers the image:

        PdfContentByte cb = stamp.getOverContent(page);
    

    But almost immediately after that line, you redefine cb as the layer that goes under the existing image:

        cb = stamp.getUnderContent(page);
    

    Remove this line and your watermark will appear.

    You are not doing your customer a favor, because:

    1. you are using a version of iText that could bring him in trouble.
    2. your addWatermark() method assumes that the origin of the coordinate system is (0, 0) and this isn't always the case, so if your customer starts using your method for other PDFs, it may add the watermark outside the visible area of the page.
    3. you first create a PDF and then you read that PDF to add a watermark. Why aren't you adding the watermark during creation using page events?
    4. when you create the PDF, you scale the TIFF images to exactly match an A4 page. This means that the images will be seriously distorted if they have an aspect ratio that is different from the aspect ratio of an A4 page. For instance: you create a page in portrait, but if the TIFF is a page in landscape, you will make the TIFF illegible.

    All in all, your code is not suited for production. My advice would be to rewrite it and to use the most recent iText version.