2

当我尝试使用下面的代码打印预览时,它会在之前打印的项目上打印项目。当我将if块放在for循环之外时,它开始生成一个无限页面。

private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{    
    SolidBrush brush = new SolidBrush(Color.Black);
    Font font = new Font("Courier New", 12);

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

    for (int i = 0; i < 100; i++)
    {
        e.Graphics.DrawString("Line: " + i, font, brush, startX, startY);
        startY += font.Height;
        lineperpage++;

        if (lineperpage > 50)
        {
            e.HasMorePages = true;
            startY = 30;
            lineperpage = 0;
            startX = 300;
        }
        else
        {
            e.HasMorePages = false;
        }
    } 
}
4

1 回答 1

0

您必须将要打印的数据与单页的实际绘图分开。您不能以相同的方法使用它们。将 HasMorePages 设置为 true 只会向 PrintMangager 发出PrintPage再次引发事件的信号。

i在您的情况下,您的变量看起来像是数据。您需要在 PrintPage 事件之外跟踪其进度。

int i = 0;  // keep track of data in an instance variable 

// this event is re-entrant. It will be called as long as HasMorePages = true;
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{    
    SolidBrush brush = new SolidBrush(Color.Black);
    Font font = new Font("Courier New", 12);

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

    // removed
    //for (int i = 0; i < 100; i++)
    // print a page as long as their is space left AND data available
    while (lineperpage < 50 && i < 100)
    {
        e.Graphics.DrawString("Line: " + i, font, brush, startX, startY);
        startY += font.Height;
        lineperpage++;

        i++;  // next dataitem
    }

    e.HasMorePages = i < 100; // keep printing as long as there is date 
}
于 2016-07-03T12:08:41.583 回答