FreeMarker模板导出pdf(二)之word转化pdf

762 阅读1分钟

书接上回已经完成了,通过FreeMarker模板生成word,接下来需要完成word转换成pdf的过程,在此阶段采用了Aspose.Words技术实现

1. 准备jar包,并使用

下载jar包

链接: pan.baidu.com/s/1WB1kyFo6… 提取码: rrl4

  1. 新建lib目录

截屏2022-03-05 下午10.25.12.png 2. 修改pom文件

<dependency>
    <groupId>com.aspose</groupId>
    <artifactId>aspose-words</artifactId>
    <version>15.8.0</version>
    <scope>system</scope>
    <systemPath>${project.basedir}/lib/aspose-words-15.8.0-jdk16.jar</systemPath>
</dependency>
  1. 在resource目录下配置licenc文件

截屏2022-03-05 下午10.28.35.png

2. 干活

使用下面这个工具类,就可以实现word转成pdf啦,(不过有一点,水印样式变了,还没找到解决办法影响不大)

package com.mc.wine.utils;

import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import lombok.SneakyThrows;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

public class AsposeUtil {

    /**
     * 加载license 用于破解 不生成水印
     */
    @SneakyThrows
    private static void getLicense() {
        try (InputStream is = AsposeUtil.class.getClassLoader().getResourceAsStream("License.xml")) {
            License license = new License();
            license.setLicense(is);
        }
    }

    /**
     * word转pdf
     *
     * @param wordPath word文件保存的路径
     * @param pdfPath  转换后pdf文件保存的路径
     */
    @SneakyThrows
    public static void wordToPdf(String wordPath, String pdfPath) {
        getLicense();
        File file = new File(pdfPath);
        try (FileOutputStream os = new FileOutputStream(file)) {
            Document doc = new Document(wordPath);
            doc.save(os, SaveFormat.PDF);
        }
    }
}

参考: juejin.cn/post/699056…