1

I have a List with multiple PDFs , and I want to merge all of them into a single PdfDocument (im using iText) , and then transform this PdfDocument into a ByteArrayOutputStream (OR a byte[]).

public byte[] mergePdfDocumentsIntoAPdfDocument (List<PdfDocument> pdfDocuments){

 final ByteArrayOutputStream mergedPdfStream = new ByteArrayOutputStream();
    final PdfDocument mergedPdfDocument = new PdfDocument(new PdfWriter(mergedPdfStream));


//I dont know how can I continue this

What should I do in order to achieve this?

mkl
  • 90,588
  • 15
  • 125
  • 265
Nexussim Lements
  • 535
  • 1
  • 15
  • 47

1 Answers1

3
public byte[] mergePdfDocumentsIntoAPdfDocument(List<PdfDocument> pdfDocuments){
    ByteArrayOutputStream mergedPdfStream = new ByteArrayOutputStream();
    PdfDocument resultDoc = new PdfDocument(new PdfWriter(mergedPdfStream));

    for (PdfDocument doc : pdfDocuments) {
        int n = doc.getNumberOfPages();
        for (int i = 1; i <= n; i++) {
            PdfPage page = doc.getPage(i).copyTo(resultDoc);
            resultDoc.addPage(page);
        }
    }

    resultDoc.close();
    return mergedPdfStream.toByteArray();
}
devgianlu
  • 1,547
  • 13
  • 25