簡體   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