How to add an image to an existing PDF using AffineTransform?

I am using PdfStamper's getOverContent() method to add an image to a PDF file using an AffineTransform instance. When I open the resulting PDF, I can't see the image. This is my code:

PdfContentByte content = stamper.getOverContent(1);
If I use the commented line without the transform it works perfectly: the image is added to the PDF, but with the AffineTransform, it does not show up. I intend to use a sophisticated transform, but I tried with the "Identity" transformation first...

Posted on StackOverflow on Dec 7, 2015 by Mário de Sá Vera

I have examined your problem and I am pretty sure that your image gets added. However: you can't see it because the dimension of the image is 1 user unit by 1 user unit.

I've made an example to show you how to fix this problem: AddImageAffineTransform

public void manipulatePdf(String src, String dest)
    throws IOException, DocumentException {
    PdfReader reader = new PdfReader(src);
    PdfStamper stamper = new PdfStamper(
        reader, new FileOutputStream(dest));
    Image image = Image.getInstance(IMG);
    AffineTransform at = AffineTransform.getTranslateInstance(36, 300);
        image.getScaledWidth(), image.getScaledHeight()));
    PdfContentByte canvas = stamper.getOverContent(1);
    canvas.addImage(image, at);

In this example, I start with a translation: 36 user units from the left border and 300 user units from the bottom. If I would add the image using this transformation, I'd add the image at those coordinates, but it would be too small to see with the naked eye.

To make sure the image is visible, I concatenate a scale transformation scaling the image to its width in X direction and to its height in Y direction.

Ready to use iText?

Try our iText 7 Library and add-ons FREE for 30 days. Test your proof of concept, and see if our solution is right for you.

Get my FREE trial

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