How to add multiple images into a single PDF?

I have the following code, but this code only adds the last image to the PDF.


Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document,
    new FileOutputStream(filePath));;
for (String imageIpath : imagePathsList) {
    Image image1 = Image.getInstance(imageIpath);
    image1.setAbsolutePosition(10f, 10f);
    image1.scaleAbsolute(600, 800);
Would you give me a hint about how to update the code in order to add all the images into the exported PDF? The imagePathsList variable contains all the paths of images that that I want to add into a single PDF.

Posted on StackOverflow on Mar 29, 2015 by aurelianr

Take a look at the MultipleImages example and you'll discover that there are two errors in your code:

  1. You create a page with size 595 x 842 user units, and you add every image to that page regardless of the dimensions of the image.

  2. You claim that only one image is added, but that's not true. You are adding all the images on top of each other on the same page. The last image covers all the preceding images.

Take a look at my code:

public void createPdf(String dest) throws IOException, DocumentException {
    Image img = Image.getInstance(IMAGES[0]);
    Document document = new Document(img);
    PdfWriter.getInstance(document, new FileOutputStream(dest));;
    for (String image : IMAGES) {
        img = Image.getInstance(image);
        img.setAbsolutePosition(0, 0);

I create a Document instance using the size of the first image. I then loop over an array of images, setting the page size of the next page to the size of each image before I trigger a newPage() [*]. Then I add the image at coordinate (0, 0) because now the size of the image will match the size of each page.

[*] The newPage() method only has effect if something was added to the current page. The first time you go through the loop, nothing has been added yet, so nothing happens. This is why you need set the page size to the size of the first image when you create the Document instance.

Ready to use iText?

Try our iText 7 Library and add-ons FREE for 30 days. Test your proof of concept, and see if our solution is right for you.

Get my FREE trial

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