使用freemarker模板生成带图片的word |
您所在的位置:网站首页 › word填充图片 › 使用freemarker模板生成带图片的word |
文章目录
前言一、制作freemarker模板1、 准备模板2、修改模板
二、后台代码1.引入freemarker依赖2. freemarker工具类方法3. 测试方法
三、测试结果总结
前言
以xml的格式生成word,可以将图片的二进制数据保存在word中,无需考虑图片的存放位置。 一、制作freemarker模板 1、 准备模板首先,新建一个docx,然后往word里粘贴一个图片,再将word另存为xml文件。 新建一个freemarker文件,如 word.ftl,将xml内容拷贝到word.ftl中。 2、修改模板1、找到图片所在的Relationship ,修改成如下格式 2、找到 ,写入图片的title和引用的Relationship (1)title在 ${pict.title}(2)Relationship 在 (3)完整的body如下 ${pict.title} :3、找到 pkg:binaryData标签 将原来的二进制数据删除,并修改为如下格式 ${pict.data} 二、后台代码 1.引入freemarker依赖 org.freemarker freemarker 2.3.28 2. freemarker工具类方法 public static File crateWord(Map data, String templateName, String targetFile) throws IOException, TemplateException { Configuration cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS); String path = templateName.substring(0,templateName.lastIndexOf("/")); String filename = templateName.substring(templateName.lastIndexOf("/") + 1); cfg.setClassForTemplateLoading(TemplateUtils.class, path); cfg.setEncoding(Locale.getDefault(), "UTF-8"); cfg.setObjectWrapper(new DefaultObjectWrapper(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS)); Writer out = null; File outFile = new File(targetFile); try { Template template = cfg.getTemplate(filename, "UTF-8"); out = new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"); template.process(data, out); out.flush(); } finally { try { if (out != null) { out.close(); } } catch (IOException e) { e.printStackTrace(); } } return outFile; } 3. 测试方法 public static void main(String[] args) throws Exception { Map data = getData(); String templateName = "/templates/ftl/word.ftl"; String targetFile = "C:\\Users\\x\\Desktop\\word\\word.docx"; TemplateUtils.crateWord(data,templateName,targetFile); }createWord方法 private static Map getData() throws IOException { Map data = new HashMap(); List pictList = new ArrayList(); Map pict1 = new HashMap(); pict1.put("title", "图片1"); pict1.put("data", TemplateUtils.getBinaryData(bathPath + "test2.jpg")); Map pict2 = new HashMap(); pict2.put("title", "图片2"); pict2.put("data", TemplateUtils.getBinaryData(bathPath + "test3.jpg")); pictList.add(pict1); pictList.add(pict2); data.put("pictList", pictList); return data; }getBinaryData 方法 public static String getBinaryData(String src) throws IOException { File file = new File(src); InputStream in = new FileInputStream(file); byte[] data = new byte[in.available()]; try { in.read(data); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } Base64.Encoder encoder = Base64.getEncoder(); return encoder.encodeToString(data); } 三、测试结果 |
今日新闻 |
点击排行 |
|
推荐新闻 |
图片新闻 |
|
专题文章 |
CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭 |