springboot生成pdf文件html文件 将所有pdf文件用zip压缩打包

实现创建pdf文件代码 通过一个项目id对应多个专家生成多个pdf文件代码

@RequestMapping(value = _MODEL_NAME + "/pdfs")
@ResponseBody
public String pdfs(@RequestBody Integer[] ids,
                   HttpServletResponse resp,
                   HttpServletRequest req) {
    //存储
    List files = new ArrayList<>();
    if (ids.length > 0) {
        for (int id : ids) {
            ComplexRelationProductDo query = new ComplexRelationProductDo();
            query.setQueryProductId(id);
            List productDos = complexRelationService.reviewHisProductInfo(query);
            if (productDos == null || productDos.size() == 0) {
                return setResultError("没有查询到项目信息");
            }
            ComplexRelationProductDo dos = productDos.get(0);
            //是否完成
            if (dos.getRp_status_() != 2) {
                return setResultError("项目评审没有完成");
            }
            //查询项目的打分规则
            List recordDetailList = complexRelationService.productScoreListById(id);

            //如果是已完成的,根据record关联专家
            List specInfoList = complexRelationService.productSpecListById(id);
            String pdfHtmlRoot = sysConfig.getTempPdfHtml() + File.separator + dos.getPi_batch_id();
            File pdfHtmlRootFile = new File(pdfHtmlRoot);
            if (!pdfHtmlRootFile.exists())
                pdfHtmlRootFile.mkdirs();
            String pdfRoot = sysConfig.getTempPdf() + File.separator + dos.getPi_batch_id();
            File pdfRootFile = new File(pdfRoot);
            if (!pdfRootFile.exists())
                pdfRootFile.mkdirs();

            File pdfHtml = null;
            String pdf = null;

            for (SpecInfo spec : specInfoList) {
                //查询专家的评论信息以及签名
                SpecInfo specReviewInfo = complexRelationService.productSpecInfoById(id, spec.getId());
                if (specReviewInfo == null) {
                    //TODO:记录SQL
                    continue;
                }
                String fileName = specReviewInfo.getSignUrl();
                if (fileName == null || fileName.length() == 0) {
                    fileName = "empty_sign.png";
                }
                File tmp = new File(sysConfig.signPath() + fileName);
                if (!tmp.exists()) {
                    fileName = "empty_sign.png";
                }
                dos.getCpt_name_();
                String title = String.format("绍兴“名士之乡”英才计划%s人才(%s)项目评审打分表", (dos.getCpt_name_().indexOf("创业") > -1 ? "创业" : "创新"), (dos.getCpt_name_().indexOf("团队") > -1 ? "团队" : "个人"));

                Context context = new Context();
                context.setVariable("name", dos.getPi_user_name());
                context.setVariable("title", title);
                context.setVariable("recordDetailList", recordDetailList);
                context.setVariable("recordDetailListSize", recordDetailList.size());
                context.setVariable("remark", specReviewInfo.getRemark());
                context.setVariable("fileName", fileName);
                context.setVariable("recordScore", specReviewInfo.getRecordScore());
                context.setVariable("date", DateFormatUtils.format(specReviewInfo.getCreateTime(), "yyyy年M月dd日"));

                pdfHtml = new File(pdfHtmlRoot + File.separator + id + "_" + specReviewInfo.getId() + ".html");
                boolean succ = templateConfig.process("pdfs/pdf_score", context, pdfHtml);

                if (succ && pdfHtml.exists()) {
                    try {
                        byte[] htmlByte = FileCopyUtils.copyToByteArray(new File(pdfHtmlRoot + File.separator + id + "_" + specReviewInfo.getId() + ".html"));
                        pdf = pdfRoot + File.separator + dos.getPi_user_name() + "_" + specReviewInfo.getUserName() + ".pdf";
                        //生成pdf文件
                        pdfConfig.generate(pdf, PageSize.A4, "", true, null, htmlByte);
                        File f = new File(pdf);
                        //存储文件地址
                        if (f.exists()) {
                            //TODO: 记录SQL
                            LOGGER.info("pdf exists:{}", f.getName());
                            //获取各个文件路径
                            files.add(pdf);
                        } else {
                            //TODO: 记录SQL
                            LOGGER.info("pdf exists:{}", f.getName());
                        }

                    } catch (Exception e) {
                        LOGGER.error("", e);
                    }
                } else {
                    //TODO:记录SQL
                    LOGGER.info("pdfHtml exists:{}", pdfHtml.getName());
                }
            }
        }
    } else {
        return setResultError();
    }
    pdfFile(resp, files);
    return setResult();
}

生成pdf文件代码

@Value("${pdf.imageRoot}")
private String imageRoot;
@Value("${pdf.fontRoot}")
private String fontRoot;
@Value("${pdf.zipRoot}")
private String zipRoot;

public String getZipRoot() {
    return zipRoot;
}

public String getImageRoot() {
    return imageRoot;
}

public String getFontRoot() {
    return fontRoot;
}

public void setImageRoot(String imageRoot) {
    imageRoot = imageRoot;
}

public void setFontRoot(String fontRoot) {
    fontRoot = fontRoot;
}

public void generate(String targetPdf, Rectangle pageSize, String header, boolean isFooter, File watermark, byte[] htmlBytes)
        throws Exception {

    final String charsetName = "UTF-8";
    Document document = new Document(pageSize);

    OutputStream out = new FileOutputStream(targetPdf);
    /**
     * 设置边距
     */
    // document.setMargins(30, 30, 30, 30);
    PdfWriter writer = PdfWriter.getInstance(document, out);
    /**
     * 添加页码
     */
    //PdfBuilder builder = new PdfBuilder(header, 10, pageSize, watermark, isFooter);
    PdfBuilder builder = new PdfBuilder(header, 10, pageSize, watermark, isFooter, fontRoot);
    writer.setPageEvent(builder);

    document.open();

    /**
     * html内容解析
     */
    HtmlPipelineContext htmlContext =
            new HtmlPipelineContext(new CssAppliersImpl(pdfXMLWorkerFontProvider)) {
                @Override
                public HtmlPipelineContext clone() throws CloneNotSupportedException {
                    HtmlPipelineContext context = super.clone();
                    ImageProvider imageProvider = this.getImageProvider();
                    context.setImageProvider(imageProvider);
                    return context;
                }
            };

    /**
     * 图片解析
     */
    htmlContext.setImageProvider(pdfAbstractImageProvider);
    htmlContext.setAcceptUnknown(true).autoBookmark(true).setTagFactory(Tags.getHtmlTagProcessorFactory());

    /**
     * css解析
     */
    CSSResolver cssResolver = XMLWorkerHelper.getInstance().getDefaultCssResolver(true);
    cssResolver.setFileRetrieve(new FileRetrieve() {
        @Override
        public void processFromStream(InputStream in, ReadingProcessor processor) throws IOException {
            try (InputStreamReader reader = new InputStreamReader(in, charsetName)) {
                int i = -1;
                while (-1 != (i = reader.read())) {
                    processor.process(i);
                }
            } catch (Exception e) {
                logger.error("", e);
            }
        }

        /**
         * 解析href
         */
        @Override
        public void processFromHref(String href, ReadingProcessor processor) throws IOException {
            InputStream is = new ByteArrayInputStream(href.getBytes());
            try {
                InputStreamReader reader = new InputStreamReader(is, charsetName);
                int i = -1;
                while (-1 != (i = reader.read())) {
                    processor.process(i);
                }
            } catch (Exception e) {
                logger.error("", e);
            }

        }
    });

    HtmlPipeline htmlPipeline = new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, writer));
    Pipeline pipeline = new CssResolverPipeline(cssResolver, htmlPipeline);
    XMLWorker worker = null;
    worker = new XMLWorker(pipeline, true);
    XMLParser parser = new XMLParser(true, worker, Charset.forName(charsetName));
    try (InputStream inputStream = new ByteArrayInputStream(htmlBytes)) {
        parser.parse(inputStream, Charset.forName(charsetName));
    }
    document.close();
}

}
实现下载zip功能代码

private void pdfFile(HttpServletResponse resp, List files) {
    try {
        //创建压缩文路径地址
        String zipBasePath = pdfConfig.getZipRoot();
        //创建zip名称
        String zipName = "项目评审打分表" + getDateString() + ".zip";
        String zipFilePath = zipBasePath + File.separator + zipName;
        //压缩文件
        File zip = new File(zipFilePath);
        if (!zip.exists()) {
            zip.createNewFile();
        }
        //创建zip文件输出流
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zip));
        this.zipFile(zipBasePath, zipName, zipFilePath, files, zos);
        zos.close();
        //设置下载的压缩文件名称
        resp.setHeader("Content-disposition", "attachment;filename=" + zipName);
        //将打包后的文件写到客户端,输出的方法同上,使用缓冲流输出
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(zipFilePath));
        byte[] buff = new byte[bis.available()];
        bis.read(buff);
        bis.close();
        // 清空response
        resp.reset();
        // 设置response的Header
        resp.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(zipName, "UTF-8"));
        OutputStream out = resp.getOutputStream();
        //输出数据文件
        out.write(buff);
        //释放缓存
        out.flush();
        //关闭输出流
        out.close();

    } catch (Exception e) {
        LOGGER.error("", e);
    }
}

zip压缩文件实现代码

/**
 * 压缩文件
 *
 * @param zipBasePath 临时压缩文件基础路径
 * @param zipName     临时压缩文件名称
 * @param zipFilePath 临时压缩文件完整路径
 * @param filePaths   需要压缩的文件路径集合
 * @throws IOException
 */
private String zipFile(String zipBasePath, String zipName, String zipFilePath, List filePaths, ZipOutputStream zos) throws IOException {

    //循环读取文件路径集合,获取每一个文件的路径
    for (String filePath : filePaths) {
        //根据文件路径创建文件
        File inputFile = new File(filePath);
        //判断文件是否存在
        if (inputFile.exists()) {
            //判断是否属于文件,还是文件夹
            if (inputFile.isFile()) {
                //创建输入流读取文件
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream(inputFile));
                //将文件写入zip内,即将文件进行打包
                zos.putNextEntry(new ZipEntry(inputFile.getName()));
                //写入文件的方法,同上
                int size = 0;
                //设置读取数据缓存大小
                byte[] buffer = new byte[1024];
                while ((size = bis.read(buffer)) > 0) {
				// while ((size = bis.read(buffer))!= -1) {
                    zos.write(buffer, 0, size);
                }
                //关闭输入输出流
                zos.closeEntry();
                bis.close();
            } else {
                //如果是文件夹,则使用穷举的方法获取文件,写入zip
                try {
                    File[] files = inputFile.listFiles();
                    List filePathsTem = new ArrayList();
                    for (File fileTem : files) {
                        filePathsTem.add(fileTem.toString());
                    }
                    return zipFile(zipBasePath, zipName, zipFilePath, filePathsTem, zos);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
    return null;
}

用uuid生成唯一zip包名

/**
 * 生成zip名
 *
 * @return
 */
private String getDateString() {
    String dateString = UUID.randomUUID().toString();

    return dateString;
}

你可能感兴趣的:(java,springboot,java)