java如何使用poi-tl在word文档里面渲染多张图片

发布时间:2024年01月10日

1. Poi-tl官网

http://deepoove.com/poi-tl/

2.引入依赖

		<dependency>
            <groupId>com.deepoove</groupId>
            <artifactId>poi-tl</artifactId>
            <version>1.12.1</version>
        </dependency>

3.编写Word图片模版

 {{?pictures}}{{@picture}}{{/pictures}}          ?和/为图片集合的开始和结束标签     @picture为每一张图片元素

4.Java代码

@RequestMapping("/test")
@RestController
public class TestController {

    private static final String IMAGE_PATH = "D:\\test\\image\\";

    @GetMapping("/download")
    public void generateWord(HttpServletResponse response) throws IOException {
        Map<String, Object> content = new HashMap<>();

        List<Map<String, PictureRenderData>> pictureList = createPictureList(240, 240);
        content.put("pictures", pictureList);


        XWPFTemplate document = XWPFTemplate.compile(new ClassPathResource("templates/test.docx").getFile()).render(content);

        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("微信图片_20231217213601.jpg", width, height));
        list.add(createPictureMap("190623-1701774383944b.jpg", width, height));
        list.add(createPictureMap("202054-1695298854fd7d.jpg", width, height));

        return list;
    }

    private Map<String, PictureRenderData> createPictureMap(String imageName, int width, int height) {
        Map<String, PictureRenderData> map = new HashMap<>();
        map.put("picture", Pictures.ofLocal(IMAGE_PATH + imageName).size(width, height).create());
        return map;
    }

    private void setResponseHeader(HttpServletResponse response) {
        response.reset();
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition",
                "attachment;filename=user_word_" + System.currentTimeMillis() + ".docx");
    }
}
文章来源:https://blog.csdn.net/nyasm/article/details/135513898
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。