Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apache PDFBox - merge documents without loading objects to memory

I'm trying to merge PDF documents using PDFMergerUtility. I was thinking about mergeDocuments() method but when I looked into the source code, the files are loaded as in-memory PDDocuments, which I'm trying to avoid, because my application works with huge images that are exported to pdf and creating PDDocument containing these images causes OutOfMemoryError: Java heap space.

Is there any way to merge these documents without loading the whole objects to memory, using PDFBox?

like image 490
Peter K Avatar asked Aug 15 '26 21:08

Peter K


1 Answers

The method of PDFMergerUtility that allows for merging documents, accepts a parameter that allows you to define what strategy may be used to manager memory during the merge.

There are 3 strategies: using the main memory, using temporary files and a mix of the other 2; additionally, you can tune up to what limit one strategy or the other may be used.

In your case, you should go for temporary files only - this can be done as follows [assuming the instance of your PDFMergerUtility object is called pdfMerger] :

pdfMerger.mergeDocuments(MemoryUsageSettings.setupTempFileOnly().streamcache)

(the version of Pdfbox used in this solution is 3.0.5)

like image 89
Luca Tampellini Avatar answered Aug 18 '26 10:08

Luca Tampellini



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!