繁体   English   中英

使用 pdfBox 合并文档时出现堆空间问题

[英]Heap space issue while merging the document using pdfBox

当我尝试合并一个 44k 页面 pdf 时出现 java.lang.OutOfMemory 错误。我正在从我的数据库中分块获取所有 44k 页面并尝试与我的主文档合并。 它在 9.5k 页之前都可以正常处理,然后开始抛出堆空间错误。

public void getDocumentAsPdf(String docid) {

       

        PDDocument pdDocument = new PDDocument();

        try {

            //fetching total count from DB
            Long totalPages = countByDocument(docid);
            Integer batchSize = 400;
            Integer skip=0;
            Long totalBatches = totalPages/batchSize;
            Long remainingPages = totalPages%batchSize;

            for (int i = 1; i <= totalBatches; i++) {
                
                log.info("Batch : {}", i );
                
                //fetching pages of given document in ascending order from database
                List<Page> documentPages = fetchPagesByDocument(document,batchSize,
                        skip);
                pdDocument = mergePagesToDocument(pdDocument,documentPages);
                skip+=batchSize;
            }

            if(remainingPages>0)
            {
                //fetching remaining pages of given document in ascending order from database
                List<Page> documentPages = fetchPagesByDocument(document,batchSize,skip);
                pdDocument = mergePagesToDocument(pdDocument,documentPages);
            }

           
        }
        catch (Exception e)
        {
         
            throw new InternalErrorException("500","Exception occurred while merging! ");
        }

        
    }

合并pdf逻辑

public PDDocument mergePagesToDocument(PDDocument pdDocument,List<Page> documentPages)  {

        try {
            PDFMergerUtility pdfMergerUtility = new PDFMergerUtility();
            pdfMergerUtility.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
            for (Page page : documentPages) {
                byte[] decodedPage = java.util.Base64.getDecoder().decode(page.getPageData());
                PDDocument addPage = PDDocument.load(decodedPage);
                pdfMergerUtility.appendDocument(pdDocument, addPage);
                addPage.close();
            }
            return pdDocument;
        }catch (Exception e)
        {
      
            throw new InternalErrorException("500",e.getMessage());
        }

    }

我认为我这边有一些 memory 泄漏导致了给定的问题。 任何建议或更好的方法都会有所帮助。 提前致谢!

这不完全是 memory 泄漏,但您正试图将整个 44k 页 PDF 存储在 pdDocument 变量中。 它可能比您的堆大小大。 您可以使用 VM 选项-Xmx增加它( 在此处阅读更多信息)。

或者,您可以更改您的方法,不立即将 44k 页加载到 memory。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM