Introduction
Problem – there are many examples of how to print multi page text to the printer. Unfortunately none that I found worked for me. I need to print a two column multi page custom report, when I do not know ahead what I will be printing. Good news – I do not have to deal with the case when width of the printed object is larger than page width.
I am not very happy with the solution I found and will greatly appreciate anyone pointing out a better solution for me. On the other hand, if anyone has to deal with a similar problem, this works.
Using the Code
I created two arrays of strings with random font size and attributes.
The Reset button resets those two columns so that a lot of random testing can be done.
The general idea behind the logic is that the code keeps track of the number of pages. The current page height is the visible area of the printer page minus 2 vertical margins. The vertical offset is (number of pages) * (visible area).
The complexity starts when you have a string
that is 'nishta hin nishta her' – split in the middle between two pages. I added the offset that will move everything "down".
The main logic is in the DrawString
method:
private void DrawString(Graphics g, string s, Font font, Brush brush, float x, float y)
{
y += m_fVerticalMargin + m_fPrevPageSmallTopOffset - m_fTopOffset;
if (y < m_fVerticalMargin)
{
return;
}
if (y > m_fPageHeight + m_fVerticalMargin)
{
if (!m_bMorePages)
{
m_bMorePages = true;
return;
}
}
SizeF pSize = g.MeasureString(s, font);
if (y + pSize.Height > m_fPageHeight + m_fVerticalMargin)
{
m_fThisPageSmallTopOffset = Math.Max(
m_fThisPageSmallTopOffset,
m_fPageHeight + m_fVerticalMargin - y);
m_bMorePages = true;
return;
}
g.DrawString(s, font, Brushes.Black, x, y);
}
History
- 15th June, 2007: Initial post
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.