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

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

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

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

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

    org.freemarker
    freemarker
    2.3.30

    com.aspose
    aspose-words
    15.8.0
2、创建模板

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

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

4、导出world
public ByteArrayOutputStream createWord(Map 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;



@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 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;
    }

    
    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);
    }


    
    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;
    }

    
    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;
    }

    
    public void zipPdfOrWord(String fileName, List 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 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 getImportData(ExportProductPdfAndWord dto) {
        Map dataMap = new HashMap<>();
        dataMap.put("userName", dto.getUserName());
        dataMap.put("age", dto.getAge());
        return dataMap;
    }
6.调用
new HtmlToWordUtil().zipPdfOrWord("导出",rspList,req.getWordAndPdf(), "导出.xml",response);

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/966740.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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