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 imgSrc, String src, String dest) throws Exception {
PdfDocument pdfDoc = new PdfDocument(new PdfReader(src), new PdfWriter(dest));
ImageData image = ImageDataFactory.create(imgSrc);
Image imageModel = new Image(image);
AffineTransform at = AffineTransform.getTranslateInstance(36, 300);
at.concatenate(AffineTransform.getScaleInstance(imageModel.getImageScaledWidth(),
imageModel.getImageScaledHeight()));
PdfCanvas canvas = new PdfCanvas(pdfDoc.getFirstPage());
float[] matrix = new float[6];
at.getMatrix(matrix);
canvas.addImage(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.