如何从WinForms打印多个页面?

虽然网上有一些教程,但我仍然不知道为什么这不能正确打印多个页面。 我究竟做错了什么?

public static void printTest() { PrintDialog printDialog1 = new PrintDialog(); PrintDocument printDocument1 = new PrintDocument(); printDialog1.Document = printDocument1; printDocument1.PrintPage += new PrintPageEventHandler(printDocument1_PrintPage); DialogResult result = printDialog1.ShowDialog(); if (result == DialogResult.OK) { printDocument1.Print(); } } 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 = 40; for (int i = 0; i = pageHeight) { e.HasMorePages = true; offsetY = 0; } else { e.HasMorePages = false; } } } 

您可以在此处找到此代码打印结果的示例: 打印文档

你永远不会从循环中返回。 将其更改为:

 if (offsetY >= pageHeight) { e.HasMorePages = true; offsetY = 0; return; // you need to return, then it will go into this function again } else { e.HasMorePages = false; } 

此外,您需要将循环更改为从第2页上的当前编号开始,而不是再次使用i = 0重新启动。