Optim.Looking at the original,"C#打印操作实例--实现分页打印操作源码,"I'll remove unnecessary parts as per the rules."源码"(source code)is a generic descriptor,so I’ll remove that."实例"(example)might be redundant but can stay in this context.I'll also replace the double hyph

C#的分页打印操作,真的是做桌面程序常用但又容易被忽略的一块。尤其你要打印报表或者长文档时,一页一页打才合理嘛。这套源码里用的是.NET 里的 System.Drawing.Printing,配合 PrintDocumentPrintPageEventArgs 搞定分页打印。逻辑清晰,步骤明了,拿来就能用,挺适合快速上手或改成自己项目里的。

PrintDocument 的初始化也简单,直接 new 一个对象,设置好纸张和边距。比如:

PrintDocument printDoc = new PrintDocument();
printDoc.DocumentName = "分页打印示例";
printDoc.DefaultPageSettings.PaperSize = new PaperSize("自定义大小", 800, 600);

注册事件这步也别忘了,打印的核心就在 PrintPage 事件里。通过 e.Graphics 来绘制内容,想画啥都行,文本、表格、图片都可以整:

printDoc.PrintPage += new PrintPageEventHandler(this.printDoc_PrintPage);

分页逻辑也得挺清楚,核心是你得知道当前第几页、每页打印多少条:

private void printDoc_PrintPage(object sender, PrintPageEventArgs e) {
  int startIndex = currentPage * pageSize;
  int endIndex = Math.Min(startIndex + pageSize, data.Count);
  for (int i = startIndex; i < endIndex xss=removed xss=removed>

用户点个“打印”按钮就可以开始了:

private void btnPrint_Click(object sender, EventArgs e) {
  currentPage = 0;
  printDoc.Print();
}

如果你正好在做 WinForms 或者 WPF,想实现报表输出、列表打印这种需求,这个源码值得一试。调试的时候记得注意字体大小和页边距,尤其中英文混排容易超界,打印预览也最好加上。

rar 文件大小:2.88MB