Archive for Juli 30th, 2009

Surprisingly I never really had to use any Input- Outputstreaming with Java since a few days ago. … Well, ok, some FileInputStreams or some InputStreams from resources; but that’s not what I mean.

Playing around with iText I had to manipulate a few PDF-Templates as explained earlier under PDF-Templates for iText and then merge them together into one PDF-file. The problem was, that iText needs to have an OutputStream to put the content to. At first I was on the wrong track trying to use PipedStreams … but those only work between different threads, not in the same so I had to throw that idea away.

I came accross the ByteArrayOutput- and ByteArrayInputStreams. You just go ahead and create a ByteArrayOutputStream and give that one to the iText PdfReader. If you need the Stream again, you can now use it, manipulate it a 2nd time and in the end pass it to the user as a File (FileOutputStream) or through the browser using the response.getOutputStream().

The code looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
 
PdfCopyFields copy = new PdfCopyFields(outputStream);
 
// walk through the readers and add several PDF-files to one document
for (PdfReader pdfReader : readers) {
  copy.addDocument(pdfReader);
}
copy.close();
 
// save result of this reader in memory
PdfReader read = new PdfReader(new ByteArrayInputStream(outputStream.toByteArray()));
 
// stamper to have access to AcroFields
PdfStamper stamp = new PdfStamper(read, finalOutputStream);
 
// fill pdf form fields with given stamper
fillPdfFormFields(stamp);
stamp.close();
 
outputStream.flush();
outputStream.close();
finalOutputStream.close();