java生产word文档相关的工具类

freemark工具类

package com.odm.enterprise.utils;

import cn.afterturn.easypoi.word.WordExportUtil;
import cn.afterturn.easypoi.word.entity.MyXWPFDocument;
import cn.hutool.core.lang.Assert;
import freemarker.cache.ClassTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.lang.WordUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Encoder;

import javax.annotation.PostConstruct;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

/**
 * FreeMarkers工具类
 */
@Component
public class FreeMarkerUtil {

    private final Configuration cfg = new Configuration(Configuration.VERSION_2_3_0);

    /**
     * spring加载类时执行该方法,类似于构造函数
     *
     * @throws IOException
     */
    @PostConstruct
    public void buildConfiguration() throws IOException {
        this.cfg.setDefaultEncoding("UTF-8");
//        this.cfg.setDirectoryForTemplateLoading(new File("/Users/Desktop/template/2022-11-29/"));
//        Resource path = new DefaultResourceLoader().getResource("classpath:/template");
//        this.cfg.setDirectoryForTemplateLoading(path.getFile());
        this.cfg.setTemplateLoader(new ClassTemplateLoader(new WordUtils().getClass().getClassLoader(),"/template"));
    }


    /**
     * 创建word文档
     *
     * @param dataMap  需要填入的字段
     * @param template 模板
     * @return 生成的模板文件
     */
    public static File createDoc(Map<?, ?> dataMap, Template template) {
        String name = System.currentTimeMillis() + ".doc";
        File f = new File(name);
        try {
            Writer w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f), StandardCharsets.UTF_8));
            template.process(dataMap, w);
            w.close();
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
        return f;
    }

    /**
     * 导出word
     * <p>第一步生成替换后的word文件,只支持docx</p>
     * <p>第二步下载生成的文件</p>
     * <p>第三步删除生成的临时文件</p>
     * 模版变量中变量格式:{{foo}}
     *
     * @param templatePath word模板地址
     * @param temDir       生成临时文件存放地址
     * @param fileName     文件名
     * @param params       替换的参数
     * @param request      HttpServletRequest
     * @param response     HttpServletResponse
     */
    public static void exportWord(InputStream templatePath, String temDir, String fileName, Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) {
        Assert.notNull(templatePath, "模板路径不能为空");
        Assert.notNull(temDir, "临时文件路径不能为空");
        Assert.notNull(fileName, "导出文件名不能为空");
        Assert.isTrue(fileName.endsWith(".docx"), "word导出请使用docx格式");
        if (!temDir.endsWith("/")) {
            temDir = temDir + File.separator;
        }
        File dir = new File(temDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        try {
            String userAgent = request.getHeader("user-agent").toLowerCase();
            if (userAgent.contains("msie") || userAgent.contains("like gecko")) {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } else {
                fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
            }
            MyXWPFDocument doc = new MyXWPFDocument(templatePath);
            WordExportUtil.exportWord07(doc, params);
            String tmpPath = temDir + fileName;
            FileOutputStream fos = new FileOutputStream(tmpPath);
            doc.write(fos);
            // 设置强制下载不打开
            response.setContentType("application/force-download");
            // 设置文件名
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
            OutputStream out = response.getOutputStream();
            doc.write(out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            delFileWord(temDir, fileName);//这一步看具体需求,要不要删
        }
    }

    /**
     * 删除零时生成的文件
     */
    public static void delFileWord(String filePath, String fileName) {
        File file = new File(filePath + fileName);
        File file1 = new File(filePath);
        file.delete();
        file1.delete();
    }

    public static String encodeImageToBase64(File file) throws Exception {
        //将图片文件转化为字节数组字符串,并对其进行Base64编码处理
        InputStream in = null;
        byte[] data = null;
        //读取图片字节数组
        try {
            in = new FileInputStream(file);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
            throw new Exception("图片上传失败!");
        }
        //对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        String base64 = encoder.encode(data);
        return base64;//返回Base64编码过的字节数组字符串
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        String a = "张三";
        a = new String(a.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
//        a = URLEncoder.encode(a, "ISO_8859_1");
        System.out.println(a);
    }

    /**
     * 导出word
     *
     * @param response 响应流
     * @param title    导出的文件名称
     */
    public void export(HttpServletResponse response, Map<?, ?> map, String title, String templateName) {
        File file;
        Template freemarkerTemplate;
        try {
            freemarkerTemplate = cfg.getTemplate(templateName);
            // 调用工具类的createDoc方法生成Word文档
            file = createDoc(map, freemarkerTemplate);
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, title);
            FileUtils.writeBytes(file.getAbsolutePath(), response.getOutputStream());
            FileUtils.deleteFile(file.getAbsolutePath());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 渲染模板数据
     *
     * @param template 模板类
     * @param model    数据
     * @return
     */
    private String renderTemplate(Template template, Object model) {
        StringWriter result = new StringWriter();
        try {
            template.process(model, result);
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result.toString();
    }

    /**
     * 生成文件
     *
     * @param ftlFileName ftl文件名称
     * @param data        数据
     * @param filePath    生成文件路径
     */
    public void createFile(String ftlFileName, Object data, String filePath) {
        Writer out = null;
        try {
            String result = this.renderTemplate(cfg.getTemplate(ftlFileName, "UTF-8"), data);
            File file = new File(filePath);
            if (file.exists()) {
                FileUtils.deleteFile(filePath);
            }
            FileUtils.mkdirs(filePath);
            out = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(filePath), StandardCharsets.UTF_8), 1024);
            out.write(result);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public String getImageBase(String src) {
        if (src == null || src == "") {
            return "";
        }
        File file = new File(src);
        if (!file.exists()) {
            return "";
        }
        InputStream in = null;
        byte[] data = null;
        try {
            in = new FileInputStream(file);
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }
        try {
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);
    }

    public String getEmpAutograph(String filePath) {
        String img = null;
        if (StringUtils.isNotEmpty(filePath)) {
            InputStream in = null;
            byte[] picdata = null;
            try {
                in = new FileInputStream(filePath);
                picdata = new byte[in.available()];
                in.read(picdata);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    in.close();
                } catch (IOException e) {

                    e.printStackTrace();
                }
            }
            BASE64Encoder encoder = new BASE64Encoder();
            img = encoder.encode(picdata);
            return img;
        } else {
            return null;
        }
    }

    public void outDocx(File documentFile, InputStream ins, String fileName,
                        HttpServletResponse response) throws IOException {
//        FtlToWordUtil.setDownloadHeader(request, response, fileName);
        response.setContentType("application/force-download");// 设置强制下载不打开
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));//指定下载的文件名
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");

        File docxFile = new File(fileName);
        ZipOutputStream zipout = null;
        InputStream in = null;
        InputStream is = null;

        try {
            OutputStream os = new FileOutputStream(docxFile);
            int bytesRead = 0;
            byte[] buffer2 = new byte[8192];
            while ((bytesRead = ins.read(buffer2, 0, 8192)) != -1) {
                os.write(buffer2, 0, bytesRead);
            }
            os.close();
            ins.close();

            ZipFile zipFile = new ZipFile(docxFile);
            Enumeration<? extends ZipEntry> zipEntrys = zipFile.entries();
            zipout = new ZipOutputStream(response.getOutputStream());
            int len = -1;
            byte[] buffer = new byte[1024];
            while (zipEntrys.hasMoreElements()) {
                ZipEntry next = zipEntrys.nextElement();
                is = zipFile.getInputStream(next);
                // 把输入流的文件传到输出流中 如果是word/document.xml由我们输入
                zipout.putNextEntry(new ZipEntry(next.toString()));
                if ("word/document.xml".equals(next.toString())) {
                    in = new FileInputStream(documentFile);
                    while ((len = in.read(buffer)) != -1) {
                        zipout.write(buffer, 0, len);
                    }
                    in.close();
                } else {
                    while ((len = is.read(buffer)) != -1) {
                        zipout.write(buffer, 0, len);
                    }
                    is.close();
                }
                zipout.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (zipout != null) {
                try {
                    zipout.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (docxFile != null) {
                try {
                    docxFile.delete();// 删除临时文件
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            documentFile.delete();
        }
    }


    /**
     * 生成word文件
     * @param dataMap 数据
     * @param ftlName ftl模板名
     * @param wordName word文件名
     * @return
     */
    public File createDoc(Object dataMap,String ftlName,String wordName) {
        // 设置模本装置方法和路径,FreeMarker支持多种模板装载方法。可以重servlet,classpath,数据库装载,
        Template t = null;
        try {
            //要装载的模板
            t = cfg.getTemplate(ftlName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(t==null){
            return null;
        }
        // 输出文档名称
        File outFile = new File(wordName);
        Writer out =null;

        try {
            out =new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        if(out==null){
            return null;
        }
        try {
            t.process(dataMap, out);
            out.close();
        } catch ( IOException | TemplateException e) {
            e.printStackTrace();
        }
        return outFile;
    }

    /**
     * 导出word文档,响应到请求端
     *
     * @param tempName,要使用的模板
     * @param docName,导出文档名称
     * @param dataMap,模板中变量数据
     * @param resp,HttpServletResponse
     */
    public boolean exportDoc(String tempName, String docName, Map<?, ?> dataMap, HttpServletResponse resp) throws Exception {
        boolean status = false;
        ServletOutputStream sos = null;
        InputStream fin = null;
        if (resp != null) {
            resp.reset();
        }
        Template t = null;
        try {
            // tempName.ftl为要装载的模板
            t = cfg.getTemplate(tempName);
            t.setEncoding("utf-8");
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 输出文档路径及名称 ,以临时文件的形式导出服务器,再进行下载
        String name = "temp" + (int) (Math.random() * 100000) + ".doc";
        File outFile = new File(name);
        Writer out = null;
        try {
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), StandardCharsets.UTF_8));
            status = true;
        } catch (Exception e1) {
            e1.printStackTrace();
        }

        try {
            t.process(dataMap, out);
            out.close();
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            fin = new FileInputStream(outFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 文档下载
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/msword");
        docName = new String(docName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        resp.setHeader("Content-disposition", "attachment;filename=" + docName + ".doc");
        try {
            sos = resp.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] buffer = new byte[512]; // 缓冲区
        int bytesToRead = -1;
        // 通过循环将读入的Word文件的内容输出到浏览器中
        try {
            while ((bytesToRead = fin.read(buffer)) != -1) {
                sos.write(buffer, 0, bytesToRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fin != null)
                try {
                    fin.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if (sos != null)
                try {
                    sos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if (outFile != null)
                outFile.delete(); // 删除临时文件
        }
        return status;
    }
}

Https文件地址转base64

package com.odm.enterprise.utils.image;

import org.springframework.stereotype.Component;
import sun.misc.BASE64Encoder;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * @author bluekingzmm
 * @desc
 * @date 2022年11月25日
 */
@Component
public class HttpRequestUtil {

    //https的
    public static String httpsRequest(String requestUrl, String requestMethod, String outputStr) {

        // StringBuffer buffer = new StringBuffer();
        byte[] data = null;

        try {
            // 创建SSLContext对象,并使用我们指定的信任管理器初始化
            TrustManager[] tm = {new MyX509TrustManager()};
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            URL url = new URL(requestUrl);
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
            httpUrlConn.setSSLSocketFactory(ssf);

            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 设置请求方式(GET/POST)
            httpUrlConn.setRequestMethod(requestMethod);

            if ("GET".equalsIgnoreCase(requestMethod))
                httpUrlConn.connect();

            // 当有数据需要提交时
            if (null != outputStr) {
                OutputStream outputStream = httpUrlConn.getOutputStream();
                // 注意编码格式,防止中文乱码
                outputStream.write(outputStr.getBytes(StandardCharsets.UTF_8));
                outputStream.close();
            }

            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            // InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            // BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            byte[] buffers = new byte[1024];
            //每次读取的字符串长度,如果为-1,代表全部读取完毕
            int len = 0;
            while ((len = inputStream.read(buffers)) != -1) {
                outStream.write(buffers, 0, len);
            }
            inputStream.close();
            data = outStream.toByteArray();

            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
            //jsonObject = JSONObject.fromObject(buffer.toString());
        } catch (Exception ce) {
            System.out.println(ce.getMessage());
        }

        BASE64Encoder encoder = new BASE64Encoder();
        if (data == null) {
            return " ";
        }
        return encoder.encode(data);

    }

    //http的
    public static String getImageStrFromUrl(String imgURL) {
        byte[] data = null;
        HttpURLConnection conn = null;
        try {
            URL url = new URL(imgURL);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);
            conn.setReadTimeout(5 * 1000);
            InputStream inStream = conn.getInputStream();
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            //每次读取的字符串长度,如果为-1,代表全部读取完毕
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            inStream.close();
            data = outStream.toByteArray();

        } catch (IOException e) {
            e.printStackTrace();

        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }

        BASE64Encoder encoder = new BASE64Encoder();
        if (data == null) {
            return "";
        }
        return encoder.encode(data);
        //String base64Image = Base64.getEncoder().encodeToString(data);
        //return base64Image;
    }

    public static void main(String[] args) {
        String get = httpsRequest("https://odm-b.oss-cn-shanghai.aliyuncs.com/odmfile/截屏2022-10-28 16.56.44eb0fb1f176474a7394bbf42ab7987738.png", "GET", null);
        System.out.println(get);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值