如何从 WinForms 打印多个页面? [英] How do I print multiple pages from WinForms?

查看:19
本文介绍了如何从 WinForms 打印多个页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然网上有一些教程,但我仍然不明白为什么这不能正确打印多页.我做错了什么?

Although there are some tutorials on web, I'm still lost on why this doesn't print multiple pages correctly. What am I doing wrong?

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 < 100; i++)
   {             
       graphic.DrawString("Line: " + i, font, brush, startX, startY + offsetY);
       offsetY += (int)fontHeight;

       if (offsetY >= pageHeight)
       {
           e.HasMorePages = true;
           offsetY = 0;
       }
       else {
           e.HasMorePages = false;
       }
   }
}

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

You can find an example of this code's printed result here: Printed Document

推荐答案

你永远不会从循环中返回.改为:

You never return from the loop. Change it to:

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 重新启动.

In addition you need to change the loop to start at the current number on the 2nd page instead of restarting with i=0 again.

这篇关于如何从 WinForms 打印多个页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆