编程的“hello world”默认服务器端的ASP.NET MVC打印机(Programmatic

2019-06-27 17:00发布

我已经安装了打印机和内部网服务器上的工作,我想编程方式发送的“Hello World”到默认打印机。 这似乎是最简单的事情,但我一直在google搜索,但没有成功了几个小时。 (注:我正在开发运行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();
}

Answer 1:

打印的“Hello World”服务器端的.NET

  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);
}


Answer 2:

首先,给出一个选项来选择打印机。 你的整体要求是在微软支持网站已经说明。

在这里看看。

样品从那里(在万一哪天页面已经死了): -

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);
    }
}


文章来源: Programmatically “hello world” default SERVER-side printer in ASP.NET MVC