Search code examples
c#winformsinfinite-loopprintdocument

Infinite Loop PrintDocument HasmorePages c#


I have problems to print the information in multiples pages, currently it cause a infinite Loop i have some hours surfing in the web for a solution but is not clearly.

static void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
{
    Graphics graphic = e.Graphics;
    SolidBrush brush = new SolidBrush(Color.Black);

    Font font = new Font("Courier New", 12);

    e.PageSettings.PaperSize = new PaperSize("A4", 850, 1100);

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

    float fontHeight = font.GetHeight();
    int startX = 40;
    int startY = 30;
    int offsetY = 0;

    for (int i = 0; i < 100; i++)
    {
        graphic.DrawString("Line: " + i, font, brush, startX, startY + offsetY);
        offsetY += (int)fontHeight;

        if (offsetY >= pageHeight)
        {
            e.HasMorePages = true;
            offsetY = 0;
            return;
        }
        else
        {
            e.HasMorePages = false;
        }
    }
}

any ideas? thank you


Solution

  • Ok, I think, I figured out what do you want. I think you want to print 100 lines.

    For your case you should have and instance field to keep printed lines count.

    Try something like this:

    var printedLines = 0;
    var linesToPrint = 100;
    
    ...
    
    private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
    {
        e.HasMorePages = false;
    
        ....
    
    
        while(printedLines < linesToPrint)
        {
             graphic.DrawString("Line: " + printedLines, font, brush, startX, startY + offsetY);
             offsetY += (int)fontHeight;
    
             ++printedLines;
    
             if (offsetY >= pageHeight)
             {
                  e.HasMorePages = true;
                  offsetY = 0;
                  return;
             }
        }
    }