You use iText commands in the wrong order:
- Your
DataStore
constructor creates a newDocument
and calls itsopen
method (which is too early as there is no writer yet). - Some time later, in the first
saveData
call, you callcreateFile
which creates thePdfWriter
. - In all
saveData
callsaddText
is called which forSamples > 0
opens the document again each time (which is ok at the first time but shall not be done multiple times). - Eventually, in the
saveData
call withSamples == 0
you close the document.
Thus, in essence you do this:
document = new Document();
document.open();
[...]
PdfWriter.getInstance(document, file);
[...]
[for `Samples` times]
document.open();
[add some paragraphs]
[add an image]
[end for]
document.close();
Compare this to how it should be done:
// step 1
Document document = new Document();
// step 2
PdfWriter.getInstance(document, new FileOutputStream(filename));
// step 3
document.open();
// step 4
[add content to the PDF]
// step 5
document.close();
(copied from the HelloWorld.java sample from iText in Action — 2nd Edition)
Only for Samples == 1
you have it about right (the superfluous document.open()
in the constructor being ignored as there is no writer yet); for larger values of Samples,
though, you open the document multiple times with a writer present which will likely append a PDF start over and over again to the output stream.
Quite likely you can fix the issue by removing all your current document.open()
calls (including the if(Samples > 0)
in addText()
) and add one in createFile()
right after PdfWriter.getInstance(document, file).