VKP
VKP

Reputation: 658

OutofMemory Java Heap Space When merging PDF using itext

I am trying to merge around 15 pdfs into a single PDF. It's working most of the time but sometimes getting OutofMemory Java Heap Space error. I want to avoid temp file creation. Below is my code .

public static byte[] mergePdf(List < InputStream > inputStreams) {
    Document document = new Document();
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    PdfCopy copy = new PdfSmartCopy(document, byteArrayOutputStream);
    document.open();
    for (InputStream inputStream: inputStreams) {
        PdfReader pdfReader = new PdfReader(inputStream);
        copy.addDocument(pdfReader);
        copy.freeReader(pdfReader);
        pdfReader.close();
    }
    document.close();
    return byteArrayOutputStream.toByteArray();
}

Upvotes: 0

Views: 651

Answers (1)

Krzysztof Cichocki
Krzysztof Cichocki

Reputation: 6414

If you send it somwhere to OutputStream (eg. thru http - which seems to be true as you don't want to store it on disk) then instead of using intermediate ByteArrayOutpuStream (which is the RAM hog) - send it to the OutputStream directly - pass the OutputStream to the method creating the pdf, in this way you'll avoid holding it in memory at all.

Upvotes: 1

Related Questions