Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using iText 2.1.7 to merge large PDFs

Tags:

java

pdf

itext

I am using an older version of iText (2.1.7) to merge PDFs. Because that is the last version under the MPL available to me. I cannot change this.

Anyways. I am trying to merge multiple PDFs. Everything seems to work ok, but when I go over about 1500 pages, then the generated PDF fails to open (behaves as if it is corrupted)

This is how I am doing it:

private byte[] mergePDFs(List<byte[]> pdfBytesList) throws DocumentException, IOException {
    Document document = new Document();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    PdfCopy copy = new PdfCopy(document, outputStream);
    document.open();

    for (byte[] pdfByteArray : pdfBytesList) {
        ByteArrayInputStream readerStream = new ByteArrayInputStream(pdfByteArray);
        PdfReader reader = new PdfReader(readerStream);

        for (int i = 0; i < reader.getNumberOfPages(); ) {
            copy.addPage(copy.getImportedPage(reader, ++i));
        }

        copy.freeReader(reader);
        reader.close();
    }

    document.close();

    return outputStream.toByteArray();
}

Is this the correct approach? Is there anything about this that would hint at breaking when going over a certain amount of pages? There are no exceptions thrown or anything.

like image 566
Seephor Avatar asked Nov 07 '22 05:11

Seephor


1 Answers

For anyone curious, the issue had nothing to do with iText and instead was the code responsible for returning the response from iText.

like image 171
Seephor Avatar answered Nov 29 '22 12:11

Seephor