Multiple images

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

31st May 2016
iText PDF

Switch code for this example

MultipleImages.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.  * This code sample was written by Bruno Lowagie in answer to this question:
  10.  * http://stackoverflow.com/questions/29331838/add-multiple-images-into-a-single-pdf-file-with-itext-using-java
  11.  */
  12. package com.itextpdf.samples.sandbox.images;
  13.  
  14. import com.itextpdf.io.image.ImageDataFactory;
  15. import com.itextpdf.kernel.geom.PageSize;
  16. import com.itextpdf.kernel.pdf.PdfDocument;
  17. import com.itextpdf.kernel.pdf.PdfWriter;
  18. import com.itextpdf.layout.Document;
  19. import com.itextpdf.layout.element.Image;
  20. import com.itextpdf.samples.GenericTest;
  21. import com.itextpdf.test.annotations.type.SampleTest;
  22.  
  23. import org.junit.experimental.categories.Category;
  24.  
  25. import java.io.File;
  26.  
  27. @Category(SampleTest.class)
  28. public class MultipleImages extends GenericTest {
  29.     public static final String DEST =
  30.             "./target/test/resources/sandbox/images/multiple_images.pdf";
  31.     public static final String[] IMAGES = {
  32.             "./src/test/resources/img/berlin2013.jpg",
  33.             "./src/test/resources/img/javaone2013.jpg",
  34.             "./src/test/resources/img/map_cic.png"
  35.     };
  36.  
  37.     public static void main(String[] args) throws Exception {
  38.         File file = new File(DEST);
  39.         file.getParentFile().mkdirs();
  40.         new MultipleImages().manipulatePdf(DEST);
  41.     }
  42.  
  43.     @Override
  44.     protected void manipulatePdf(String dest) throws Exception {
  45.         Image image = new Image(ImageDataFactory.create(IMAGES[0]));
  46.         PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
  47.         Document doc = new Document(pdfDoc, new PageSize(image.getImageWidth(), image.getImageHeight()));
  48.         for (int i = 0; i < IMAGES.length; i++) {
  49.             image = new Image(ImageDataFactory.create(IMAGES[i]));
  50.             pdfDoc.addNewPage(new PageSize(image.getImageWidth(), image.getImageHeight()));
  51.             // Notice that now it is not necessary to set image position,
  52.             // because images are not overlapped while adding.
  53.             image.setFixedPosition(i + 1, 0, 0);
  54.             doc.add(image);
  55.         }
  56.         doc.close();
  57.     }
  58. }
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