Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

c# - How do I print multiple pages from 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
}

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...