Image masks

This is a code example of iText PDF, discover more.

31st May 2016

Switch code for this example

    This file is part of the iText (R) project.
    Copyright (c) 1998-2016 iText Group NV


 * This code sample was written by Bruno Lowagie in answer to this question:
package com.itextpdf.samples.sandbox.images;

import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Image;
import com.itextpdf.samples.GenericTest;
import com.itextpdf.test.annotations.type.SampleTest;

import org.junit.experimental.categories.Category;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;

public class MakeJpgMask extends GenericTest {
    public static final String DEST = "./target/test/resources/sandbox/images/make_jpg_mask.pdf";
    public static final String IMAGE = "./src/test/resources/img/javaone2013.jpg";
    public static final String MASK = "./src/test/resources/img/berlin2013.jpg";

    public static void main(String[] args) throws Exception {
        File file = new File(DEST);
        new MakeJpgMask().manipulatePdf(DEST);

    public static ImageData makeBlackAndWhitePng(String image) throws IOException {
        BufferedImage bi = File(image));
        BufferedImage newBi = new BufferedImage(bi.getWidth(), bi.getHeight(), BufferedImage.TYPE_USHORT_GRAY);
        newBi.getGraphics().drawImage(bi, 0, 0, null);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(newBi, "png", baos);
        return ImageDataFactory.create(baos.toByteArray());

    protected void manipulatePdf(String dest) throws Exception {
        PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
        // Note that it is not necessary to create new PageSize object,
        // but for testing reasons (connected to parallelization) we call constructor here
        PageSize pageSize = new PageSize(PageSize.A4).rotate();
        Document doc = new Document(pdfDoc, pageSize);

        ImageData image = ImageDataFactory.create(IMAGE);
        ImageData mask = makeBlackAndWhitePng(MASK);

        Image img = new Image(image);
        img.scaleAbsolute(pageSize.getWidth(), pageSize.getHeight());
        img.setFixedPosition(0, 0);


Still have questions? 

We're happy to answer your questions. Reach out to us and we'll get back to you shortly.

Contact us
Stay updated

Join 11,000+ subscribers and become an iText PDF expert by staying up to date with our new products, updates, tips, technical solutions and happenings.

Subscribe Now