首页 > 解决方案 > 如何合并 pdf 文件并将其下载为 zip 文件

问题描述

我希望你能帮助我。我有很多 pdf 文件,它们是 byte[] 格式的,因为我是从数据库中获取它们的。我需要合并它们,但生成的文件不能超过 1000 张,所以如果我的 pdf 文件的总数超过 1000 张,我将不得不构建许多限制在这种尺寸范围内的 pdf 文件。

我刚刚完成,我构建了一个返回 List<ByteArrayInputStream[]> 的算法

现在,它是我的问题。如何获取每个文件,将它们合并并放入一个 zip 文件以供下载?

我试过这个...

public static void openZipFile(HttpServletResponse response, String fileName, List<ByteArrayInputStream[]> conteudosZIP)
        throws Exception {

    response.setContentType("application/zip");
    response.setHeader("Content-Disposition", "attachment;filename=" + fileName.replaceAll("\u0020", "_").replaceAll(",", "_") + ".zip");
    
    ServletOutputStream out = response.getOutputStream();
    ZipOutputStream zout = new ZipOutputStream(out);
    Integer cont = 1;
    
    for(ByteArrayInputStream[] conteudoArray : conteudosZIP ) {
        PDDocument result = new PDDocument();
        PDFMergerUtility ut = new PDFMergerUtility();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        for(ByteArrayInputStream conteudo : conteudoArray) {
            ut.appendDocument(result, PDDocument.load(conteudo));
        }
        result.save(byteArrayOutputStream);
        ZipEntry ze = new ZipEntry(fileName + '_' + cont++ + ".pdf");
        zout.putNextEntry(ze);
        zout.write(byteArrayOutputStream.toByteArray());
        zout.closeEntry();          
    }       
}

标签: javapdfzippdfbox

解决方案


目前尚不清楚其中的哪一部分不适合您。当你运行它时会发生什么?

您可能想zout.close()在最后添加一个。


推荐阅读