0

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 ByteArrayOutputStreams. This solves problem!

Community
  • 1
  • 1
PattMauler
  • 400
  • 4
  • 22
  • Are you sure that reusing the same BAOS for stamping and combining PDFs is a good idea? – hoaz Dec 07 '12 at 18:09
  • @hoaz Actually, no, I'm not sure at all. It's worked fine so far. What could be the potential issue there-- or is that my problem? – PattMauler Dec 07 '12 at 19:51
  • 2
    I would create two BAOS instances, one for stamper, another for stitching – hoaz Dec 07 '12 at 20:29
  • If after applying @hoaz ' suggestion of using separate byte array output streams (which I do support) you still get a faulty PDF, please supply a sample PDF for inspection. – mkl Dec 07 '12 at 22:54
  • I just tried two ByteArrayOutputStreams. I will edit the question above to illustrate what I did. – PattMauler Dec 07 '12 at 23:03

1 Answers1

1

I would create two BAOS instances, one for stamper, another for stitching.

Your problem is that you write single BAOS to itself after stamping and this mixes content.

hoaz
  • 9,883
  • 4
  • 42
  • 53