javaweb使用freemarket 导出word ,pdf 工具类

本文介绍了如何在JavaWeb项目中利用Freemarker工具类进行Word和PDF的导出,虽然不支持扩展后缀名如.docx,但提供了配套资源链接供下载使用。在内容中提到了环境依赖、工具类代码以及相关图片解析和模板后缀名处理的方法。
摘要由CSDN通过智能技术生成

简单记录一些技术点,不是什么难点,但用起来方便,不支持扩展后缀名.例如,可以导出doc,但不支持docx.

环境依赖:该依赖不好导入一般需要手动导入,给一个跟我项目配套资源链接,是我自己上传的,就在本项目中使用https://download.csdn.net/download/camel_gold/13108504

	<!-- https://mvnrepository.com/artifact/org.freemarker/freemarker freemarker模板 -->
		<dependency>
			<groupId>org.freemarker</groupId>
			<artifactId>freemarker</artifactId>
		</dependency>
	<!-- https://mvnrepository.com/artifact/com.aspose.words/aspose-words-jdk16 -->
		<dependency>
			<groupId>com.aspose.words</groupId>
			<artifactId>aspose-words-jdk16</artifactId>
			<version>15.8.0</version>
		</dependency>

工具类

package com.yx.service.common.doc.impl;

import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import com.yx.model.hk.entity.HkWeldingProcedure;
import com.yx.service.common.doc.DocService;
import com.yx.utils.common.FileUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateNotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * created by asus on 2019/8/19.
 */
@Service
@SuppressWarnings("ALL")
class DocServiceImpl implements DocService {

    static Logger logger = LoggerFactory.getLogger(DocServiceImpl.class);
    static String tplPath = "/freemarker/template";
    /**
     * 保存模板
     */
    private static Map<String, Template> tpls = new HashMap<String, Template>();

    static {
        try {
            Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);
            configuration.setDefaultEncoding("utf-8");
            configuration.setNumberFormat("0.#");
            configuration.setClassForTemplateLoading(DocServiceImpl.class, tplPath);
            List<String> files = FileUtil.getAllFiles(DocServiceImpl.class.getResource("/").getPath().replaceAll("^/", "") + tplPath);
            if (files != null) {
                for (String file : files) {
                    try {
                        Template tpl = configuration.getTemplate(file);
                        tpls.put(file, tpl);
                    } catch (TemplateNotFoundException e) {
                        logger.error("未配置模板文件:" + file);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Autowired
    HttpServletRequest req;
    @Autowired
    HttpServletResponse res;

    //获取兼容的文件名
    @Override
    public String genCompitableName(String fileName, String suffix) {
        if (isIE()) {
            try {
                fileName = java.net.URLEncoder.encode(fileName + suffix, StandardCharsets.UTF_8.name());
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return fileName + suffix;
    }

    //下载失败,消息提示
    @Override
    public void failDown(String msg) {
        OutputStreamWriter writer = null;
        try {
            res.reset();
            writer = new OutputStreamWriter(res.getOutputStream(), StandardCharsets.UTF_8);
            String data = "<script language='javascript'>alert(\"" + msg + "\");window.history.back();</script>";
            writer.write(data);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
    *@author 小王
    *@date 2020/10/19 23:16
    ** @param map
     * @param hkWeldingProcedure
     * @param tplFile
    *@return java.io.File
    *@Description:  保存模板文件到本地
    **/
    @Override
    public File save2Local(Map<String, Object> map, String filePath, String tplFile) {
            File file=null,pdfFile=null;
            if(map.size()>0){
                pdfFile=new File(filePath+ ".pdf");
                if(!pdfFile.getParentFile().exists()){
                    //先得到文件的上级目录,并创建上级目录
                    pdfFile.getParentFile().mkdirs();
                }
                if(pdfFile.exists()){
                    pdfFile.delete();
                }
                if (tplFile != null) {
                    Template tpl = tpls.get(tplFile);
                    if (tpl != null) {
                        FileOutputStream fileOs = null;
                        FileInputStream fileIs = null;
                        FileOutputStream pdfOs = null;
                        try {
                            if (tpl.toString().contains("Word.Document")) {
                                file = new File(filePath + ".doc");
                            } else {
                                throw new RuntimeException("请设置word模板");
                            }
                            fileOs = new FileOutputStream(file);
                            Writer w = new OutputStreamWriter(fileOs, StandardCharsets.UTF_8);
                            //freemaker渲染保存
                            tpl.process(map, w);
                            if (getLicense()) {
                                fileIs = new FileInputStream(file);
                                Document doc = new Document(fileIs);
                                //全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
                                pdfOs = new FileOutputStream(pdfFile);
                                doc.save(pdfOs, SaveFormat.PDF);
                            } else {
                                throw new RuntimeException("转换证书异常");
                            }
                        } catch (TemplateException e) {
                            e.printStackTrace();
                            throw new RuntimeException("模板处理异常");
                        } catch (Exception e) {
                            e.printStackTrace();
                            throw new RuntimeException("转换处理异常");
                        } finally {
                            try {
                                if (fileOs != null) {
                                    fileOs.close();
                                }
                                if (fileIs != null) {
                                    fileIs.close();
                                }
                                if (pdfOs != null) {
                                    pdfOs.close();
                                }
                                if (file != null) {
                                    boolean delete = file.delete();
                                }
                            } catch (IOException e) {
                                throw new RuntimeException("IO异常!");
                            }
                        }
                    }else {
                        throw new RuntimeException("模板文件未配置");
                    }
                } else {
                    throw new RuntimeException("模板文件参数空");
                }
            }
            return pdfFile;

    }

    //纯流操作/

    /**
     * 文档创建
     *
     * @param tplFile  模板类型
     * @param fileName 文档名
     * @return
     */
    @Override
    public void genDocEx(Map<String, Object> dataMap, String tplFile, String fileName) {
        if (tplFile != null) {
            Template tpl = tpls.get(tplFile);
            if (tpl != null) {
                if (tpl.toString().contains("Word.Document")) {//文档
                    fileName = genCompitableName(fileName, ".doc");
                } else {//表格
                    fileName = genCompitableName(fileName, ".xls");
                }
                res.reset();
                res.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(), StandardCharsets.ISO_8859_1));
                res.setContentType("application/octet-stream");
                try (ServletOutputStream os = res.getOutputStream()) {
                    Writer w = new OutputStreamWriter(os, StandardCharsets.UTF_8);
                    tpl.process(dataMap, w);
                } catch (TemplateException | IOException e) {
                    e.printStackTrace();
                    throw new RuntimeException("模板处理异常");
                }
            } else {
                throw new RuntimeException("模板文件未配置");
            }
        } else {
            throw new RuntimeException("模板文件参数空");
        }
    }

    /**
     * 文档创建
     *
     * @param tplFile  模板类型
     * 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值