Pelle Nilsson
Pelle Nilsson

Reputation: 19

C# printing multiple pages

This is my code, works fine when I print one page, but when I try to print something that doesn't fit onto one page it doesn't start the new page, it just accepts the offset change and starts writing over the first page.

Does anyone know what to do?

private void printDocument_PrintPage(object sender, PrintPageEventArgs e)
{
    Graphics graphic = e.Graphics;

    Font font = new Font("Courier New", 12);
    float fontHeight = font.GetHeight();
    int startX = 10;
    int startY = 10;
    int offset = 0;

    float pageWidth = e.PageSettings.PrintableArea.Width;
    float pageHeight = e.PageSettings.PrintableArea.Height;

    foreach (string line in textRichTextBox.Lines)
    {
        graphic.DrawString(line, font, new SolidBrush(Color.Black), startX, startY + offset);
        offset += (int)fontHeight;// + 5

        if (offset >= pageHeight - (int)fontHeight)
        {
            e.HasMorePages = true;
            offset = 0;
        }
    }
    e.HasMorePages = false;
}

Upvotes: 1

Views: 4529

Answers (2)

yms
yms

Reputation: 10418

You need to stop sending text to the printer once you reach the end of the page, just setting HasMorePages to true will not be enough. You can either add a break statement there, or change your loop altogether and also keep somewhere the last position you processed from your list.

Upvotes: 0

thumbmunkeys
thumbmunkeys

Reputation: 20764

You are using the API wrong, the doc says:

In the PrintPage event handler, use the Graphics property of the PrintPageEventArgs class and the document contents to calculate line length and lines per page. After each page is drawn, check to see if it is the last page, and set the HasMorePages property of the PrintPageEventArgs accordingly. The PrintPage event is raised until HasMorePages is false. Also, make sure the PrintPage event is associated with its event-handling method.

You can't set HasMorePages in a loop, only on exit of the callback. The callback will be called until you set HasMorePages to false

Upvotes: 1

Related Questions