【问题标题】:Heap space issue while merging the document using pdfBox使用 pdfBox 合并文档时出现堆空间问题
【发布时间】:2022-12-03 18:40:16
【问题描述】:

当我尝试合并一个 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());
        }

    }

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

【问题讨论】:

    标签: java spring spring-boot java-8 pdfbox


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-24
      • 1970-01-01
      • 1970-01-01
      • 2015-08-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多