Click here to Skip to main content
15,511,250 members
Articles / Programming Languages / C#
Article
Posted 15 Jun 2007

Stats

27.4K views
855 downloads
14 bookmarked

Multi Page Multi Column Text Printing

Rate me:
Please Sign up or sign in to vote.
3.67/5 (2 votes)
15 Jun 2007CPOL1 min read
How to do a multi page multi column text printing
Screenshot - PrintApp.jpg

Screenshot - PrintPreview.jpg

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:

C#
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) // Below the printable area
    {
        return;
    }

    if (y > m_fPageHeight + m_fVerticalMargin) // Above the printable area
    {
        if (!m_bMorePages) // It is possible that there is no split
        {
            m_bMorePages = true;
            return;
        }
    }

    SizeF pSize = g.MeasureString(s, font);
    if (y + pSize.Height > m_fPageHeight + m_fVerticalMargin) 
    // This text is split between two pages - everything needs to be moved down;
    {
        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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --