freemarker导出Word文档并在其中插入图片

  1. 先将word转成xml格式,再用notepad将其转为ftl格式(将要填入数据的地方加个占位符,${name})
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.test.person.WordGenerator;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class personServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    public personServlet() {
        super();
    }
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
/*
         * freemarker导出Word文档并在其中插入图片 分页和一页 代码没区别 有四处 xxx.doc
         */
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");
        Map map = new HashMap();

        /*
         * // 通过循环将表单参数放入键值对映射中 // 提示:在调用工具类生成Word文档之前应当检查所有字段是否完整 //
         * 否则Freemarker的模板殷勤在处理时可能会因为找不到值而报错 这里暂时忽略这个步骤了 Enumeration
         * paramNames = request.getParameterNames();
         * while(paramNames.hasMoreElements()) { String key =
         * paramNames.nextElement(); String value = request.getParameter(key);
         * map.put(key, value); }
         */
        map.put("title", "评定");
map.put("img",WordGenerator.getImageString("C:/Users/Public/Pictures/Sample Pictures/3.png"));

        File file = null;
        InputStream fin = null;
        ServletOutputStream out = null;
        try {
            // 调用工具类WordGenerator的createDoc方法生成Word文档
            file = WordGenerator.createDoc(map, "成绩评定表");
            fin = new FileInputStream(file);

            response.setCharacterEncoding("utf-8");
            response.setContentType("application/msword");
            // 设置浏览器以下载的方式处理该文件默认名为xxx.doc //URLEncoder.encode("成绩评定表.doc",
            // "UTF-8")
            response.addHeader("Content-Disposition", "attachment;filename="
                    + new String("成绩评定表.doc".getBytes("GB2312"), "ISO_8859_1"));

            out = response.getOutputStream();
            byte[] buffer = new byte[512]; // 缓冲区
            int b = -1;
            // 通过循环将读入的Word文件的内容输出到浏览器中
            while ((b = fin.read(buffer)) != -1) {
                out.write(buffer, 0, b);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
            // response.getWriter().print("cuowu ");
        } finally {
            if (fin != null)
                fin.close();
            if (out != null)
                out.close();
            if (file != null)
                file.delete(); // 删除临时文件
        }
    }

}
package com.test.person;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

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

public class WordGenerator {
    private static Configuration configuration = null;
    private static Map allTemplates = null;

    static {
        configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");
        configuration.setClassForTemplateLoading(WordGenerator.class,"/com/test/person");
        allTemplates = new HashMap<>(); // Java 7 钻石语法
        try {
            allTemplates.put("成绩评定表",configuration.getTemplate("成绩评定表.ftl"));
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    private WordGenerator() {
        throw new AssertionError();
    }

    public static File createDoc(Map dataMap, String filename)
            throws TemplateException, IOException {
        String name = "temp" + (int) (Math.random() * 100000) + ".doc";
        File f = new File(name);
        Template t = allTemplates.get(filename);

        // 这个地方不能使用FileWriter因为需要指定编码类型否则生成的Word文档会因为有无法识别的编码而无法打开
        Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
        t.process(dataMap, w);
        w.close();

        return f;
    }

    // 将图片转换成BASE64字符串
    public static String getImageString(String imgname) throws IOException {
        InputStream in = null;
        byte[] data = null;
        try {
            in = new FileInputStream(imgname);
            data = new byte[in.available()];
            in.read(data);


            in.close();
        } catch (IOException e) {
            throw e;
        } finally {
            if (in != null)
                in.close();
        }
        BASE64Encoder encoder = new BASE64Encoder();
        return data != null ? encoder.encode(data) : "";
    }

}

你可能感兴趣的:(freemarker导出Word文档并在其中插入图片)