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)); document.open(); for (String imageIpath : imagePathsList) { Image image1 = Image.getInstance(imageIpath); image1.setAbsolutePosition(10f, 10f); image1.scaleAbsolute(600, 800); document.add(image1); } writer.close();
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:
-
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.
-
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:
protected void manipulatePdf(String dest) throws Exception {
Image image = new Image(ImageDataFactory.create(IMAGES[0]));
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
Document doc = new Document(pdfDoc, new PageSize(image.getImageWidth(), image.getImageHeight()));
for (int i = 0; i
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 addNewPage()
[*]. Then I add the image at coordinate (0, 0)
because now the size of the image will match the size of each page.
[*] The addNewPage()
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.
Click How to add multiple images into a single PDF? if you want to see how to answer this question in iText 5.