2012-07-23 230 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或空值