springboot 利用EasyPoi 导出带有图片的word,无黑色背景

一、导入jar包


        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-base</artifactId>
            <version>3.2.0</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-annotation</artifactId>
            <version>3.2.0</version>
        </dependency>

二、导出工具方法

public static void exportWordByImg(String templatePath,String fileName, Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) {

        Assert.notNull(templatePath,"模板路径不能为空");
        Assert.notNull(fileName,"导出文件名不能为空");
        Assert.isTrue(fileName.endsWith(".docx"),"word导出请使用docx格式");
        try {
            String userAgent = request.getHeader("user-agent").toLowerCase();
            if (userAgent.contains("msie") || userAgent.contains("like gecko")) {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } else {
                fileName = new String(fileName.getBytes("utf-8"), "ISO-8859-1");
            }
            WordImageEntity image = new WordImageEntity();
            image.setHeight(50);//设置高度
            image.setWidth(90);//设置宽度
            image.setType(WordImageEntity.Data);//类型
            image.setData(image2byte("http://localhost/upload/avatar/2019-11-12/1194160525404151808.jpg"));
            params.put("imgUrl", image);
            XWPFDocument doc = WordExportUtil.exportWord07(templatePath, params);
            String tmpPath = fileName;
            FileOutputStream fos = new FileOutputStream(tmpPath);
            doc.write(fos);
            // 设置强制下载不打开
            response.setContentType("application/force-download");
            // 设置文件名
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
            OutputStream out = response.getOutputStream();
            doc.write(out);
            out.close();
            File file = new File(tmpPath);
            if(file.exists()){
                file.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
//            delAllFile(temDir);//这一步看具体需求,要不要删
        }
    }

解说:WordImageEntity 源码

package cn.afterturn.easypoi.word.entity;

import cn.afterturn.easypoi.entity.ImageEntity;

/** @deprecated */
@Deprecated
public class WordImageEntity extends ImageEntity {
    public WordImageEntity() {
    }

    public WordImageEntity(byte[] data, int width, int height) {
        super(data, width, height);
    }

    public WordImageEntity(String url, int width, int height) {
        super(url, width, height);
    }
}

从源码看出,该类有两个方法,可以传入URL,也可以直接利用byte[] ,博主测试后发现,利用URL 导出会有黑色背景,通过byte[] 导出一切正常。

猜你喜欢

转载自blog.csdn.net/xljx_1/article/details/103225630