iText - Read pdfs in a loop and merge one by one

2019-08-28 05:58发布

问题:

I have a loop where I read a pdf file every time. And I want to add these pdf files into another final pdf. Basically merging all pdfs into one new pdf file.

I tried following way :

I tried to concatenate byteArrays inside the loop like

ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
for (............){
  outputStream.write(myInfo.getByteArray());
}

pdfreader = new PdfReader(outputStream.toByteArray());
FileOutputStream fileout = new FileOutputStream(file);

PdfStamper pdfStamper = new PdfStamper(pdfreader, fileout);

pdfStamper.close();
pdfreader.close();

The problem the final pdf does not have all the pdfs. Instead it has only one pdf.

And I am not sure if this is the right way to do it. Or is there any other to merge pdfs one by one ?

回答1:

Have a look at the documentation for PdfMerger: itextsupport.com/apidocs/iText7/7.0.3/com/itextpdf/kernel/utils/PdfMerger.html

I can prepare an example later if needed.