Images and Affine Transformations

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

8th December 2015
admin-marketing

Switch code for this example

AddImageAffineTransform.java
  1. /**
  2.  * Example written by Bruno Lowagie in answer to the following question:
  3.  * http://stackoverflow.com/questions/34117589
  4.  */
  5. package sandbox.stamper;
  6.  
  7. import com.itextpdf.awt.geom.AffineTransform;
  8. import com.itextpdf.text.DocumentException;
  9. import com.itextpdf.text.Image;
  10. import com.itextpdf.text.pdf.PdfContentByte;
  11. import com.itextpdf.text.pdf.PdfReader;
  12. import com.itextpdf.text.pdf.PdfStamper;
  13. import java.io.File;
  14. import java.io.FileOutputStream;
  15. import java.io.IOException;
  16.  
  17. /**
  18.  * @author Bruno Lowagie (iText Software)
  19.  */
  20. public class AddImageAffineTransform {
  21.     public static final String SRC = "resources/pdfs/hello.pdf";
  22.     public static final String DEST = "results/stamper/hello_with_image.pdf";
  23.     public static final String IMG = "resources/images/bruno.jpg";
  24.    
  25.     public static void main(String[] args) throws IOException, DocumentException {
  26.         File file = new File(DEST);
  27.         file.getParentFile().mkdirs();
  28.         new AddImageAffineTransform().manipulatePdf(SRC, DEST);
  29.     }
  30.     public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
  31.         PdfReader reader = new PdfReader(src);
  32.         PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
  33.         Image image = Image.getInstance(IMG);
  34.         AffineTransform at = AffineTransform.getTranslateInstance(36, 300);
  35.         at.concatenate(AffineTransform.getScaleInstance(image.getScaledWidth(), image.getScaledHeight()));
  36.         PdfContentByte canvas = stamper.getOverContent(1);
  37.         canvas.addImage(image, at);
  38.         stamper.close();
  39.         reader.close();
  40.     }
  41.    
  42. }
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