多页打印文本文件

时间:2014-01-02 07:14:36

标签: c# visual-studio-2012 printing

我试图根据数据集中给定的记录数循环要打印的文本文件 但它只是覆盖整个页面而无法继续并创建第二页。任何人都可以帮我处理我的代码。感谢

//Calling the Print Document Event and the TextFile 

     private void button1_Click(object sender, EventArgs e){
                string text = System.IO.File.ReadAllText
                (Application.StartupPath+"\\tempnotice_planet.txt");
                string printPath = Application.StartupPath + "\\tempnotice_planet.txt";
                streamToPrint = new StreamReader(printPath);
                printFont = new System.Drawing.Font("Arial", 10);
                printDocument1.Print();
                streamToPrint.Close();
            }


//Printing Code
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs ev)
    {


        float yPos = 0f;
        int count = 0;
        float leftMargin = ev.MarginBounds.Left;
        float topMargin = ev.MarginBounds.Top;
        string line = null;
        int i = 0;



        for (i = 0; i <= records.Tables["Files"].Rows.Count - 1; i++)
        {
            // Calculate the number of lines per page.

    float linesPerPage = ev.MarginBounds.Height / printFont.GetHeight(ev.Graphics);

    // Print each line of the file. 
            while ((count < linesPerPage && ((line = streamToPrint.ReadLine()) != null)))
            {

                yPos = topMargin + count * printFont.GetHeight(ev.Graphics);
                ev.Graphics.DrawString(line, printFont, Brushes.Black, leftMargin, yPos, new StringFormat());
                count++; 
            }

    //after a set of textfile printed..Return to the begining of the textfile to print it again for next batch
    //Continuos Printing
            if (streamToPrint.EndOfStream)
            {
                streamToPrint.DiscardBufferedData();
                streamToPrint.BaseStream.Seek(2, SeekOrigin.Begin);
                ev.HasMorePages = true;
            }

              if (count > linesPerPage)
              {
                  ev.HasMorePages = true;
                  count = 0;
              }
              else
              {
                  ev.HasMorePages = false;
              }

           }


        }

1 个答案:

答案 0 :(得分:0)

printDocument1_PrintPage只能打印一页,然后退出。它应该将ev.HasMorePages设置为true,除非在打印完最后一页之后,它应该是假的。

您可以在呼叫之间单独保留文件位置。摆脱外循环:

for (i = 0; i <= records.Tables["Files"].Rows.Count - 1; i++)