c# - 将文件发送到打印机,没有打印任何内容

标签 c# asp.net printing

我有这样的要求,我必须从 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!
}

请告诉我是否有其他方法可以做到这一点,我只需要查看打印的数据。注意:我没有使用白色前景色或类似的东西,打印机可以接收大约 1 MB 的文本,然后只打印一页,其中没有任何内容。

最佳答案

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

  • 打开上面代码中的文件,将流读取器保存在全局中 实例变量。
  • 添加页面事件处理程序
  • 在退出时关闭流

我认为这个example in MSDN完全适合

如果您查看 MSDN 中有关 DocumentName 的文档属性(property)你会发现这个声明

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.

关于c# - 将文件发送到打印机,没有打印任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11619232/

相关文章:

printing - 打印机驱动程序是做什么的?如何拦截/获取它发送给打印机的数据/命令?

c# - 是否可以使用 ReadOnlySpan<char> 从字符串中解析 int

c# - 在 OSX 上使用 MonoKickstart 时找不到 gdiplus.dll

c# - 使用 LINQ 更新 SQL 行中的每个字段而无需专门声明每个字段?

c# - 面对没有主键约束的表时,Dapper 或 ADO.NET

asp.net - 是否需要使用 Me (VB.NET) 关键字?

python - 从 RDF 查询结果打印/解析 JSON 对象

c# - 制作游戏 - 安全变量的优势是什么?

c# - SolrNet 中是否有核心操作的类或方法?

java - 如何打印 List<Object[]> 值?