7

我已安装打印机并在 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();
}
4

2 回答 2

10

在 .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);
}
于 2012-09-01T21:07:40.443 回答
1

首先给出选择打印机的选项。您的全部要求已在 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);
    }
}
于 2012-09-01T17:29:54.863 回答