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: https://www.sign.plus/online-signature-generator

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

PdfReader.killIndirect(currentImg);
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(maskImage);
    }
    signatureImage.scaleToFit(targetWidth.floatValue(),
            targetHeight.floatValue());
    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.
jamie@example.com
Subscribe