2

First google result takes me to Add multiple images into a single pdf file with iText using java which was posted 5 years ago. I am not sure which version they are using, because the Image object doesn't even have the getInstance method for me. Needless to say I am not getting much help from that link.

Anyways I am trying to create a javaFX application that loops multiple JPG images to create a single PDF document. Below is my code, which successfully creates a PDF from 2 images, but I am having trouble making the second image display on the second page.

In the link I posted above the simple solution I saw was to do document.newPage() then do document.add(img), but my document object doesn't have that method? I am not sure what to do.

            PdfWriter writer = new PdfWriter("D:/sample1.pdf"); 

            // Creating a PdfDocument       
            PdfDocument pdfDoc = new PdfDocument(writer);              

            // Adding a new page 
            // I can add multiple pages here, but when I add multiple images they do not
            // automatically flow over to the next page. 
            pdfDoc.addNewPage();
            pdfDoc.addNewPage();  

            // Creating a Document        
            Document document = new Document(pdfDoc);               

            String imageFile = "C:/Users/***/Downloads/MAT204/1.3-1.4 HW/test.jpg";

            ImageData data = ImageDataFactory.create(imageFile);

            Image img = new Image(data);

            img.setAutoScale(true);

            img.setRotationAngle(-Math.toRadians(90));

            // I can add multiple images, but they overlaps each other and only
            // appears on the first page.
            // Is there a way for me to change the current page to write on?
            document.add(img);
            document.add(img);

            // Closing the document    
            document.close();              
            System.out.println("PDF Created");

problem

Anyways, I just want to figure out how to manually add another image before I write a loop to automate the process.

Inkplay_
  • 561
  • 2
  • 5
  • 18

1 Answers1

3

After doing more research I found the answer here.

https://kb.itextpdf.com/home/it7kb/examples/multiple-images

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 < IMAGES.length; i++) {
        image = new Image(ImageDataFactory.create(IMAGES[i]));
        pdfDoc.addNewPage(new PageSize(image.getImageWidth(), image.getImageHeight()));
        image.setFixedPosition(i + 1, 0, 0);
        doc.add(image);
    }

    doc.close();
}
Inkplay_
  • 561
  • 2
  • 5
  • 18