aurelianr aurelianr - 1 month ago 15
Java Question

Add multiple images into a single pdf file with iText using java

I have the following code but this code add only the last image into pdf.

try {
filePath = (filePath != null && filePath.endsWith(".pdf")) ? filePath
: filePath + ".pdf";
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document,
new FileOutputStream(filePath));
document.open();
// document.add(new Paragraph("Image Example"));
for (String imageIpath : imagePathsList) {

// Add Image
Image image1 = Image.getInstance(imageIpath);
// Fixed Positioning
image1.setAbsolutePosition(10f, 10f);
// Scale to new height and new width of image
image1.scaleAbsolute(600, 800);
// image1.scalePercent(0.5f);
// Add to document
document.add(image1);
//document.bottom();


}
writer.close();

} catch (Exception e) {
LOGGER.error(e.getMessage());
}


Would you give me a hint about how to update the code in order to add all the images into the exported pdf? imagePathsList contains all the paths of images that that I want to add into a single pdf.

Best Regards,
Aurelian

Answer

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));
    document.open();
    for (String image : IMAGES) {
        img = Image.getInstance(image);
        document.setPageSize(img);
        document.newPage();
        img.setAbsolutePosition(0, 0);
        document.add(img);
    }
    document.close();
}

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.