PdfUtil.java 7.4 KB
Newer Older
苗卫卫 committed
1 2 3 4 5
package com.boco.nbd.wios.flow.util;


import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
苗卫卫 committed
6
import com.aspose.words.*;
苗卫卫 committed
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
import com.boco.nbd.cams.core.constant.CamsConstant;
import com.boco.nbd.wios.flow.entity.pdf.BlockPairBo;
import com.boco.nbd.wios.flow.entity.pdf.SurveyDataBo;
import com.boco.nbd.wios.manage.contants.WiosConstant;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.data.PictureRenderData;
import com.deepoove.poi.util.BytePictureUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Date;


/**
 * @author miaoguoqing
 * @version V1.0
 * @ClassName PdfUtils
 * @description 生成pdf 工具类
 * @email miaoguoqing@boco.com.cn
 * @date 2022/10/25
 */
@Slf4j
public class PdfUtil {

    /**
     * 用于判断导出的word是否转pdf
     */
    public static int judgment = 0;

    public void pdfUtils() {
        judgment = 0;
    }

苗卫卫 committed
43 44 45 46 47 48 49 50 51 52 53 54 55 56
    private static boolean getLicense() {
        boolean result = false;

        try {
            InputStream is = PdfUtil.class.getClassLoader().getResourceAsStream("License.xml");
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception var3) {
            var3.printStackTrace();
        }

        return result;
    }
苗卫卫 committed
57 58 59 60 61 62 63

    /**
     * 根据模板生成word
     *
     * @param path     模板的路径
     * @param fileName 生成word文件的文件名
     */
苗卫卫 committed
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
    public void getWord(String path, BlockPairBo blockPairBo, String fileName, HttpServletResponse response) throws Exception {
        ClassPathResource resource = new ClassPathResource(path);
        InputStream is = resource.getInputStream();
        String saveRoute = path.substring(0, path.lastIndexOf("/"));
        XWPFTemplate xwpfTemplate = XWPFTemplate.compile(is);
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        if (judgment == 0) {
            fileName = java.net.URLDecoder.decode(fileName, CamsConstant.UTF_8);
            xwpfTemplate.render(blockPairBo).write(output);
            String pdf = fileName.substring(0, fileName.lastIndexOf(".")) + DateUtil.format(new Date(), DatePattern.PURE_DATETIME_PATTERN) + ".pdf";
            ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray());
            doc2pdf(input, saveRoute + "/" + pdf);
            File file = new File(saveRoute + "/" + pdf);
            //判断文件大小,并压缩
            if (file.length() > WiosConstant.FILE_SIZE) {
                file.delete();
                for (SurveyDataBo bo : blockPairBo.getExperiences()) {
                    compressPictures(bo);
                }
                getWord(path, blockPairBo, fileName, response);
                return;
            }
            try {
                log.info("========================{}下载开始========================", pdf);
                is = new BufferedInputStream(new FileInputStream(saveRoute + "/" + pdf));
                byte[] buffer = new byte[is.available()];
                is.read(buffer);
                response.reset();
                // 设置response的Header
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), CamsConstant.UTF_8));
                response.addHeader("Content-Length", "" + file.length());
                response.setContentType("application/octet-stream");
                response.setCharacterEncoding("utf-8");
                OutputStream os = new BufferedOutputStream(response.getOutputStream());
                os.write(buffer);
                os.flush();
                log.info("========================{}下载结束========================", pdf);
                //删除缓存文件
                file.delete();
            } catch (IOException ex) {
                log.error(pdf + "下载异常:", ex);
                ex.printStackTrace();
            }
        } else {
            fileName = java.net.URLDecoder.decode(fileName, CamsConstant.UTF_8);
            output = new ByteArrayOutputStream();
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            xwpfTemplate.write(output);
            judgment = 0;
        }
        this.close(output);
        this.close(is);
    }
苗卫卫 committed
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171

    /**
     * 关闭输入流
     *
     * @param is
     */
    public void close(InputStream is) {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 关闭输出流
     *
     * @param os
     */
    public void close(OutputStream os) {
        if (os != null) {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 修改图片大小
     *
     * @param
     */
    public SurveyDataBo compressPictures(SurveyDataBo bo) {
        //原始图片的长度和宽度
        int height = bo.getPicture().getHeight();
        int width = bo.getPicture().getWidth();
        //通过比例压缩
        float scale = 0.8f;
        //压缩之后的长度和宽度
        int doWithHeight = (int) (scale * height);
        int dowithWidth = (int) (scale * width);
        bo.setPicture(new PictureRenderData(dowithWidth, doWithHeight, ".png", BytePictureUtils.getUrlBufferedImage(bo.getUrlPath())));
        return bo;
    }

    /**
     * word 转 pdf
     *
     * @param wordPath word 的路径 word 的路径
     * @param pdfPath  pdf 的路径
     */
苗卫卫 committed
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
    public static void doc2pdf(String wordPath, String pdfPath) {
        if (getLicense()) {
            try {
                long old = System.currentTimeMillis();
                File file = new File(pdfPath);
                FileOutputStream os = new FileOutputStream(file);
                Document doc = new Document(wordPath);

                doc.save(os, 40);
                long now = System.currentTimeMillis();
                os.close();
                log.info("共耗时:" + (double) (now - old) / 1000.0D + "秒");
            } catch (Exception var9) {
                var9.printStackTrace();
            }

        }
    }

    public static void doc2pdf(InputStream is, String pdfPath) {
        if (getLicense()) {
            try {
                long old = System.currentTimeMillis();
                File file = new File(pdfPath);
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                FileOutputStream os = new FileOutputStream(pdfPath);
                Document doc = new Document(is);
                PdfSaveOptions options = new PdfSaveOptions();
                // 文字和图像压缩
                options.setExportDocumentStructure(true);
                options.setTextCompression(PdfTextCompression.FLATE);
                options.setImageCompression(PdfImageCompression.AUTO);
                // 接收修订
                doc.acceptAllRevisions();
                doc.save(os, options);
                long now = System.currentTimeMillis();
                os.close();
                log.info("共耗时:" + (double) (now - old) / 1000.0D + "秒");
            } catch (Exception var9) {
                var9.printStackTrace();
            }
        }
    }
苗卫卫 committed
217
}