freemarker导出pdf

freemarker模板导出doc的之前有写过,这里就不再多说了,不清楚的可以看之前的文章Freemarker 模板导出(带图片)

转换后的文件展示

在这里插入图片描述

FreemarkerUtils工具类(这里用的工具类导出和之前不一样,不仅仅是页面进行下载,还有本地的保存)

package com.sinosoft.common.utils.freemarker;

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

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author 庭前云落
 * @description
 * @date 2022年07月25日 10:45
 */
public class FreemarkerUtils {

    /**
     * 使用 freemarker 生成word文档
     *
     * @param templateDir  模板所在目录路径
     * @param templateName 模板 例如:xxx.ftl
     * @param data         数据
     * @param fileSavePath 文档生成后,存放的路径
     * @param fileName     生成后的文件名称
     * @param response
     * @throws Exception
     */
    public static void freemarkerExport(String templateDir, String templateName, Map<String, Object> data, String fileSavePath, String fileName, HttpServletResponse response) throws Exception {
        // 1.设置 freeMarker的版本和编码格式
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_22);
        configuration.setDefaultEncoding("UTF-8");
        // 2.设置 freeMarker生成Word文档,所需要的模板的路径
        configuration.setDirectoryForTemplateLoading(new File(templateDir));
        // 3.设置 freeMarker生成Word文档所需要的模板 ---> xxx.ftl
        Template t = null;
        try {
            // 模板文件名称
            t = configuration.getTemplate(templateName);
        } catch (IOException e) {
            throw new IOException("获取 ftl模板失败!" + e.getMessage());
        }
        File fileDir = new File(fileSavePath);
        if(!fileDir.exists()){
            fileDir.mkdirs();
        }
        // 4.生成 Word文档的全路径名称
        File outFile = new File(fileSavePath + fileName);
        System.out.println(outFile);
        // 5.创建一个 Word文档的输出流
        Writer writer = null;
        try {
            writer = new OutputStreamWriter(new FileOutputStream(outFile), StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
        try {
            for (Map.Entry<String, Object> entry : data.entrySet()) {
                if (Objects.isNull(entry.getValue())) {
                    data.put(entry.getKey(), "");
                    System.out.println("您输入的" + entry.getKey() + "为空!");
                }else{
                    // String value=entry.getValue().toString().replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\n","<w:br/>");
                    if (!Objects.isNull(entry.getValue()) && entry.getValue().getClass().isInstance(String.class)) {
                        String value=entry.getValue().toString().replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\n","<w:br/>");
                        data.put(entry.getKey(),value );
                    }
                    if (!Objects.isNull(entry.getValue()) && entry.getValue().getClass().isInstance(List.class)) {
                        data.put(entry.getKey(), new ArrayList<>().add(entry.getValue()));
                    }
                    else {
                        String value = entry.getValue().toString().replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\n", "<w:br/>");
                        data.put(entry.getKey(), value);
                    }
                }
            }
            // 6.装载数据
            t.process(data, writer);
            response.setCharacterEncoding("utf-8");
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.setContentType("application/json");

            // 7.读取生成好的 Word文档
            File file = new File(fileSavePath + fileName);
            FileInputStream is = new FileInputStream(file);
            OutputStream os = response.getOutputStream();
            byte[] b = new byte[1024];
            int length;
            while ((length = is.read(b)) > 0) {
                os.write(b, 0, length);
            }
            os.flush();
            os.close();
            writer.flush();
            writer.close();
        } catch (IOException e) {
            throw new IOException(e.getMessage());
        } finally {
            deleteTempFile(fileSavePath + fileName);
        }
    }

    /**
     * 删除临时生成的文件
     */
    public static void deleteTempFile(String filePath) {
        File f = new File(filePath);
        boolean delete = f.delete();
    }
}

数据的查询及填充,不同模板的选择判断这里就不进行展示了。

   /**
     * 文书转pdf保存
     *
     * @return
     */
    @ApiOperation(value = "文书转pdf保存")
    @RequestMapping(value = "/savePetitionTemplatePdf", method = RequestMethod.GET)
    @LogAnnotation("文书转pdf保存")
    public Result savePetitionTemplatePdf(String oid, HttpServletResponse response) {
        try {
            Map<String, String> nameMap = documentApproverInfoService.getName(oid);
            String templateName = nameMap.get("templateName");
            String exportFileName = nameMap.get("fileName");
            String pdfName = nameMap.get("pdfName");
            //给文书赋值
            Map<String, Object> map = documentInfoService.obtainTemplate(oid, templateName);
            //模板所在路径
            String templateFileName = this.getClass().getResource("/").getPath() + "templates" + File.separator;
            //生成word文档
            FreemarkerUtils.freemarkerExport(templateFileName, templateName, map, folder, exportFileName, response);

            // doc转换为pdf
            Document document = new Document();
            document.loadFromFile(folder+exportFileName);
            document.saveToFile(folder+pdfName, FileFormat.PDF);

            return Result.ok().message("保存成功").data(folder+pdfName);
        } catch (Exception e) {
            log.error("保存异常", e);
            return Result.error().message("保存失败");
        }
    }
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值