栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java 使用 freemarker模板 生成 word 并用 aspose 转换成PDF

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java 使用 freemarker模板 生成 word 并用 aspose 转换成PDF

添加依赖:

        
        
            org.springframework.boot
            spring-boot-starter-freemarker
        

        
            com.aspose.cells
            aspose-cells
            20.4 - c
            system
            ${project.basedir}/src/main/resources/lib/aspose-cells-20.4 - c.jar
        

        
            com.aspose.words
            aspose-words
            words-18.10-jdk16
            system
            ${project.basedir}/src/main/resources/lib/aspose-words-18.10-jdk16.jar
        
freemarker生成WORD的工具类
package com.vxdata.pdf.aspose.utils;


import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.Version;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Map;

@Component
public class WordUtil {

    
    @Value("${word2pdf.templatePath}")
    private String templatePath;

    
    public void createWord(Map dataMap, String templateName, String fileName) throws Exception {
        // 设置FreeMarker的版本和编码格式
        Configuration configuration = new Configuration(new Version("2.3.28"));
        configuration.setDefaultEncoding("UTF-8");

        // 设置FreeMarker生成Word文档所需要的模板的路径
        configuration.setDirectoryForTemplateLoading(new File(templatePath));
        // 此处把模版文件都放在 resources 下的 templates 中
        // configuration.setClassForTemplateLoading(WordUtils.class, "/templates");

        // 设置FreeMarker生成Word文档所需要的模板
        Template tem = configuration.getTemplate(templateName, "UTF-8");
        // 创建一个Word文档的输出流
        Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(fileName)), StandardCharsets.UTF_8));
        // FreeMarker使用Word模板和数据生成Word文档
        tem.process(dataMap, out);
        out.flush();
        out.close();
    }
}
注意点

生成图片: 需要base64格式, 先用图片占位, 调整好格式, 然后把图片的base64换成占位符
生成复选框: 整体替换, 不要一个个替换

aspose 生成PDF的工具类 Jar包:

链接:https://pan.baidu.com/s/1YKXbt13w-Bu6-h1TjFTX9A
提取码:ci5q

破解文件: license.xml

aspose需要破解, 破解文件要放在resources下


    
        
            Aspose.Total for Java
            Aspose.Words for Java
        
        Enterprise
        20991231
        20991231
        8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7
    
    sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=

package com.vxdata.pdf.aspose.utils;

import com.aspose.words.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

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


@Slf4j
@Component
public class Word2PdfUtil {
    
    private static boolean getLicense() {
        boolean result = false;
        try {
            InputStream is = new ClassPathResource("/license.xml").getInputStream();
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    
    public Boolean word2pdf(String inputPath, String outPath) {
        try (FileOutputStream os = new FileOutputStream(outPath)) {
            if (getLicense()) {
                Document doc = new Document(inputPath);
                doc.save(os, SaveFormat.PDF);
                return true;
            }
            log.error("转换失败!", "破解失败");
            return false;
        } catch (Exception e) {
            log.error("转换失败!", e);
            return false;
        }
    }
}
调用工具类
package com.vxdata.pdf.aspose.service.impl;

import com.vxdata.pdf.aspose.service.IPdfService;
import com.vxdata.pdf.aspose.utils.Word2PdfUtil;
import com.vxdata.pdf.aspose.utils.WordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;
import java.util.UUID;

@Component
public class PdfServiceImpl implements IPdfService {
    @Autowired
    private WordUtil wordUtil;
    @Autowired
    private Word2PdfUtil word2PdfUtil;
    @Value("${word2pdf.tmpPath}")
    private String tmpPath;

    
    @Override
    public void word2pdf(Map map, HttpServletResponse response, String templateFileName) {
        long start = System.currentTimeMillis();
        try {
            // word与pdf的随机文件名
            String tmpFile = tmpPath + File.separator + UUID.randomUUID().toString();
            String wordFileName = tmpFile + ".docx";
            String pdfFileName = tmpFile + ".pdf";
            // 生成word
            wordUtil.createWord(map, templateFileName, wordFileName);
            // 生成pdf
            Boolean flag = word2PdfUtil.word2pdf(wordFileName, pdfFileName);

            if (flag) {
                byte[] buf = new byte[8 * 1024];
                int len = 0;
                try (InputStream is = new FileInputStream(pdfFileName); OutputStream os = response.getOutputStream();) {
                    while ((len = is.read(buf, 0, buf.length)) != -1) {
                        os.write(buf, 0, len);
                    }
                    os.flush();
                } finally {
                    try {
                        deleteFile(wordFileName);
                        deleteFile(pdfFileName);
                    } catch (Exception e) {
                    }
                }
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        long end = System.currentTimeMillis();
        System.out.println("pdf转换成功,共耗时:" + +(end - start) / 1000.0);
    }

    
    public static boolean deleteFile(String filePath) {
        boolean flag = false;
        File file = new File(filePath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/978362.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号