How to add an image to an existing PDF using AffineTransform?
Why does it work If I use the commented line without the transform, but with the AffineTransform, it does not show up?
This is my code:
PdfContentByte content = stamper.getOverContent(1);
content.addImage(data.image,desc.transform);//content.addImage(data.image);
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.
protected void manipulatePdf(String dest) throws Exception {
PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest));
ImageData image = ImageDataFactory.create(IMG);
// Translation defines the position of the image on the page and scale transformation sets image dimensions
// Please also note that image without scaling is drawn in 1x1 rectangle. And here we draw image on page using
// its original size in pixels.
AffineTransform affineTransform = AffineTransform.getTranslateInstance(36, 300);
// Make sure that the image is visible by concatenating a scale transformation
affineTransform.concatenate(AffineTransform.getScaleInstance(image.getWidth(), image.getHeight()));
PdfCanvas canvas = new PdfCanvas(pdfDoc.getFirstPage());
float[] matrix = new float[6];
affineTransform.getMatrix(matrix);
canvas.addImageWithTransformationMatrix(image, matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]);
pdfDoc.close();
}
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.
Click How to add an image to an existing PDF using AffineTransform? if you want to see how to answer this question in iText 5.