Zach said:
[...]
What I do not understand is the possibility of printing a blanc page.
Doesn't line = streamToPrint.ReadLine() = null stop that form happening?
If the last line of the file winds up being printed as the very last line
possible on a page, then in this statement:
while (count < linesPerPage && ((line = streamToPrint.ReadLine()) !=
null))
The second half of the condition will never execute, because count <
linesPerPage is true. Then you'll set "ev.HasMorePages" to true, because
"line" is not null. Then the next time your PrintPage event handler is
called, it will finally call ReadLine() only to find that there is no more
data. But by that time, the page is already being printed. So you'll get
a blank page.
You can't fix the problem simply by using the non-short-circuiting &
operator instead of &&, because then you'll read a line at the end of each
page that will never get printed, because the string returned by
ReadLine() will be lost when the method returns.
To fix the problem, you should change the code so that the "line" variable
is not a local, but instead is in an instance of an object (either the
form itself along with the other stuff, or preferably in a
printing-specific object for that purpose along with the other
print-related data). Then you can always attempt to read the next line,
but only drawing the string if there's room, moving on to the next page
otherwise.
If I am missing the cause of blanc pages being printed, wouldn't a way
out be to count the lines before I go in and check the counter value?
You can read the file twice, counting lines first, and then reading it
again. Or you can read the file into an array of strings, one string per
line, before you start to print anything. Or any number of other
alternatives. But since it's possible to solve the problem storing just
one string between pages, it seems to me that's the most efficient
approach.
Pete