private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
try
{
Graphics graphic = e.Graphics;
SolidBrush brush = new SolidBrush(Color.Black);
Font font = new Font("Courier New", 12);
float pageWidth = e.PageSettings.PrintableArea.Width;
float pageHeight = e.PageSettings.PrintableArea.Height;
float fontHeight = font.GetHeight();
int startX = 40;
int startY = 30;
int offsetY = 40;
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;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
答案 0 :(得分:2)
每当您设置e.HasMorePages = true
时,它都会再次触发printDocument1_PrintPage()
事件处理程序。你需要为i保留一个类变量,这样每次打印下一页时它都不会重新开始。不要在事件处理程序中本地声明它。
private class MyPrinter
{
private int i = 0;
private void Print()
{
i = 0;
printDocument1.Print();
}
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
.....
.....
.....
while (i < 100)
{
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;
}
i = i + 1;
}
}
}