当我尝试使用下面的代码打印预览时,它会在先前打印的项目上打印项目。当我将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;
}
}
}
答案 0 :(得分: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
}