c#中的多页打印文档

时间:2014-07-03 19:12:01

标签: c# loops recursion printing

请帮助我一些人,我必须在c#中打印多个页面的文档,我通过互联网然后使用此代码但不能正常工作,(打印一页后循环再次启动)

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

1 个答案:

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