Java使用ftl模板文件生成Word,以及Word转换图片或Pdf工具类

Java使用ftl模板文件生成Word

一、写在前面

最近在项目中使用打印功能,发现这个功能我已经写过多次了,下面这个文章的发步日期在2020年,不得不感慨时间之快啊。
https://blog.csdn.net/weixin_43238452/article/details/109636200?spm=1001.2014.3001.5501
下面介绍一下应用场景:这次项目依旧是springboot项目,使用ftl模版生成的word文件。比上一版相比更加灵活而且实用性更高,还可插入base64图片进行展示
关于ftl模板我会简单介绍一下使用的心得,其实也是一些标签而已,熟悉以后操作起来也比较快

二、word转ftl模板,ftl标签简单介绍
1.找到使用的word模板(如图是我自己编写的一个word模板,后续会以此进行操作)

在这里插入图片描述

2.左上角点击另存为xml文件

在这里插入图片描述

3.直接将保存的xml文件改后缀名为 ftl 然后放到项目 resources/static 目录下。进去之后idea会自动格式化,如果没有,建议按ctrl+f搜索对应的汉字进行定位(注:模板必须在static目录下,改个英文名防止乱码)

在这里插入图片描述

4.标签及语法
(1)替换标签可以是对象点属性也可以是单个变量

在这里插入图片描述

(2) 循环标签,如图会根据list的大小进行循环赋值

在这里插入图片描述

(3)判断标签如图,第一个为判断cks遍历下标是否大于5,第二层为判断cks是否拥有下一个数据

在这里插入图片描述

5.代码编写
1.导入maven依赖,freemarker和word工具类依赖aspose-words,后者可点击下载,下载jar包后自行打入maven仓库,我是直接导入的依赖坐标
		 <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
        </dependency>

        <dependency>
            <groupId>com.luhuiguo</groupId>
            <artifactId>aspose-words</artifactId>
            <version>22.10</version>
        </dependency>
2.模板替换工具类

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.Version;
/**
     * 
     * @param dataMap 存储数据的map集合
     * @param savePath 生成word保存路径
     */
    public static void ftl2Word(Map<String, Object> dataMap, String savePath) {
        try {
            Configuration configuration = new Configuration(new Version("2.3.0"));
            configuration.setDefaultEncoding("utf-8");
            //.ftl配置文件所在路径
            Template template = configuration.getTemplate("demo.ftl", "utf-8");
            /*File file = new File("resources/static");
            String absolutePath = file.getAbsolutePath();*/
            //上面获取路径有bug,absolutePath 既存demo.ftl的路径,不包含demo.ftl
            // 如:D:\IdeaProjectsTwo\beauty-master\beauty-main\src\main\resources\static
            configuration.setDirectoryForTemplateLoading(new File(absolutePath));
            //输出文档路径及名称
            File outFile = new File(savePath);
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),
                    "utf-8"), 10240);
            template.process(dataMap, out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
3.word工具类
/**
 * @Author: SongTiankai
 * @Description: word工具类
 * @Date: 2022/12/9 19:34
 * @Version: 1.0
 */
public class WordUtil {


    /**
     * @Description: 验证aspose.word组件是否授权:无授权的文件有水印标记
     */
    public static boolean isWordLicense() {
        boolean result = false;
        try {
            String s = "<License><Data><Products><Product>Aspose.Total for Java</Product><Product>Aspose.Words for Java</Product></Products><EditionType>Enterprise</EditionType><SubscriptionExpiry>20991231</SubscriptionExpiry><LicenseExpiry>20991231</LicenseExpiry><SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber></Data><Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature></License>";
            ByteArrayInputStream inputStream = new ByteArrayInputStream(s.getBytes());
            com.aspose.words.License license = new com.aspose.words.License();
            license.setLicense(inputStream);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    
    public static void word2pdf(String docPath, String savePath) {
        try {
            String s = "<License><Data><Products><Product>Aspose.Total for Java</Product><Product>Aspose.Words for Java</Product></Products><EditionType>Enterprise</EditionType><SubscriptionExpiry>20991231</SubscriptionExpiry><LicenseExpiry>20991231</LicenseExpiry><SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber></Data><Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature></License>";
            ByteArrayInputStream is = new ByteArrayInputStream(s.getBytes());
            License license = new License();
            license.setLicense(is);
            com.aspose.words.Document document = new com.aspose.words.Document(docPath);
            document.save(new FileOutputStream(new File(savePath)), SaveFormat.PDF);
        } catch (Exception e) {

            e.printStackTrace();
        }
    }


    public static void word2Image(String docPath, String savePath) {
        try {
            String s = "<License><Data><Products><Product>Aspose.Total for Java</Product><Product>Aspose.Words for Java</Product></Products><EditionType>Enterprise</EditionType><SubscriptionExpiry>20991231</SubscriptionExpiry><LicenseExpiry>20991231</LicenseExpiry><SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber></Data><Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature></License>";
            ByteArrayInputStream is = new ByteArrayInputStream(s.getBytes());
            License license = new License();
            license.setLicense(is);
            com.aspose.words.Document document = new com.aspose.words.Document(docPath);
            document.save(new FileOutputStream(new File(savePath)), SaveFormat.PNG);
        } catch (Exception e) {

            e.printStackTrace();
        }
    }

}
6.工具测试
1.测试代码
@ApiOperation("word测试接口")
    @PostMapping("/testCreat")
    public ResultData testCreat() {
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("ckd", "生产一车间");
        dataMap.put("llrq", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        dataMap.put("llbm", "领料部");
        dataMap.put("kgy", "王武");
        dataMap.put("zg", "占山");
        dataMap.put("llr", "里斯");
        WordUtil.ftl2Word(dataMap, "D:\\home\\word\\ckd.doc");
        WordUtil.word2Image("D:\\home\\word\\ckd.doc", "D:\\home\\word\\ckd.png");
        WordUtil.word2pdf("D:\\home\\word\\ckd.doc", "D:\\home\\word\\ckd.pdf");
        return new SuccessResultData();
    }
2.pdf

在这里插入图片描述

3.word

在这里插入图片描述

4.png

在这里插入图片描述

7.小结

至此功能实现,今天太晚了,明天研究一下路径获取,更新后给大家贴代码!
如果对你有帮助,希望可以一键三连!
感谢!

评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爪哇Bubble

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值