freemark工具类简单使用(转)

freemark工具类简单使用

FreeMarker 是一款 模板引擎: 即一种基于模板和要改变的数据, 并用来生成输出文本(HTML网页,电子邮件,配置文件,源代码等)的通用工具。

它不是面向最终用户的,而是一个Java类库,是一款程序员可以嵌入他们所开发产品的组件。

所需要的pom依赖

1

2

3

4

5

<dependency>

    <groupId>org.freemarker</groupId>

    <artifactId>freemarker</artifactId>

    <version>${freemarker.version}</version>

</dependency>

 

工具类代码:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

package com.common.base.utils;

import java.io.*;

import java.util.Locale;

import java.util.Map;

import freemarker.template.Configuration;

import freemarker.template.Template;

/**

 * @Auther: tony_t_peng

 * @Date: 2020-12-08 11:25

 * @Description:

 */

public class FreeMarkerUtil {

    /**

     **   @param fileName 要读取的文件名,包括文件后缀名

     *   * @param item 传入的map

     *   * @param filePath 要读取的文件路径

     */

    public static String generateString(String fileName, String templatePath, Map<String, Object> data) throws IOException {

        StringWriter out = new StringWriter();

        process(fileName,templatePath,data,out);

        return out.getBuffer().toString();

    }

    public static void generateFile(String fileName, String templatePath, Map<String, Object> data,File outFile) throws IOException {

        Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"));

        process(fileName,templatePath,data,out);

    }

    private static void  process(String fileName, String templatePath,Map<String, Object> data, Writer out) throws IOException {

        try {

            // 通过Template可以将模板文件输出到相应的流

            Template template = getTemplate(fileName, templatePath);

            template.process(data, out);

            out.flush();

        catch (Exception e){

            e.printStackTrace();

        }finally {

            if(out!=null){

                out.close();

            }

        }

    }

    private static Template getTemplate(String fileName, String templatePath){

        try {

            // 通过Freemaker的Configuration读取相应的ftl

            Configuration cfg = new Configuration();

            cfg.setEncoding(Locale.CHINA, "utf-8");

            // 设定去哪里读取相应的ftl模板文件

            cfg.setDirectoryForTemplateLoading(new File(templatePath));

            // 在模板文件目录中找到名称为name的文件

            Template temp = cfg.getTemplate(fileName);

            return temp;

        catch (IOException e) {

            e.printStackTrace();

        }

        return null;

    }

}

  

单元测试代码:

1

String IDPS_TEMPLATE_NAME="CN.D.MANULIFE.TEMPLATE.ftl";  //模板文件名<br><br> String filePath = getClass().getResource("/tempalte/freemark/").getPath(); //模板文件夹地址<em> File file = new File(OUT_FILE_PATH+"CN.D.MANULIFE.DBSCOVR.txt"); //输出文件对象<br><br> FreeMarkerUtil.generateFile(IDPS_TEMPLATE_NAME,filePath,buildCoverageData(asOfDt),file);//</em>buildCoverageData<em id="__mceDel">封装要给map,用以存放对象</em>

ftl 模板代码  示例:  

1

2

3

4

${header!""}

<#list items as item>

  ${item.field1!""}${item.field2!""}<br></#list>

${trailer!""}

  ${item.field1!""}是非空判断,如果没有非空判断,null的情况下会报错

Spring Boot本身并不是一个直接用于将Freemarker模板生成的DOC文档换为PDF的工具,但它可以作为一个基础框架提供服务整合。通常的做法是结合其他第三方库,例如Thymeleaf、iText或PDFBox等,来进行这个换过程。 以下是一个简化的步骤: 1. **使用Freemarker生成DOC**: Spring Boot可以与Freemarker集成,创建模板并渲染HTML内容。例如,在Controller层中: ```java @GetMapping("/generate-doc") public ResponseEntity<Document> generateDoc(@PathVariable String name) { Map<String, Object> model = ...; // 模板数据 try (ResponseEntity<Document> response = new ResponseEntity<>(new FileSystemResource("templates/" + name + ".ftl"), HttpStatus.OK)) { return response; } catch (IOException e) { throw new RuntimeException(e); } } ``` 2. **换为PDF**: 利用iText、Apache PDFBox或者其他PDF生成库,接收HTML内容并将其化为PDF。在Controller层或者单独的服务类中: ```java @PostMapping("/convert-to-pdf") public ResponseEntity<ByteArrayResource> convertToPdf(@RequestBody String htmlContent) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (HtmlToPdfConverter converter = new HtmlToPdfConverter()) { converter.setBaseFont(FontFactory.getFont(FontFactory.TIMES_ROMAN)); converter.convertToPDF(baos, htmlContent); } catch (Exception e) { throw new RuntimeException(e); } return ResponseEntity.ok() .contentType(MediaType.APPLICATION_OCTET_STREAM) .body(new ByteArrayResource(baos.toByteArray())); } ``` 这里的`HtmlToPdfConverter`是一个假设的类,实际应使用相应的库提供的API。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值