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文件

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

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

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

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;


/**
 * @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 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 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);

你可能感兴趣的:(java杂谈,spring,boot,java)