How to merge|replace images into a PDF document via itextpdf lib in Java

How to merge|replace images into a PDF document via itextpdf lib in Java
Photo by Lewis Keegan / Unsplash

In my previous post, I guided how to find all the images that are signatures place holders. In this post, I will tell how to replace or merge them with your fancy signature image.

First, you need to prepare your fancy signature image. You can try with:

And create a BufferedImage from your signature.

In the RenderListener implementation, we detected the image object that might be the signature place holder. Then 4 steps need to be done to merge your fancy contract.

PdfReader::killIndirect, remove the connection

com.itextpdf.text.Image::getInstance(bufferedImage) create a new mask Image

PdfWriter writer = pdfStamper.getWriter();

create indirect connection with the new signature image

BufferedImage bufferedImage = ImageIO
        .read(new ByteArrayInputStream(imageBytes));
if (bufferedImage != null) {
    Image signatureImage = Image.getInstance(bufferedImage, null);
    Image maskImage = signatureImage.getImageMask();

    if (maskImage != null) {
        log.error("maskImage {}", maskImage.getAbsoluteX());
    writer.addDirectImageSimple(signatureImage, (PRIndirectReference) obj);

Apply signatures programiclly via itextpdf

Subscribe to Post, Code and Quiet Time.

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.