Adding up ByteArrayOutputStreams
-
20-06-2021 - |
Вопрос
Im having a bunch of ByteArrayOutputstreams
onto which pdf reports are written over different parts of a particular workflow. I use IText to accomplish this. Now, at the end I would like to group all these single ByteArrayOutputstreams into a bigger ByteArrayOutputstream
so as to group all pdf reports together.
I looked at Apache Commons library but could not find anything of use.
1 way that i know of is to convert each of these ByteArrayOutputstreams
into byte[]
and then using System.arraycopy
to copy them into a bigger byte[]
. The problem with this is me having to declare the size of the result byte[]
upfront which makes it non-ideal.
Is there any other way to copy/append to/concatenate ByteArrayOutputStreams taht i may have missed ?
Решение
You can use a List<Byte[]>
for that. You can add your bytes on the go to the list.
List<Byte[]> listOfAllBytes = new ArrayList<Byte[]>;
ByteArrayOutputstreams byteArray = //...
listOfAllBytes.add(byteArray.toByteArray);
At the end, you can just get the full byte array back.
Другие советы
Write all but one of their toByteArray()
results into the remaining one.
public class Concatenate {
/** The resulting PDF file. */
public static final String RESULT
= "path/to/concatenated_pdf.pdf";
public static void main(String[] args)
throws IOException, DocumentException {
String[] files = { "1.pdf", "2.pdf" };
Document document = new Document();
PdfCopy copy = new PdfCopy(document, new FileOutputStream(RESULT));
document.open();
PdfReader reader;
int n;
// loop over the documents you want to concatenate
for (int i = 0; i < files.length; i++) {
reader = new PdfReader(files[i]);
// loop over the pages in that document
n = reader.getNumberOfPages();
for (int page = 0; page < n; ) {
copy.addPage(copy.getImportedPage(reader, ++page));
}
copy.freeReader(reader);
}
document.close();
}
}