从PRINT按钮打印.rtf或.txt文件?

时间:2013-12-14 06:01:59

标签: c#

我正在制作一个简单的工作记事本测试程序。我希望能够点击菜单栏中的菜单项(打印)并将文档打印到我的打印机。以下代码是我使用的,但我不确定这是否是我需要的简单打印。我是C#的新手,因此不熟悉printDocument类。

private void printToolStripMenuItem_Click(object sender, EventArgs e)
        {


       try 
       {
           StreamReader streamToPrint = new StreamReader
              ("C:\\My Documents\\MyFile.txt");
           try 
           {
              Font printFont = new Font("Arial", 10);
              PrintDocument pd = new PrintDocument();
              pd.PrintPage += new PrintPageEventHandler(myFileName);
              pd.Print();
           }  
           finally 
           {
              streamToPrint.Close();
           }
       }  
       catch(Exception ex) 
       {
           MessageBox.Show(ex.Message);
       } 

1 个答案:

答案 0 :(得分:1)

问题:您没有正确处理PrintPagEvent

解决方案:通过编写PrintPageEvent处理程序来打印正确处理PrintPageEvent所需的文档。

    String content="";  
    Font printFont = new Font("Arial", 10);
    private void printToolStripMenuItem_Click(object sender, EventArgs e)
    {
       try 
       {
              content= File.ReadAllText("C:\\My Documents\\MyFile.txt");
              PrintDocument pd = new PrintDocument();
              pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
              pd.Print();
       }  
       catch(Exception ex) 
       {
           MessageBox.Show(ex.Message);
       } 
    }
     private void pd_PrintPage(object sender, PrintPageEventArgs ev)
     {
       ev.Graphics.DrawString(content,printFont , Brushes.Black,
                       ev.MarginBounds.Left, 0, new StringFormat());
     }