ASP.NET MVC中以编程方式“hello world”默认的SERVER端打印机

我安装了打印机并在Intranet服务器上工作,我想以编程方式将“hello world”发送到该默认打印机。 这似乎是最简单的事情,但我一直在谷歌搜索几个小时没有成功。 (注意:我正在运行Windows 7的部署机器上开发asp.net mvc)

我试图将VB中的一个例子翻译成C#,但它说“没有安装打印机”。

public void TestPrint() { var x = new PrintDocument(); x.PrintPage += new PrintPageEventHandler(PrintPage); x.Print(); } private void PrintPage(Object sender, PrintPageEventArgs e) { var textToPrint = "Hello world"; var printFont = new Font("Courier New", 12); var leftMargin = e.MarginBounds.Left; var topMargin = e.MarginBounds.Top; e.Graphics.DrawString(textToPrint, printFont, Brushes.Black, leftMargin, topMargin); } 

我也尝试过MSDN的一个片段,但它说它无法识别打印机名称。

 public void TestPrint(string msg) { var server = new LocalPrintServer(); var queue = LocalPrintServer.GetDefaultPrintQueue(); // Call AddJob var job = queue.AddJob(); // Write a Byte buffer to the JobStream and close the stream var stream = job.JobStream; var buffer = UnicodeEncoding.Unicode.GetBytes(msg); stream.Write(buffer, 0, buffer.Length); stream.Close(); } 

在.NET中打印“hello world”服务器端

  1. 共享打印机
  2. 创建PrintDocument对象
  3. 按名称引用打印机
  4. 添加提供内容的方法
  5. 打印

 using System.Drawing; using System.Drawing.Printing; public void Print() { var doc = new PrintDocument(); doc.PrinterSettings.PrinterName = "\\\\deployment-machine-name\\share-name"; doc.PrintPage += new PrintPageEventHandler(ProvideContent); doc.Print(); } public void ProvideContent(object sender, PrintPageEventArgs e) { e.Graphics.DrawString( "Hello world", new Font("Arial", 12), Brushes.Black, e.MarginBounds.Left, e.MarginBounds.Top); } 

首先提供选择打印机的选项。 您的整个要求已在Microsoft支持站点上说明。

看看这里。

来自那里的样本(如果有一天页面已经死了): –

 private void print_Click(object sender, System.EventArgs e) { string s = "Hello"; // device-dependent string, need a FormFeed? // Allow the user to select a printer. PrintDialog pd = new PrintDialog(); pd.PrinterSettings = new PrinterSettings(); if( DialogResult.OK == pd.ShowDialog(this) ) { // Send a printer-specific to the printer. RawPrinterHelper.SendStringToPrinter(pd.PrinterSettings.PrinterName, s); } }