达到的效果:把服务器上的图片插入word文档中,并且生成一个word文件。
其他包括:文字换行、图片大小适应一个word文档页等。
直接上代码:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
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;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
public class InsertMultipleImagesToWordDocument {
public static void main(String[] args) {
// 加载Word文档
try {
List<String> imagePaths = new ArrayList<>();
imagePaths.add("C:\\Users\\tuyua\\Desktop\\空白图片空白图片\\111.png");
imagePaths.add("C:\\Users\\tuyua\\Desktop\\空白图片空白图片\\222.png");
imagePaths.add("C:\\Users\\tuyua\\Desktop\\空白图片空白图片\\333.png");
XWPFDocument doc = new XWPFDocument();
// 插入图片
for (String imagePath : imagePaths) {
XWPFParagraph paragraph = doc.createParagraph();
paragraph.setAlignment(ParagraphAlignment.CENTER); // 设置对齐方式为居中
XWPFRun run = paragraph.createRun();
run.setFontSize(12); // 设置字体大小
run.setText("这是你要输入的文字!!!!!");//输入文字,比如可以图片的说明文字等
run.addBreak();//换行
// 读取原始图片
BufferedImage originalImage = ImageIO.read(new File(imagePath));
// 计算宽高比
double aspectRatio = (double) originalImage.getWidth() / originalImage.getHeight();
// 计算新的宽度和高度
int newWidth = 400;//高度固定在word一页内
int newHeight = 650;//高度固定在word一页内
if (aspectRatio == 1.00) {
newHeight = newWidth;
} else if (aspectRatio > 1.00) {
//宽度固定,高度按照比例缩小
newHeight = (int) (newWidth / aspectRatio);
} else {
//高度固定,宽度按照比例缩小(如果算下来宽度超过400,那么宽度固定400,再缩小高度)
newWidth = (int) (newHeight * aspectRatio);
if (newWidth > 400) {
newWidth = 400;
newHeight = (int) (newWidth / aspectRatio);
}
}
FileInputStream is = new FileInputStream(imagePath);
run.addPicture(is, XWPFDocument.PICTURE_TYPE_PNG, imagePath, Units.toEMU(newWidth), Units.toEMU(newHeight));
is.close();
}
// word文件要存放的路径
String fileDir = "C:\\Users\\tuyua\\Desktop\\空白图片空白图片\\" + UUidUtils.getUuid();
File dir = new File(fileDir);
// 使用mkdirs()方法创建文件夹,包括任何必要的父文件夹
dir.mkdirs();
FileOutputStream out = new FileOutputStream(fileDir + "/" + "testInsertImage.docx");
doc.write(out);
out.close();
doc.close();
System.out.println("success");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
效果如下:
success!!!