javaapache-poifileoutputstream

how to insert every image in a new page to a ( word document )


i'm having some images, and i'm trying to insert each image to a new page in a ( word document ). my code works fine only for one image

i'm trying to write a program to insert the first image to the first page of the document

and then automatically open a new page to insert the second one and so on

import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

public class Test{

public static void main(String[] args) throws Exception {
        XWPFDocument document = new XWPFDocument();
        XWPFParagraph paragraph = document.createParagraph();
        XWPFRun run = paragraph.createRun();


        FileOutputStream fout = new FileOutputStream(  new File("D:\\word java.docx"));

 File image = new File("C:\\Users\\Pictures\\image1.jpg");
 File image2 = new File("C:\\Users\\Pictures\\image2.jpg");
 File image3 = new File("C:\\Users\\Pictures\\image2.jpg"); // i want to insert those three image in one (Word Document)

 FileInputStream imageData= new FileInputStream(image);


        int imageType = XWPFDocument.PICTURE_TYPE_JPEG;
        String imageFileName = image.getName();


        int width = 450;
        int height = 400;


        run.addPicture(imageData, imageType, imageFileName,
                Units.toEMU(width),
                Units.toEMU(height));
        document.write(fout);

        
        fout.close();
        document.close();


    }
}

Solution

  • You could use the setPageBreak() method. Below is a runnable example how this could be done. Of course, the image paths would need to reflect the images you want to apply to the WORD document. In the example runnable below, the image paths are placed into a String[] array names filePaths and Text to be added to the bottom of these images are placed into a parallel String[] array named imageTexts. Each image will be placed into its own document page with its respective text. Please read the comments in code:

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
    import org.apache.poi.util.Units;
    import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
    import org.apache.poi.xwpf.usermodel.XWPFDocument;
    import org.apache.poi.xwpf.usermodel.XWPFParagraph;
    import org.apache.poi.xwpf.usermodel.XWPFRun;
    
    
    public class Apache_POI_Demo {
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            /* These are the images we want to place into a WORD document
               but only one image per page. We place them into a String[]
               Array for easier handling especially if you plan to plan to
               insert lots of them into the document.                 */
            String[] filePaths = {"C:/Users/Devils/Pictures/DUCKS/image1.jpg",  // Image 1
                                  "C:/Users/Devils/Pictures/DUCKS/image2.jpg",  // Image 2
                                  "C:/Users/Devils/Pictures/DUCKS/image3.jpg"}; // Image 3
            
            /* There are specific Strings related to each image. These 
               strings will be applied under each respective image on 
               each page.                                */
            String[] imageText = {"Just Some Cute Ducks",       // For image1 
                                  "A Couple more Cute Ducks!",  // For image2 
                                  "A Bit Of A Happy Duck"};     // For image3
            
            // Create a new WORD document ('Try With Resources' used!)
            try (XWPFDocument doc = new XWPFDocument()) {
                    // The pages we want (one page for each image).
                    XWPFParagraph[] page = new XWPFParagraph[filePaths.length];
                    
                    /* Iterate through each image, load it in, 
                       and apply it to the document.        */
                    for (int pg = 0; pg < filePaths.length; pg++) {
                        // New paragraph for this current page.
                        page[pg] = doc.createParagraph();
                        // Align everything to center
                        page[pg].setAlignment(ParagraphAlignment.CENTER);
                        
                        // Create Page
                        XWPFRun run = page[pg].createRun();
                        
                        // Load Image File... 
                        File image = new File(filePaths[pg]);
                        // 'Try With Resources' used! here as well.
                        try (FileInputStream imageData = new FileInputStream(image)) {
                            int imageType = XWPFDocument.PICTURE_TYPE_JPEG;  // Image type is jpg
                            String imageFileName = image.getName();          // Get image file Name (only)
                            int width = 450;                                 // Set image Width
                            int height = 400;                                // Set image Height
                            
                            // Add image as first paragraph in document page.
                            run.addPicture(imageData, imageType, imageFileName,
                                    Units.toEMU(width),
                                    Units.toEMU(height));
                            
                            // Add text center under image ("Image #n") as part of first paragraph.
                            run.setFontFamily("Courier");               // Set the Font name for text.
                            run.setBold(true);                          // Set Text Bold.
                            run.setItalic(true);                        // Set Text Italic.
                            run.setColor("0000ff");                     // Set text color Blue (hex RGB color value).
                            run.setFontSize(11);                        // Set the Font Size for this text.
                            run.setText("Image #" + (pg + 1));          // The text to add to document...
                            run.setText(" - " + imageFileName);         // The text to add to document line.
                            
                            // Add a second paragraph to document on current page.
                            XWPFParagraph paragraph2 = doc.createParagraph();
                            // Also align this paragraph text to center of document.
                            paragraph2.setAlignment(ParagraphAlignment.CENTER);
                            // Create the paragraph 2 object
                            XWPFRun run2 = paragraph2.createRun();
                            run2.setFontFamily("Time New Roman");       // Set the Font for this paragraph
                            run2.setBold(false);                        // Set Font Bold OFF
                            run2.setItalic(false);                      // Set Font italic OFF
                            run2.setFontSize(14);                       // Set the Font Size to 14
                            run2.setText(imageText[pg]);                // Apply the desired text from Array
                            page[pg].setPageBreak(true);                // Apply a new Page Break.  ******
                        }
                    }
    
                // Save (Write) the WORD Document.
                try (FileOutputStream out = new FileOutputStream("D:\\POI_test\\word java.docx")) {
                    doc.write(out);
                }
    
            }
            catch (IOException | InvalidFormatException ex) {
                System.err.println(ex.getMessage());
            }
        }
    }
    

    With the Images I used, the following was the result within WORD:

    enter image description here