Multiple page print document in c#

不问归期 提交于 2019-12-25 07:09:52

问题


please some one help me , i have to print a document in multiple pages in c#, i went through internet then used this code but not working, (loop is again start after printing one page )

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:


Whenever you set e.HasMorePages = true, it will just fire the printDocument1_PrintPage() event handler again. You need to keep a class variable for i, so that it won't restart at 0 every time the next page prints. Don't declare it locally inside the event handler.

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


来源:https://stackoverflow.com/questions/24561611/multiple-page-print-document-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!