Excel转pdf再转png

controller层

 public AjaxResult viewContract(String contractNum,String openId){
        AjaxResult result = AjaxResult.success();
        try{
           WxSevPerfectServeSignInfo perfectServeVo = perfectServeService.ViewContract(contractNum, openId);
          result.setData(perfectServeVo);
        }catch (BusinessException e){
            result = AjaxResult.failure(e.getMessage());
            result.setCode("100");
        }catch(Exception e){
            result = AjaxResult.failure("***");
            log.error("**",contractNum,openId, e);
        }
        return result;
    }

service

 @Transactional(readOnly = true)
    public WxSevPerfectServeSignInfo ViewContract(String contractNum, String openId) throws Exception {
        WxSevPerfectServeSignInfo contractInfo = wxsevPerfectServeSignInfoMapper.getByContractNum(contractNum);//查表看有没有,没有就调用下面的create方法生成一个
        if (contractInfo == null || StringUtil.isEmpty(contractInfo.getContractPdfPath())) {

            contractInfo = createContract(contractNum, openId);
        }

        return contractInfo;
    }

createContract

public WxSevPerfectServeSignInfo createContract(String contractNum, String openId) throws Exception {
        HashMap<String, Object> map = new HashMap<>();//map主要是装excel模板需要的数据进去
         map.put("ActiveDate","生效日期:" +  DateUtil.changeDateTOStr3(perfectServeVo.getActiveDate()));//例如这样,后面是日期工具类的转换时间格式的方法
         for (String str:map.keySet()) {
            String value = String.valueOf(map.get(str));
           if (value.contains("null")){
               String s = value.replace("null", "");
               map.put(str,s);
           }
        }//装完后,将一些为null的值替换成空字符串
           ExcelUtil.replaceModelMap(map, templatePath, contractExcelPath);//把数据、模板的路径和数据模板结合后的保存路径传给excel的工具类进行填充和保存
        ExportUtil.excel2Pdf(contractExcelPath, contractPdfPath);//将填充好的excel转为pdf
        String[] images = ExportUtil.pdf2Png(contractPdfPath);//将pdf转为png
 try {
            File excelPath = new File(contractExcelPath);
            if (excelPath.isFile() && excelPath.exists()) {
                excelPath.delete();
            }
        } catch (Exception e) {
            logger.error("删除excel文件出错", e);
        }

ExcelUtil.replaceModelMap
用到的依赖

 <dependency>
        <groupId>org.apache.poigroupId>
        <artifactId>poi-ooxmlartifactId>
        <version>3.14version>
        dependency>

        <dependency>
        <groupId>org.apache.poigroupId>
        <artifactId>poi-scratchpadartifactId>
        <version>3.14version>
        dependency>
 public static boolean replaceModelMap(Map map, String sourceFilePath, String targetFilePath) {
        boolean bool = true;
        try {
            POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(sourceFilePath));
            HSSFWorkbook wb = new HSSFWorkbook(fs);
            HSSFSheet sheet = wb.getSheetAt(0);
            Iterator rows = sheet.rowIterator();
            while (rows.hasNext()) {
                HSSFRow row = (HSSFRow) rows.next();
                if (row != null) {
                    int num = row.getLastCellNum();
                    for (int i = 0; i < num; i++) {
                        HSSFCell cell = row.getCell(i);
                        if (cell != null) {
                            if(cell.getCellType() != 1)//如果单元格非String类型,不管
                                continue;
                            String value = cell.getStringCellValue();
                            if(StringUtil.isNotEmpty(value)){
                                String object = "";
                                if(value.startsWith("#") && value.endsWith("#")){
                                    String substring = value.substring(1, value.length() - 1);
                                    if (map.containsKey(substring)){
                                        object = String.valueOf(map.get(substring));
                                        value = value.replaceAll("(?i)#" + substring + "#", object);
                                        cell.setCellValue(value);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            // 输出文件
            File file = new File(targetFilePath).getParentFile();
            if (!file.exists()) {
                file.mkdirs();
            }
            FileOutputStream fileOut = new FileOutputStream(targetFilePath);
            wb.write(fileOut);
            fileOut.close();
            wb.close();
            fs.close();
        } catch (Exception e) {
            bool = false;
            e.printStackTrace();
            logger.error("替换失败",e);
        }
        return bool;
    }

ExportUtil.excel2Pdf
用到的依赖

 <dependency>
            <groupId>com.asposegroupId>
            <artifactId>aspose-cellsartifactId>
            <version>8.5.2version>
            <scope>systemscope>
            <systemPath>${project.basedir}/src/main/webapp/WEB-INF/lib/aspose-cells-8.5.2.jarsystemPath>
        dependency>
 public static void excel2Pdf(String excelPath, String pdfPath) {
        if (!ExportUtil.GetLicense()) {
            System.out.println("无法获取Excel License,请联系管理员检查");
        }
        try {
            long old = System.currentTimeMillis();
            Workbook wb = new Workbook(excelPath);// 原始excel路径
            wb.save(pdfPath, com.aspose.cells.SaveFormat.PDF);
            long now = System.currentTimeMillis();
            logger.info("开始进行Excel:" + excelPath + "转换PDF:" + pdfPath + " , 共耗时:" + ((now - old) / 1000.0) + "秒");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("保存PDF失败",e);

        }
    }

ExportUtil.pdf2Png
用到的依赖

 <dependency>
            <groupId>org.apache.pdfboxgroupId>
            <artifactId>pdfboxartifactId>
            <version>2.0.13version>
        dependency>

        <dependency>
            <groupId>org.apache.pdfboxgroupId>
            <artifactId>fontboxartifactId>
            <version>2.0.13version>
        dependency>
public static String[] pdf2Png(String pdfPath) {
        File file = new File(pdfPath);
        PDDocument pdDocument;
        String[] pngs = null;
        try {
            String imgFolderPath = file.getParent();
            int dot = file.getName().lastIndexOf('.');
            String imagePDFName = file.getName().substring(0, dot); // 获取图片文件名
            pdDocument = PDDocument.load(file);
            PDFRenderer renderer = new PDFRenderer(pdDocument);
                /* dpi越大转换后越清晰,相对转换速度越慢 */
            PdfReader reader = new PdfReader(pdfPath);
            int pages = reader.getNumberOfPages();
            StringBuffer imgFilePath = null;
            pngs = new String[pages];
            for (int i = 0; i < pages; i++) {
                String imgFilePathPrefix = imgFolderPath + File.separator + imagePDFName;
                imgFilePath = new StringBuffer();
                imgFilePath.append(imgFilePathPrefix);
                imgFilePath.append("_");
                imgFilePath.append(String.valueOf(i + 1));
                imgFilePath.append(".png");
                File dstFile = new File(imgFilePath.toString());
                BufferedImage image = renderer.renderImageWithDPI(i, 500);
                ImageIO.write(image, "png", dstFile);
                pngs[i] = imgFilePath.toString();
            }
            pdDocument.close();
            reader.close();
         //   System.out.println("PDF文档转PNG图片成功!");
        } catch (IOException e) {
            logger.error("PDF转图片失败.",  e);
        }
        return pngs;
    }

你可能感兴趣的:(java,前端,jvm)