package com.ruoyi.common.utils.document;


import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.*;
import java.util.Map;

public class DocumentHandler {

    private Configuration configuration = null;

    public DocumentHandler() {
        this.configuration = new Configuration();
        this.configuration.setDefaultEncoding("utf-8");
    }

    //将xml文件转成模板
    public Template getTemplate() {
        configuration.setClassForTemplateLoading(this.getClass(),
                "/freeMaker");
        Template t = null;
        try {
            t = configuration.getTemplate("fmaker.xml");//模板xml路径
            t.setEncoding("utf-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return t;
    }

    //获得输出流对象
    public Writer getWriter(String devType) {
        //填充后，新文件路径
        File outFile = new File("renren-fast/src/main/resources/freeMaker/wordTemplate.doc");
        Writer out = null;
        try {
            out = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(outFile), "utf-8"
            ));
        } catch (UnsupportedEncodingException | FileNotFoundException e) {
            e.printStackTrace();
        }
        return out;
    }

    //转化生成word文件
    public void createDoc(Template t, Map dataMap, Writer out) {
        try {
            t.process(dataMap, out);
            out.close();
        } catch (TemplateException | IOException e) {
            e.printStackTrace();
        }
    }

}