Use FreeMarker to export word documents (support to export pictures)

Keywords: Java FreeMarker encoding xml

1, Add maven dependency and import the jar package required by FreeMarker

1 <dependency>
2      <groupId>org.freemarker</groupId>
3      <artifactId>freemarker</artifactId>
4      <version>2.3.20</version>
5 </dependency>

2, Define word template file

3, Modify template xml file

Save the word file you just created as an xml file

 

Modify this xml file, the idea I use for development tools. I put this xml file in the project and format it with Ctrl+Alt+L, so that the content of the file looks clear and easy to modify. You can also use other xml editors, etc

Change the dynamic data in the content of the document to the identity of freemarker. In fact, it is the key in map < string, Object > such as changing Duan rantao to ${name};

The education experience needs to be iterated. Here, you can iterate through the list. All the data stored in the list are Map data, and then take it out again

Fold it up and it looks like this. Don't forget the ending list tag

Next is the picture. In the place where the picture occupation is added, you will see a piece of base64 encoded code. Delete base64 and replace it with ${image}. It is uncertain how many pictures there are, which also needs to be iterated

After all of these are done, the template is finished. Modify the file to. ftl, and then put the template into the project

 

4, Coding

Next is the code part. Write FreeMarkerUtil tool class and test

  1 package com.cccuu.project.utils;
  2 
  3 import freemarker.template.Configuration;
  4 import freemarker.template.DefaultObjectWrapper;
  5 import freemarker.template.Template;
  6 import freemarker.template.TemplateExceptionHandler;
  7 import org.apache.log4j.Logger;
  8 import sun.misc.BASE64Encoder;
  9 
 10 import java.io.*;
 11 import java.util.*;
 12 
 13 /*******************************************
 14  *
 15  * @Package com.cccuu.project.utils
 16  * @Author duan
 17  * @Date 2018/7/27 11:51
 18  * @Version V1.0
 19  *******************************************/
 20 public class FreeMarkerUtil {
 21 
 22     private static Logger log = Logger.getLogger(FreeMarkerUtil.class);
 23     private static final String ENCODING = "UTF-8";
 24     private static Configuration cfg = new Configuration();
 25 
 26     //Initialization cfg
 27     static {
 28         //Set the folder of the template
 29         cfg.setClassForTemplateLoading(FreeMarkerUtil.class, "/templates/word");
 30         // setEncoding This method must set the country and its code, otherwise ftl Chinese in generating html It's going to be a mess
 31         cfg.setEncoding(Locale.getDefault(), ENCODING);
 32         // Set the wrapper for the object
 33         cfg.setObjectWrapper(new DefaultObjectWrapper());
 34         // Set exception handler,In this way, we can ${a.b.c.d}No error even if there are no properties
 35         cfg.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
 36 
 37     }
 38 
 39     //Get template object
 40     public static Template getTemplate(String templateFileName) throws IOException {
 41         return cfg.getTemplate(templateFileName, ENCODING);
 42     }
 43 
 44     /**
 45      * Generate files based on data and template
 46      * @param data             Map Data result set for
 47      * @param templateFileName ftl Template file name
 48      * @param outFilePath      Build file name (with path)
 49      */
 50     public static File crateFile(Map<String, Object> data, String templateFileName, String outFilePath) {
 51         Writer out = null;
 52         File outFile = new File(outFilePath);
 53         try {
 54             // Get template,And set the encoding mode, which must be consistent with the encoding format in the page
 55             Template template = getTemplate(templateFileName);
 56             if (!outFile.getParentFile().exists()) {
 57                 outFile.getParentFile().mkdirs();
 58             }
 59             out = new OutputStreamWriter(new FileOutputStream(outFile), ENCODING);
 60             // Processing template
 61             template.process(data, out);
 62             out.flush();
 63             log.info("By template file" + templateFileName + "generate" + outFilePath + "Success.");
 64         } catch (Exception e) {
 65             log.error("By template file" + templateFileName + "generate" + outFilePath + "error");
 66             e.printStackTrace();
 67         } finally {
 68             try {
 69                 if (out != null) {
 70                     out.close();
 71                 }
 72             } catch (IOException e) {
 73                 log.error("Close Write Object error", e);
 74                 e.printStackTrace();
 75             }
 76         }
 77         return outFile;
 78     }
 79 
 80     //Get pictures of base64 code
 81     public static String getImageBase(String src) throws Exception {
 82         if (src == null || src == "") {
 83             return "";
 84         }
 85         File file = new File(src);
 86         if (!file.exists()) {
 87             return "";
 88         }
 89         InputStream in = null;
 90         byte[] data = null;
 91         try {
 92             in = new FileInputStream(file);
 93             data = new byte[in.available()];
 94             in.read(data);
 95             in.close();
 96         } catch (IOException e) {
 97             e.printStackTrace();
 98         }
 99         BASE64Encoder encoder = new BASE64Encoder();
100         return encoder.encode(data);
101     }
102 
103     public static void main(String[] args) {
104         try {
105             Map<String, Object> data = new HashMap<String, Object>();
106             data.put("name", "Ran Tao paragraph");
107             data.put("sex", "male");
108             data.put("birthday", "1994-03-14");
109             data.put("phone", "17737138812");
110             data.put("address", "Xuchang City, Henan Province");
111             data.put("school", "Jiangxi Normal University of science and technology");
112             List<Map<String, String>> educations = new ArrayList<Map<String, String>>();
113             Map<String, String> paramsMap = new HashMap<String, String>();
114             paramsMap.put("school", "Yuzhou high");
115             paramsMap.put("startDate", "2008-09");
116             paramsMap.put("endDate", "2012-06");
117             paramsMap.put("person", "Li Lei");
118             Map<String, String> paramsMap2 = new HashMap<String, String>();
119             paramsMap2.put("school", "Jiangxi Normal University of science and technology");
120             paramsMap2.put("startDate", "2012-09");
121             paramsMap2.put("endDate", "2016-07");
122             paramsMap2.put("person", "Li Jie");
123             educations.add(paramsMap);
124             educations.add(paramsMap2);
125             data.put("educations", educations);
126             List<String> images = new ArrayList<String>();
127             images.add(getImageBase("C:/Users/Administrator/Desktop/picture/timg.jpg"));
128             images.add(getImageBase("C:/Users/Administrator/Desktop/picture/timg11.jpg"));
129             data.put("images", images);
130             crateFile(data, "Document 1.ftl", "C:/Users/Administrator/Desktop/File/resume.doc");
131         } catch (Exception e) {
132             e.printStackTrace();
133         }
134     }
138 }

Posted by Scip on Fri, 31 Jan 2020 00:45:55 -0800