Images and Affine Transformations

This is a code example of iText PDF, discover more.

31st May 2016
admin-marketing

Switch code for this example

AddImageAffineTransform.java
  1. /*
  2.  
  3.     This file is part of the iText (R) project.
  4.     Copyright (c) 1998-2016 iText Group NV
  5.  
  6. */
  7.  
  8. /**
  9.  * Example written by Bruno Lowagie in answer to the following question:
  10.  * http://stackoverflow.com/questions/34117589
  11.  */
  12. package com.itextpdf.samples.sandbox.stamper;
  13.  
  14. import com.itextpdf.io.image.ImageData;
  15. import com.itextpdf.io.image.ImageDataFactory;
  16. import com.itextpdf.kernel.geom.AffineTransform;
  17. import com.itextpdf.kernel.pdf.PdfDocument;
  18. import com.itextpdf.kernel.pdf.PdfReader;
  19. import com.itextpdf.kernel.pdf.PdfWriter;
  20. import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
  21. import com.itextpdf.layout.element.Image;
  22. import com.itextpdf.samples.GenericTest;
  23. import com.itextpdf.test.annotations.type.SampleTest;
  24.  
  25. import org.junit.experimental.categories.Category;
  26.  
  27. import java.io.File;
  28.  
  29. @Category(SampleTest.class)
  30. public class AddImageAffineTransform extends GenericTest {
  31.     public static final String DEST = "./target/test/resources/sandbox/stamper/add_image_affine_transform.pdf";
  32.     public static final String IMG = "./src/test/resources/img/bruno.jpg";
  33.     public static final String SRC = "./src/test/resources/pdfs/hello.pdf";
  34.  
  35.     public static void main(String[] args) throws Exception {
  36.         File file = new File(DEST);
  37.         file.getParentFile().mkdirs();
  38.         new AddImageAffineTransform().manipulatePdf(DEST);
  39.     }
  40.  
  41.     @Override
  42.     protected void manipulatePdf(String dest) throws Exception {
  43.         PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest));
  44.         ImageData image = ImageDataFactory.create(IMG);
  45.         Image imageModel = new Image(image);
  46.         AffineTransform at = AffineTransform.getTranslateInstance(36, 300);
  47.         at.concatenate(AffineTransform.getScaleInstance(imageModel.getImageScaledWidth(),
  48.                 imageModel.getImageScaledHeight()));
  49.         PdfCanvas canvas = new PdfCanvas(pdfDoc.getFirstPage());
  50.         float[] matrix = new float[6];
  51.         at.getMatrix(matrix);
  52.         canvas.addImage(image, matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]);
  53.         pdfDoc.close();
  54.     }
  55. }
Contact

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