freemarker动态生成word和pdf

1、使用freemarker生成word

freemarker生成word的方法网上有很多,比较简单,基本上都差不多

所需工具

freemarker

<dependency>
	<groupId>org.freemarker</groupId>
	<artifactId>freemarker</artifactId>
	<version>2.3.31</version>
</dependency>
准备模板

准备一个word文档,为了防止有的用户还在使用非常老的word版本,这里选择生成2003版的 .doc 文件(也可以根据需求使用 .docx 文件),注意先将文档中要替换的内容写成 ${} 的形式,方便使用freemarker进行内容替换(文档中加入了一张图片,是为了演示怎么在生成word文档时添加图片)
在这里插入图片描述
另存为xml文件
在这里插入图片描述
生成的xml文件内容没有格式化,不方便查看,可以先将文件内容格式化(比如使用idea),然后找个文档编辑器,nodepad++,ueditor等都可以,直接在idea里编辑也可以,搜索一下占位符 $ 的位置,有的占位符可能会出现位置错乱,比如可能出现以下情况,这种情况就需要手动处理一下
在这里插入图片描述
这里特殊说明一下图片,图片是以base64编码的形式存在的,生成xml后直接将对应的base64字符串替换成占位符即可,比如 ${photo}
在这里插入图片描述
准备好模板文件后,将模板后缀改成 .ftl 放到工程resource目录下或文件系统目录下即可

代码

FreeMarkerForDocUtil.java

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * word文档生成工具类
 *
 * @author blank
 */
public class FreeMarkerForDocUtil{
   

    private static Logger logger = LoggerFactory.getLogger(FreeMarkerForDocUtil.class);

    /**
     * 生成word文档,并保存成文件
     * @param templatePath 文档模板所在的文件夹
     * @param templateFileName 文档模板的名称
     * @param dataMap 模板中需要替换的数据
     * @param targetFilePath 目标文件路径
     * @param targetFileName 目标文件名
     * @return File
     * @throws IOException
     * @throws TemplateException
     */
    public static File generateWord(String templatePath, String templateFileName, Map<String,Object> dataMap,String targetFilePath,String targetFileName) throws IOException, TemplateException {
   
        byte[] wordBytes = createWord(templatePath, templateFileName, dataMap);
        File filePath = new File(targetFilePath);
        if(filePath.isDirectory() && !filePath.exists()){
   
            filePath.mkdirs();
        }
        File file = new File(targetFilePath+File.separator+targetFileName);
        FileOutputStream fOut = new FileOutputStream(file);
        fOut.write(wordBytes);
        fOut.close();
        return file;
    }

    /**
     * 生成word文档,并返回byte数组
     * @param templatePath 文档模板所在的文件夹
     * @param templateFileName 文档模板的名称
     * @param dataMap 模板中需要替换的数据
     * @return 二进制数组
     * @throws IOException
     * @throws TemplateException
     */
    public static byte[] generateWord(String templatePath, String templateFileName, Map<String,Object> dataMap) throws IOException, TemplateException {
   
        byte[] wordBytes = createWord(templatePath, templateFileName, dataMap);
        return wordBytes;
    }

    /**
     * 生成word文档
     * @param templatePath 文档模板所在的文件夹
     * @param templateFileName 文档模板的名称
     * @param dataMap 模板中需要替换的数据
     * @return 二进制数组
     */
    private static byte[] createWord(String templatePath, String templateFileName, Map<String,Object> dataMap) throws IOException, TemplateException {
   
        Configuration configuration = getConfiguration(templatePath);
        Template template = configuration.getTemplate(templateFileName);

        for(Map.Entry<String,Object> entry:dataMap.entrySet()){
   
            String value = entry.getValue().toString();
            // 处理转义字符
            value = transformForDoc(value);
            entry.setValue(value);
        }

        StringWriter stringWriter = new StringWriter();
        Writer out = new BufferedWriter(stringWriter);
        try {
   
            template.process(dataMap,out);
        } catch (TemplateException e) {
   
            logger.error(e.getMessage(),e);
            throw e;
        }finally 
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值