首页>代码>SpringBoot Freemarker定制word文档下载,支持文档内图文导出>/springboot-doc/src/main/java/com/simon/springbootdoc/util/FreeMarkerUtils.java
package com.simon.springbootdoc.util; import freemarker.template.Configuration; import freemarker.template.Template; import sun.misc.BASE64Encoder; import java.io.*; import java.util.Map; /** * @author Simon */ public class FreeMarkerUtils { private static Configuration configuration; private static String templateFolder = ImageUtils.class.getResource("/templates").getPath(); /** * 初始化模板配置 */ static { configuration = new Configuration(); configuration.setDefaultEncoding("utf-8"); try { configuration.setDirectoryForTemplateLoading(new File(templateFolder)); } catch (Exception ex) { ex.printStackTrace(); } } /** * 创建word文件 * * @param fileName * @param map * @param templateName * @return */ public static File exportWord(String fileName, Map map, String templateName) { try { Template template = configuration.getTemplate(templateName); File file = createDoc(fileName, map, template); return file; } catch (Exception ex) { ex.printStackTrace(); } return null; } /** * 创建临时word文件 * * @param fileName * @param map * @param template * @return */ private static File createDoc(String fileName, Map map, Template template) { File f = new File(fileName); try { Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8"); template.process(map, w); w.close(); } catch (Exception ex) { } return f; } /** * 图片转码 * * @param imgFile * @return */ public static String getImgFileToBase64(String imgFile) { InputStream inputStream = null; byte[] buffer = null; try { inputStream = new FileInputStream(imgFile); int count = 0; while (count == 0) { count = inputStream.available(); } buffer = new byte[count]; inputStream.read(buffer); } catch (IOException e) { e.printStackTrace(); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return new BASE64Encoder().encode(buffer); } }