JAVA将图片转成base64导出到word中

我这里使用的是freemarker-2.3.23.jar

freemarker来导出word

说一下,图片如何插入

插入成功后

关于ftl的模板如何生成呢!!

打开所需要的模板-选择另存为-其他格式

然后选择Word 2003XML文档(*.xml),点击保存

然后,将test.xml后缀名改为 test.ftl

接下里打开test.ftl

图中这个就是base64编码将它改成我们所需要的参数

然后 有两种方式来导出图片

package cn.com.tiza.hjwulian.system.common.util;

import freemarker.template.Configuration;
import freemarker.template.Template;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;


/**
 * @Desc:word操作工具类
 * @Author:LGL
 */
public class WordUtil {

    /**
     * @param dataMap      word中需要展示的动态数据,用map集合来保存
     * @param templateName word模板名称,例如:test.ftl
     * @param filePath     文件生成的目标路径,例如:D:/wordFile/
     * @param fileName     生成的文件名称,例如:test.doc
     * @Desc:生成word文件
     * @Author:LGL
     */
    @SuppressWarnings("unchecked")
    public void createWord(Map dataMap, String templateName, String filePath, String fileName) {
        try {
            //创建配置实例
            Configuration configuration = new Configuration();

            //设置编码
            configuration.setDefaultEncoding("UTF-8");

            //ftl模板文件统一放至 com.lun.template 包下面com.admin.wordtest /yuanda-biz/src/main/java/com/zkingsoft/tools/xzcvs.ftl
            configuration.setClassForTemplateLoading(WordUtil.class, "/");

            //获取模板 
            Template template = configuration.getTemplate(templateName);

            //输出文件
            File outFile = new File(filePath + File.separator + fileName);

            //如果输出目标文件夹不存在,则创建
            if (!outFile.getParentFile().exists()) {
                outFile.getParentFile().mkdirs();
            }

            //将模板和数据模型合并生成文件 
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"));


            //生成文件
            template.process(dataMap, out);

            //关闭流
            out.flush();
            out.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取图片对应的base64码
     * <p>
     * 图片
     *
     * @return 图片对应的base64码
     * @throws IOException
     * @date 2018/11/16 17:05
     */
    //获得图片的base64码
    public static String getImageBase(String src) throws Exception {
        if (src == null || src == "") {
            return "";
        }
        File file = new File(src);
        if (!file.exists()) {
            return "";
        }
        InputStream in = null;
        byte[] data = null;
        try {
            in = new FileInputStream(file);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);
    }


    /**
     * 远程读取image转换为Base64字符串
     *
     * @param imgUrl
     * @return
     */
    public static String Image2Base64(String imgUrl) {
        URL url = null;
        InputStream is = null;
        ByteArrayOutputStream outStream = null;
        HttpURLConnection httpUrl = null;
        try {
            url = new URL(imgUrl);
            httpUrl = (HttpURLConnection) url.openConnection();
            httpUrl.connect();
            httpUrl.getInputStream();
            is = httpUrl.getInputStream();

            outStream = new ByteArrayOutputStream();
            //创建一个Buffer字符串
            byte[] buffer = new byte[1024];
            //每次读取的字符串长度,如果为-1,代表全部读取完毕
            int len = 0;
            //使用一个输入流从buffer里把数据读取出来
            while ((len = is.read(buffer)) != -1) {
                //用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
                outStream.write(buffer, 0, len);
            }
            // 对字节数组Base64编码
            return new BASE64Encoder().encode(outStream.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        }  //下载
        finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outStream != null) {
                try {
                    outStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpUrl != null) {
                httpUrl.disconnect();
            }
        }
        return imgUrl;
    }

}

其中第一种就是获取本地图片转成Base64编码

第二种是通过远程读取图片来转成Base64编码

Map<String, Object> dataMap = new HashMap<String, Object>();
//日期
dataMap.put("date", "2019-9-10");
//图片
dataMap.put("image",WordUtil.Image2Base64("http://localhost:8080/images/test.jpg"));
/** 生成word */
WordUtil wordUtil = new WordUtil();
wordUtil.createWord(dataMap, "temp.ftl", configInfo.getOutputLocalPath() +folder, fileName);

然后通过Map将对应的值带入word模板中

导出效果如下

猜你喜欢

转载自blog.csdn.net/u010606701/article/details/101050147