Skip to main content
Skip table of contents

How to add multiple images into a single PDF?

How do I update my code in order to add all the images into the exported PDF instead of only the last one?

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.

JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.