springboot中使用freemarker根据flt模板导出word、pdf文档

1.导包:

<!--FreeMarker -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.aspose.words/aspose-words-jdk16 -->
<dependency>
    <groupId>com.aspose.words</groupId>
    <artifactId>aspose-words-jdk16</artifactId>
    <version>14.6.0.0</version>
</dependency>
<repositories>
    <repository>
        <id>aspose-words-jdk16</id>
        <url>https://maven.atlassian.com/3rdparty</url>
        <releases>
            <enabled>true</enabled>
        </releases>
        <snapshots>
            <enabled>true</enabled>
            <updatePolicy>always</updatePolicy>
            <checksumPolicy>fail</checksumPolicy>
        </snapshots>
    </repository>
</repositories>

引入:aspose-words-15.8.0-jdk16.jar

2>数据、包都在云盘上(免费提取哦)

链接:https://pan.baidu.com/s/1KzuXyUBHQK-zGTECu7g7gQ 
提取码:eqgv 
 

代码走起

1.工具类

 

package com.nwpusct.csal.common.util;

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

import java.io.*;

/**
* freemarker + word模板 导出word
*
* @author bobo
* @date 2019/4/14 17:41
*/
public class FreemarkeExportrWordUtil {

    /** 默FreeMarker配置实例 */
    private static final Configuration configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);

    /** 默认采用UTF-8编码 */
    private static final String ENCODING = "UTF-8";

    /** buffer */
    private static final int BUFFER_SIZE = 1024;

    /**
     * 从指定freemarker模板所在文件夹
     *
     * “/”            对应 classpath
     * “/templates/”  对应 classpath下的templates/
     */
    private static final String DEFAULT_POSITION = "/";

    static {
        configuration.setDefaultEncoding(ENCODING);
    }

    /**
     * 导出excel
     *
     * @param templateFileName
     *         模板文件名(含后缀,如:abc.ftl)
     * @param resultFileAllPathName
     *         结果文件全路径文件名 (如: C:/Users/result.doc  再如: C:/Users/result.docx)
     * @param dataObject
     *         与模板中的占位符 对应的 数据信息(一般为:一个专门创建的对象, 或者是Map)
     * @return 生成的word文件
     * @throws IOException
     * @throws TemplateException
     * @date 2019/4/16 10:52
     */
    public static File doExport(String templateFileName, String resultFileAllPathName, Object dataObject)
            throws IOException, TemplateException {
        return doExport(templateFileName, DEFAULT_POSITION, resultFileAllPathName, dataObject);
    }

    /**
     * 导出excel
     *
     * @param templateFileName
     *         模板文件名(含后缀,如:abc.ftl)
     * @param templateFileDir
     *         模板文件所在位置名(如: "/" 代表 classpath)
     * @param resultFileAllPathName
     *         结果文件全路径文件名 (如: C:/Users/result.doc  再如: C:/Users/result.docx)
     * @param dataObject
     *         与模板中的占位符 对应的 数据信息(一般为:一个专门创建的对象, 或者是Map)
     * @return 生成的word文件
     * @throws IOException
     * @throws TemplateException
     * @date 2019/4/16 10:52
     */
    public static File doExport(String templateFileName, String templateFileDir,
                                String resultFileAllPathName, Object dataObject)
            throws IOException, TemplateException {

        // 指定模板文件所在  位置
        configuration.setClassForTemplateLoading(FreemarkeExportrWordUtil.class, templateFileDir);

        // 根据模板文件、编码;获取Template实例
        Template template = configuration.getTemplate(templateFileName, ENCODING);

        File resultFile = new File(resultFileAllPathName);
        // 判断要生成的word文件所在目录是否存在,不存在则创建
        if (!resultFile.getParentFile().exists()) {
            boolean result = resultFile.getParentFile().mkdirs();
        }
        // 写出文件
        try (OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(resultFile));
             Writer writer = new BufferedWriter(osw, BUFFER_SIZE)) {
            template.process(dataObject, writer);
        }
        return resultFile;
    }

    /**
     * 获取图片对应的base64码
     *
     * @param imgFile
     *         图片
     * @return 图片对应的base64码
     * @throws IOException
     * @date 2019/4/16 17:05
     */
    public static String getImageBase64String(File imgFile) throws IOException {
        InputStream inputStream = new FileInputStream(imgFile);
        byte[] data = new byte[inputStream.available()];
        int totalNumberBytes = inputStream.read(data);
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);
    }
}


2.接口

@ApiOperation(value = "pdf文档导出")
@RequestMapping(value = "getExportPdf", method = RequestMethod.GET)
public RestResult<String> getExportPdf(@RequestParam(value = "infoId") String infoId) {
    try {
        NdeReportInfo ndeReportInfo = ndeReportInfoMapper.selectById(infoId);
        String reportParmeter = ndeReportInfo.getReportParmeter();
        // 模板文件名
        String templateFileName = "\\templates\\4-18.ftl";
        // 要生成的文件 全路径文件名E:\learn\SecurityTest\src\main\resources\importWord
        String fileName =
                "\\learn\\SecurityTest\\src\\main\\resources\\importWord\\" + new SimpleDateFormat("yyyyMMddHHmm").format(new Date()) + ".doc";
        JSONArray jsonArray = new JSONArray(reportParmeter);
        Map<String, Object> datas = new HashMap<>();
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            JSONArray tables = jsonObject.getJSONArray("tables");
            List<Map<String, Object>> list = new ArrayList<>();
            datas.put("table" + i, list);
            for (int j = 0; j < tables.length(); j++) {
                JSONObject jsonObject1 = tables.getJSONObject(j);
                JSONObject tbs = jsonObject1.getJSONObject("tbody");
                JSONArray trsTbs = tbs.getJSONArray("trs");
                for (int k = 0; k < trsTbs.length(); k++) {
                    JSONObject jsonTrs = trsTbs.getJSONObject(k);
                    JSONArray tds = jsonTrs.getJSONArray("tds");
                    Map<String, Object> tempMap = new HashMap<>();
                    Integer string = jsonTrs.getInt("loop");
                    if (string == 1) {
                        int line = 0;
                        for (int l = 0; l < tds.length(); l++) {
                            JSONObject jsonTds = tds.getJSONObject(l);
                            String type = jsonTds.getString("type");
                            if (type.equals("input")) {
                                String value = jsonTds.getString("value");
                                tempMap.put("Td" + line, value);
                                line++;
                            } else if (type.equals("label")) {
                                String value1 = jsonTds.getString("label_chn");
                                String value2 = jsonTds.getString("label_en");
                                tempMap.put("Td" + line, value1);
                                line++;
                                tempMap.put("Td" + line, value2);
                                line++;
                            }
                        }
                        list.add(tempMap);
                    }
                    if (string == 0) {
                        for (int l = 0; l < tds.length(); l++) {
                            JSONObject jsonTds = tds.getJSONObject(l);
                            String type = jsonTds.getString("type");
                            if (type.equals("input")) {
                                if (jsonTds.getString("filed").equals("examinationTo")) {
                                    String value = jsonTds.getString("value");
                                    datas.put("examinationTo", value);
                                }
                                if (jsonTds.getString("filed").equals("commissionNo")) {
                                    String value = jsonTds.getString("value");
                                    datas.put("commissionNo", value);
                                }
                                if (jsonTds.getString("filed").equals("reportNo")) {
                                    String value = jsonTds.getString("value");
                                    datas.put("reportNo", value);
                                }
                            }
                        }
                    }
                }
            }
        }

        try {
            File imageFile = new File(ndeReportInfo.getSketch());
            datas.put("myImage",
                    FreemarkeExportrWordUtil.getImageBase64String(imageFile));
        } catch (
                IOException e) {
            e.printStackTrace();
        }
        //保存word
        FreemarkeExportrWordUtil.doExport(templateFileName, fileName, datas);
        File wordFile = new File(fileName);
        if (!wordFile.exists()) {
            return RestResultUtil.failed("文件不存在");
        }
        try {
            //获取文件
            File file = new File("\\learn\\SecurityTest\\src\\main\\resources\\importPdf\\"
                    + new SimpleDateFormat("yyyyMMddHHmm").format(new Date()) + ".pdf");
            //获取文件流
            FileOutputStream os = new FileOutputStream(file);
            // Address是将要被转化的word文档
            Document doc = new Document(fileName);
            // 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF
            doc.save(os, SaveFormat.PDF);
            //删除word原始文件
            //File fileDelete = new File(fileName);
            //fileDelete.delete();
            return RestResultUtil.genSuccessResult(httpPath + file.getPath().replaceAll("\\\\", "/"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return RestResultUtil.failed("导出失败");
}

初次使用,大神莫怪,多提宝贵意见,共同学习!!!谢谢

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
您好!对于Spring Boot使用Freemarker模板生成Word文档并加密的例子,可以按照以下步骤进行操作: 1. 首先,您需要在pom.xml文件添加Freemarker和Apache POI的依赖项。在 `<dependencies>` 标签内添加以下代码: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.2</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency> ``` 2. 创建一个Freemarker模板文件,例如 `template.ftl`,并在其编写Word文档的内容,可以使用Freemarker语法进行动态内容替换。 3. 创建一个Controller类,并添加以下代码: ```java import freemarker.template.Configuration; import freemarker.template.Template; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFEncryptor; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFRun; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import javax.servlet.http.HttpServletResponse; import java.io.OutputStream; import java.util.HashMap; import java.util.Map; @Controller public class WordController { @Autowired private Configuration freemarkerConfiguration; @GetMapping("/generate-word") public void generateWord(HttpServletResponse response) throws Exception { // 加载Freemarker模板 Template template = freemarkerConfiguration.getTemplate("template.ftl"); // 创建Word文档对象 XWPFDocument document = new XWPFDocument(); // 创建段落对象 XWPFParagraph paragraph = document.createParagraph(); XWPFRun run = paragraph.createRun(); // 填充模板内容 Map<String, Object> data = new HashMap<>(); // 添加模板需要的数据,可以根据实际需求自行修改 // 渲染模板 run.setText(templateToString(template, data)); // 加密Word文档 XWPFEncryptor encryptor = new XWPFEncryptor(document); encryptor.encrypt("password"); // 替换为您自己的密码 // 设置响应头 response.setHeader("Content-disposition", "attachment; filename=encrypted_word.docx"); response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document"); // 导出Word文档 OutputStream outputStream = response.getOutputStream(); document.write(outputStream); outputStream.close(); } private String templateToString(Template template, Map<String, Object> data) throws Exception { StringWriter stringWriter = new StringWriter(); template.process(data, stringWriter); return stringWriter.toString(); } } ``` 4. 在Spring Boot的配置文件(例如 `application.properties`)添加以下配置: ```properties spring.freemarker.template-loader-path=classpath:/templates/ ``` 5. 运行Spring Boot应用程序,并访问 `/generate-word` 路径,即可生成并下载加密的Word文档。 请注意,上述代码仅为示例,您可以根据实际需求进行修改和扩展。同时,为了确保文档的安全性,请根据您的需求修改加密密码和文件名。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值