我正在尝试通过 iText 合并 1000 个 PDF 文件。我不确定内存泄漏发生在哪里。下面是示例代码。请注意,一旦合并到父文件,我就会删除子 pdf 文件。请指出下面代码中的错误,或者是否有更好的方法可以在没有内存概念的情况下做到这一点。这个过程是通过servlet(不是独立程序)完成的

FileInputStream local_fis = null;
BufferedInputStream local_bis = null;
File localFileObj = null;
for(int taIdx=0;taIdx<totalSize;taIdx++){
    frObj = (Form3AReportObject)reportRows.get(taIdx);
    localfilename = companyId + "_" +  frObj.empNumber + ".pdf";

    local_fis = new FileInputStream(localfilename);
    local_bis = new BufferedInputStream(local_fis); 
    pdfReader = new PdfReader(local_bis);

    cb = pdfWriter.getDirectContent(); 
    document.newPage();
    page = pdfWriter.getImportedPage(pdfReader, 1);
    cb.addTemplate(page, 0, 0);
    local_bis.close();
    local_fis.close();

    localFileObj = new File(localfilename);
    localFileObj.delete();
}
document.close();
有帮助吗?

解决方案

您可能想尝试类似如下(异常处理,文件关闭并且为了清楚删除删除):

for(int taIdx = 0; taIdx < totalSize; taIdx++) {
    Form3AReportObject frObj = (Form3AReportObject)reportRows.get(taIdx);

    localfilename = companyId + "_" +  frObj.empNumber + ".pdf";

    FileInputStream local_fis = new FileInputStream(localfilename);

    pdfWriter.freeReader(new PdfReader(local_fis));

    pdfWriter.flush();
}

pdfWriter.close();

其他提示

谁说有内存泄漏?合并文档需要适应的全部记忆,有没有办法解决它,它很可能大于64MB的内存的默认堆大小的(而不是光盘)。

我没有看到你的代码中的问题,但如果你想诊断它的细节,的使用的VisualVM的堆探查(随JDK自爪哇6更新10左右)。

如果你不使用的InputStream?如果可以,请尝试使用刚刚路径你“新PDFReader文件(‘/ somedirectory /文件’)。

此使读者作用在磁盘上。

在上面的代码试图创建循环内的PdfContentByte对象(cb)。外移动它可能会解决这个问题。我用类似的代码在我的应用缝合到一个PDF一起13K个体的PDF没有麻烦。

public class PdfUtils {
     public static void concatFiles(File file1, File file2, File fileOutput) throws Exception {
          List<File> islist =  new ArrayList<File>();
          islist.add(file1);
          islist.add(file2);

          concatFiles(islist, fileOutput);
         }

         public static void concatFiles(List<File> filelist, File fileOutput) throws Exception {
          if (filelist.size() > 0) {
                 PdfReader reader = new PdfReader(new FileInputStream( filelist.get(0)) );
                 Document document = new Document(reader.getPageSizeWithRotation(1));

           PdfCopy cp = new PdfCopy(document,  new FileOutputStream( fileOutput ));

           document.open();


           for (File file : filelist ) {

                PdfReader r = new PdfReader( new FileInputStream( file));
                for (int k = 1; k <= r.getNumberOfPages(); ++k) {
                    cp.addPage(cp.getImportedPage(r, k));
                }
                cp.freeReader(r);

           }
           cp.close();
           document.close();
          } else{             
           throw new Exception("La lista dei pdf da concatenare è vuota");        
          }               
         }
   }

相反合并1000个PDF的,尝试创建它们的拉链。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top