3

我想创建一个充满 PDF-As 的 ZipOutputStream。我正在使用 iText(版本 5.5.7)。对于 1000 多个 pdf 条目,我在 doc.close() 上收到 OutOfMemory-exception 并且找不到泄漏。

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(baos));
zos.setEncoding("Cp850");
for (MyObject o : objects) {
try {
    String pdfFilename = o.getName() + ".pdf";
    zos.putNextEntry(new ZipEntry(pdfFilename));
    pdfBuilder.buildPdfADocument(zos);
    zos.closeEntry();
} ...

PdfBuilder

public void buildPdfADocument(org.apache.tools.zip.ZipOutputStream zos){
   Document doc = new Document(PageSize.A4);
   PdfAWriter writer = PdfAWriter.getInstance(doc, zos, PdfAConformanceLevel.PDF_A_1B);
   writer.setCloseStream(false); // to not close my zos
   writer.setViewerPreferences(PdfWriter.ALLOW_PRINTING | PdfWriter.PageLayoutSinglePage);
   writer.createXmpMetadata();
   doc.open();
   // adding Element's to doc
   // with flushContent() on PdfPTables
   InputStream sRGBprofile = servletContext.getResourceAsStream("/WEB-INF/conf/AdobeRGB1998.icc");
   ICC_Profile icc = ICC_Profile.getInstance(sRGBprofile);
   writer.setOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);
   //try to close/flush everything possible
   doc.close();
   writer.setXmpMetadata(null);
   writer.flush();
   writer.close();
   if(sRGBprofile != null){
     sRGBprofile.close();
   }
}

有什么建议我该如何解决?我是不是忘记了什么?我已经尝试过使用 java ZipOutputStream 但它有任何区别。


谢谢你的回答!我了解 ByteOutputStream 的问题,但我不确定在我的情况下最好的方法是什么。这是一个 Web 应用程序,我需要以某种方式将 zip 打包到数据库 blob 中。

我现在正在做的是使用 iText 将 PDF 直接创建到 ZipOutputStream 中,并将相应 ByteArrayOutputSteam 的字节数组保存到 blob。我看到的选项是:

将我的数据拆分为 500 个对象包,将前 500 个 PDF 保存到数据库中,然后打开 zip 并添加接下来的 500 个,依此类推……但我认为这会造成与现在相同的情况,即太大流在内存中打开。

尝试将 PDF 保存在服务器上(不确定是否有足够的空间),创建临时 zip 文件,然后将字节提交到 blob...

有什么建议/想法吗?

4

2 回答 2

4

这是因为您ZipOutputStream由 ByteArrayOutputStream 支持,因此即使关闭条目也会将完整的 ZIP 内容保留在内存中。

于 2015-10-01T16:38:43.657 回答
0

您需要使用另一种方法来处理这个数量的参数(1000 多个文件)。

您正在将所有 PDF 文件加载到您的示例的内存中,您需要在文档块中执行此操作,以最大限度地减少这种“内存加载”的影响。

另一种方法是在文件系统上序列化您的 PDF,然后创建您的 zip 文件。

于 2015-10-01T16:32:39.950 回答