2012-07-23 228 views
2

我有这个要求,我必须从Web应用程序打印收据。我已经找到了获取字符串中的数据,生成临时文本文件,将其发送到打印机并删除文件的方法。除了打印部分,一切都很好,它什么都不产生,一个白色的文档!我在发送打印文件之前检查了我的临时文件,这里有数据,也许我以错误的方式发送文件或忘记添加一个PrintPageEventHandler(我不太确定这最后一个,或者我可能是我只是不知道)。发送文件到打印机,什么都不打印

这就是我所做的:

private void printTextfile(String strFileName) 
{ 
    //there is this standar that makes programmers declare variables at the 
    //beginning of the method and this "obj" and "str" things... 
    PrintDocument objPrintDocument =null; 
    String strPrinterName = string.Empty; 
    //getting the printer name from web.config 
    strPrinterName= ConfigurationManager.AppSettings["NOMBRE_IMPRESORA"]; 
    objPrintDocument = new PrintDocument(); 
    objPrintDocument.PrinterSettings.PrinterName = strPrinterName; 
    //the temp text file created and with data 
    objPrintDocument.DocumentName = strFileName; 
    //I guess don't need this because I've setted up the file name (it is reachable) 
    //objPrintDocument.PrintPage += new PrintPageEventHandler(this.printTextFileHandler); 
    //send the file to the printer (this works) 
    objPrintDocument.Print(); 
    //ok, now I've check my physic file and it has nothing in it! 
} 

请告诉我,如果有另一种方式来做到这一点,我只需要看到打印的数据。注意:我没有使用白色的forecolor或类似的东西,打印机可以接收1MB的文本,只需打印1页就没有任何内容。

+0

..? – MethodMan 2012-07-23 19:34:47

+0

将数据发送到打印机的代码在哪里?您正在设置DocumentName,然后调用Print,但这不会打印任何内容。 – Steve 2012-07-23 19:38:32

+0

@DJKRAZE没有错误,否则打印机无法打印任何文件。 – 2012-07-23 19:58:31

回答

3

您需要添加一个打印页面事件处理程序,将您的数据输出到打印机。
如果strFileName是包含数据的文件名,然后

  • 打开上面保存的StreamReader在全球 实例变种的代码的文件。
  • 添加页面事件处理程序
  • 在出口关闭流

我认为这example in MSDN完全适合

如果你看一下在MSDN文档有关DocumentName属性,你会觉得这种说法

The DocumentName property does not specify the file to print. 
Rather, you specify the output to print by handling the PrintPage event. 
For an example, see the PrintDocument class overview. 
1

试试这个:

private void button1_Click(object sender, EventArgs e) 
     { 
      System.IO.StreamReader filetoprint; 
       filetoprint = new System.IO.StreamReader(@"D:\\m.txt"); 
       printDocument1.Print(); 
       filetoprint.Close(); 
     } 
当你调试这个你得到一个值回strPrinterName或空值