Merge document with PDFMergerUtility in pdfbox 2.00

senthil kumar picture senthil kumar · Mar 10, 2016 · Viewed 13.5k times · Source

Pdfbox Merge Document with 1.8.xx as like mergePdf.mergeDocuments() it working fine .now pdfbox version 2.0.0 contain some argument like org.apache.pdfbox.multipdf.PDFMergerUtility.mergeDocuments(MemoryUsageSetting arg0) what is MemoryUsageSetting how to use with mergeDocuments.I read as like Merge the list of source documents, saving the result in the destination file. kindly provide some code equivalent to version 2.0.0

public void combine()
    {
        try
        {
        PDFMergerUtility mergePdf = new PDFMergerUtility();
        String folder ="pdf";
        File _folder = new File(folder);
        File[] filesInFolder;
        filesInFolder = _folder.listFiles();
        for (File string : filesInFolder)
        {
            mergePdf.addSource(string);    
        }
    mergePdf.setDestinationFileName("Combined.pdf");
    mergePdf.mergeDocuments();
        }
        catch(Exception e)
        {

        }  
    }

Answer

Tilman Hausherr picture Tilman Hausherr · Mar 10, 2016

According to the javadoc, MemoryUsageSetting controls how memory/temporary files are used for buffering.

The two easiest usages are:

MemoryUsageSetting.setupMainMemoryOnly()

this sets buffering memory usage to only use main-memory (no temporary file) which is not restricted in size.

MemoryUsageSetting.setupTempFileOnly()

this sets buffering memory usage to only use temporary file(s) (no main-memory) which is not restricted in size.

So for you, the call would be

mergePdf.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());

or

mergePdf.mergeDocuments(MemoryUsageSetting.setupTempFileOnly());

Or just pass null. This will default to main memory only. That's also what the javadoc tells: memUsageSetting defines how memory is used for buffering PDF streams; in case of null unrestricted main memory is used.