springboot整合freemarker根据模板导出word,pdf,以及word转pdf,读取工程resources下的模板文件,并导出压缩包zip

springboot整合freemarker根据模板导出word,pdf,以及word转pdf,读取工程resources下的模板文件

1、maven依赖

<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.30</version>
</dependency>
<dependency>
    <groupId>com.aspose</groupId>
    <artifactId>aspose-words</artifactId>
    <version>15.8.0</version>
</dependency>

2、创建模板

一种快捷创建模板的方式,将word样本打开,另存为xml文件

3、将生成好的xml模板文件放入resources下,新建一个templates文件夹将文件放入下面

4、导出world

public ByteArrayOutputStream createWord(Map<String, Object> dataMap, String templateName,String fileName) {
    log.info("{}:产品要素表导出word开始生成...",fileName);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    OutputStreamWriter oWriter = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8);
    Writer out = new BufferedWriter(oWriter);
    try {
        InputStream inputStream = this.getClass().getResourceAsStream("/templates/".concat(templateName));
        createWordTemplate(new String(IOUtils.toByteArray(inputStream))).process(dataMap, out);
    } catch (IOException | TemplateException e) {
        log.error("{}:产品要素表导出word失败:",fileName, e);
    } finally {
        try {
            out.flush();
            out.close();
        } catch (IOException e) {
            log.error("{}:产品要素表导出word关闭流失败", fileName,e);
        }
    }
    log.info("{}:产品要素表导出word生成完成...",fileName);
    return outputStream;
}

5.word转pdf

public static ByteArrayOutputStream wordToPdf(ByteArrayOutputStream outputStream,String fileName) {
    log.info("{}:产品要素表导出pdf开始生成...",fileName);
    ByteArrayOutputStream byteArrayOutputStream = null;
    // 验证License 若不验证则转化出的pdf文档会有水印产生:
    // Evaluation Only. Created with Aspose.Words. Copyright 2003-2015 Aspose Pty Ltd
    if (getLicense()) {
        byteArrayOutputStream = new ByteArrayOutputStream();
        ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
        try {
            Document document = new Document(inputStream);
            document.save(byteArrayOutputStream, SaveFormat.PDF);
        } catch (Exception e) {
            log.error("{}:产品要素表导出pdf,word转pdf失败",fileName, e);
        }
    }
    log.info("{}:产品要素表导出pdf生成完成...",fileName);
    return byteArrayOutputStream;
}

完成代码

import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import com.manager.dto.product.rsp.ExportProductPdfAndWordRsp;
import com.manager.enums.ContentTypeEnum;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.core.io.ClassPathResource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


/**
 * @author yanjj
 * @ClassName HtmlToWordUtil
 * @date 2022/6/7
 */
@Slf4j
public class HtmlToWordUtil {

    private static AtomicInteger TEMPLATE_ID = new AtomicInteger(0);

    private final static String  DOC = ".doc";

    private final static String  PDF = ".pdf";

    public HtmlToWordUtil() {
    }

    public ByteArrayOutputStream createWord(Map<String, Object> dataMap, String templateName,String fileName) {
        log.info("{}:产品要素表导出word开始生成...",fileName);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        OutputStreamWriter oWriter = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8);
        Writer out = new BufferedWriter(oWriter);
        try {
            InputStream inputStream = this.getClass().getResourceAsStream("/templates/".concat(templateName));
            createWordTemplate(new String(IOUtils.toByteArray(inputStream))).process(dataMap, out);
        } catch (IOException | TemplateException e) {
            log.error("{}:产品要素表导出word失败:",fileName, e);
        } finally {
            try {
                out.flush();
                out.close();
            } catch (IOException e) {
                log.error("{}:产品要素表导出word关闭流失败", fileName,e);
            }
        }
        log.info("{}:产品要素表导出word生成完成...",fileName);
        return outputStream;
    }

    /**
     * 动态创建模板
     * @param templateString 
     * @return
     * @throws IOException
     */
    private Template createWordTemplate(String templateString) throws IOException {
        StringTemplateLoader stringLoader = new StringTemplateLoader();
        String id = String.valueOf(TEMPLATE_ID.incrementAndGet());
        stringLoader.putTemplate(id, templateString);
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_30);
        cfg.setDefaultEncoding("utf-8");
        cfg.setTemplateLoader(stringLoader);
        return cfg.getTemplate(id);
    }


    /**
     * word转pdf
     * @param outputStream
     * @param fileName
     * @return
     */
    public static ByteArrayOutputStream wordToPdf(ByteArrayOutputStream outputStream,String fileName) {
        log.info("{}:产品要素表导出pdf开始生成...",fileName);
        ByteArrayOutputStream byteArrayOutputStream = null;
        // 验证License 若不验证则转化出的pdf文档会有水印产生:
        // Evaluation Only. Created with Aspose.Words. Copyright 2003-2015 Aspose Pty Ltd
        if (getLicense()) {
            byteArrayOutputStream = new ByteArrayOutputStream();
            ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
            try {
                Document document = new Document(inputStream);
                document.save(byteArrayOutputStream, SaveFormat.PDF);
            } catch (Exception e) {
                log.error("{}:产品要素表导出pdf,word转pdf失败",fileName, e);
            }
        }
        log.info("{}:产品要素表导出pdf生成完成...",fileName);
        return byteArrayOutputStream;
    }

    /**
     * 去除水印
     * Evaluation Only. Created with Aspose.Words. Copyright 2003-2015 Aspose Pty Ltd.
     */
    private static boolean getLicense() {
        boolean result = false;
        try {
            InputStream inputStream = new ClassPathResource("license.xml").getInputStream();
            License aposeLic = new License();
            aposeLic.setLicense(inputStream);
            result = true;
        } catch (Exception e) {
            log.error("产品要素表导出pdf,word转pdf去Aspose.Words水印失败", e);
        }
        return result;
    }

    /**
     * wordAndPdf 下载类型,0 word和pdf, 1 word, 2 pdf
     * 压缩文件
     */
    public void zipPdfOrWord(String fileName, List<ExportProductPdfAndWordRsp> importDtoList, Integer wordAndPdf, String templateName, HttpServletResponse response) throws IOException {
        response.setContentType(ContentTypeEnum.STREAM.getCodeText());
        response.setHeader("Content-disposition", "attachment; filename*=utf-8''" + URLEncoder.encode(fileName + ".zip", "UTF-8"));
        ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream());
        if (CollectionUtils.isEmpty(importDtoList)) {
            return;
        }
        for (ExportProductPdfAndWordRsp dto : importDtoList) {
            Map<String, Object> importData = getImportData(dto);
            if (NumberUtils.INTEGER_ONE.equals(wordAndPdf)) {
                ByteArrayOutputStream word = createWord(importData, templateName,dto.getProductFullName());
                String name = ("word/") + dto.getProductFullName().concat(DOC);
                zipOut.putNextEntry(new ZipEntry(name));
                zipOut.write(word.toByteArray());
            }
            if (NumberUtils.INTEGER_TWO.equals(wordAndPdf)) {
                ByteArrayOutputStream word = createWord(importData, templateName,dto.getProductFullName());
                ByteArrayOutputStream pdf = wordToPdf(word,dto.getProductFullName());
                String name = ("pdf/") + dto.getProductFullName().concat(PDF);
                zipOut.putNextEntry(new ZipEntry(name));
                zipOut.write(pdf.toByteArray());
            }
            if (NumberUtils.INTEGER_ZERO.equals(wordAndPdf)) {
                ByteArrayOutputStream word = createWord(importData, templateName,dto.getProductFullName());
                String wordName = ("word/") + dto.getProductFullName().concat(DOC);
                zipOut.putNextEntry(new ZipEntry(wordName));
                zipOut.write(word.toByteArray());
                ByteArrayOutputStream pdf = wordToPdf(word,dto.getProductFullName());
                String pdfName = ("pdf/") + dto.getProductFullName().concat(PDF);
                zipOut.putNextEntry(new ZipEntry(pdfName));
                zipOut.write(pdf.toByteArray());
            }
        }
        zipOut.closeEntry();
        response.flushBuffer();
        zipOut.close();
    }

    private static Map<String, Object> getImportData(ExportProductPdfAndWord dto) {
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("userName", dto.getUserName());
        dataMap.put("age", dto.getAge());
        return dataMap;
    }

6.调用

new HtmlToWordUtil().zipPdfOrWord("导出",rspList,req.getWordAndPdf(), "导出.xml",response);

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

《小书生》

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

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

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

打赏作者

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

抵扣说明:

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

余额充值