2

I'm using Apache PDFBox version 2.0.16 to add paging to an existing PDF file. My method is working great, the generated PDF is fine. However, when I open the file with Adobe Acrobat Reader, if I try to close the file, it prompts an alert asking me if I want to save the file even though I haven't edited anything, and the file is not editable at first. I can't manage to understand what's happening, and how to prevent it from prompting saving

My code is the following :

private void paging(ByteArrayOutputStream os) throws IOException {
    PDDocument doc = PDDocument.load(new ByteArrayInputStream(os.toByteArray()));
    PDFont font = getFont(doc);
    PDPageTree pages = doc.getDocumentCatalog().getPages();
    for (int i = 0; i < pages.getCount(); i++) {
        PDPage page = pages.get(i);
        PDPageContentStream contentStream = new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, true, false);
        contentStream.beginText();
        contentStream.setFont(font, FONT_SIZE);
        contentStream.setNonStrokingColor(Color.BLACK);
        contentStream.newLineAtOffset(page.getCropBox().getWidth() - 40,  15);
        contentStream.showText((i + 1) + " / " + pages.getCount());
        contentStream.endText();
        contentStream.close();
    }

    doc.save(os);
    doc.close();
}
Wàle
  • 23
  • 5
  • See my answer in the pdfbox users mailing list from yesterday. Did you try it? I think I also answered a similar question here on SO, but can't find it... Short version: call `os.reset()` before saving. – Tilman Hausherr May 14 '20 at 10:06
  • It worked, thank you very much ! Sorry I had not seen your email, looks like my email service marked it as spam. – Wàle May 14 '20 at 13:59
  • In the meantime, I found my answer, although the question was very different, so I'll write one here anyway. https://stackoverflow.com/questions/60742908/ – Tilman Hausherr May 14 '20 at 15:17

1 Answers1

0

reset 'os' before saving, so that your ByteArrayOutputStream gets cleared and positioned at the beginning.

os.reset();

Also call load() directly with the byte array:

PDDocument.load(os.toByteArray());

and update to the current version, which is 2.0.19 at this time.

Tilman Hausherr
  • 17,731
  • 7
  • 58
  • 97