1、poi-tl官网地址
http://deepoove.com/poi-tl/
2、引入poi-tl的依赖
<dependency>
<groupId>com.deepoove</groupId>
<artifactId>poi-tl</artifactId>
<version>1.12.1</version>
</dependency>
3、定义word模板
释义:?为开始标签,/为结束标签,@picture为渲染每一个图片
4、Java测试代码
@RequestMapping("/test")
@RestController
public class TestController {
private static final String PICTURE_PATH = "D:\\test\\picture\\";
@GetMapping("/download")
public void download(HttpServletResponse response) throws IOException {
//定义存储集合
Map<String, Object> pictureMap= new HashMap<>();
//创建并得到图片集合,设置图片大小
List<Map<String, PictureRenderData>> pictureList = createPictureList(100, 100);
pictureMap.put("pictureList", pictureList);
//通过XWPFTemplate处理
XWPFTemplate document = XWPFTemplate.compile(new ClassPathResource("templates/test.docx").getFile()).render(pictureMap);
//返回数据设置
setResponseHeader(response);
//输出流并关闭
OutputStream os = response.getOutputStream();
document.write(os);
os.close();
}
private List<Map<String, PictureRenderData>> createPictureList(int width, int height) {
List<Map<String, PictureRenderData>> list = new ArrayList<>();
//添加多张图片到集合
list.add(createPictureMap("Banner (1).jpg", width, height));
list.add(createPictureMap("Banner (10).jpg", width, height));
list.add(createPictureMap("Banner (100).jpg", width, height));
return list;
}
private Map<String, PictureRenderData> createPictureMap(String pictureName, int width, int height) {
Map<String, PictureRenderData> map = new HashMap<>();
//创建PictureRenderData对象并设置其大小
//Pictures还有其他方法,如Pictures.ofStream()流处理,可根据自己的需求及文档替换
map.put("picture", Pictures.ofLocal(PICTURE_PATH + pictureName).size(width, height).create());
return map;
}
private void setResponseHeader(HttpServletResponse response) {
response.reset();
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition",
"attachment;filename=picture_word_" + System.currentTimeMillis() + ".docx");
}
}
5、测试结果