I've seen similar questions here on SO regarding this problem, though mostly in the context of C#/iTextSharp.
I have the following Java method:
public byte[] prependCoversheet(byte[] pdfBytes)
{
InputStream pdfTemplate = getClass().getResourceAsStream("coversheet.pdf");
PdfReader reader = new PdfReader(pdfTemplate);
ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
PdfCopyFields copy = new PdfCopyFields(baos1);
PdfStamper stamper = new PdfStamper(reader, baos2);
AcroFields coversheet = stamper.getAcroFields();
/* Set all the field values here, etc. */
coversheet.setField("fieldName", "Lorem ipsum dolor sit amet.");
stamper.setFormFlattening(true);
stamper.close();
copy.addDocument(new PdfReader(baos2.toByteArray()));
copy.addDocument(new PdfReader(pdfBytes));
copy.close();
baos.flush();
return baos1.toByteArray();
}
The byte[]
that is returned is perfectly fine, and opens properly in Adobe Reader (unlike a similar, but probably unrelated earlier question of mine). The problem is that when the PDF is closed, Reader throws a confirmation dialog:
"Do you want to save changes to 'someFilename.pdf' before closing?"
Obviously, there are no changes to save. Other threads on SO have implicated extraneous, unused bytes at the tail of a initial buffer amount as the culprit. It's not clear to me if that pattern applies in this situation, although if I stop my IDE in Debug mode, and examine the byte[]
just before the return, there are a significant number of consecutive bytes with zeroes (0).
In this situation, though, I don't know how to determine what the "correct" size of the byte array should be.
UPDATE: Code example, above, now reflects a suggestion by hoaz in the comments to use two ByteArrayOutputStream
s. This solves problem!