public static void saveToWord(ArrayList<String> locations ) throws InvalidFormatException, IOException {
XWPFDocument docx = new XWPFDocument();
XWPFParagraph par = docx.createParagraph();
XWPFRun run = par.createRun();
FileOutputStream out = new FileOutputStream("/Users/sparker0i/WordDoc.docx");
run.setText("Hello, World. This is my first java generated docx-file. Have fun.");
run.setFontSize(13);
for (String location : locations) {
BufferedImage image = ImageIO.read(new File(location));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "jpeg", baos);
baos.flush();
ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray());
baos.close();
run.addPicture(bis, XWPFDocument.PICTURE_TYPE_JPEG, "image file", Units.toEMU(200), Units.toEMU(200)); // 200x200 pixels
bis.close();
docx.write(out);
}
out.close();
}
作为参数传递给此函数的arraylist具有要附加到我的Word文档中的所有图像的位置。当我尝试此操作时,程序确实成功运行,但是我的docx文件显示它已损坏?我想知道如何在Word文件中写入多个图像。