I have the printer installed and working on an intranet server and I want to programmatically send "hello world" to that default printer. This seems like the simplest thing but I've been googling for a couple hours with no success. (note: I am developing asp.net mvc on the deployment machine itself which is running Windows 7)
I tried to translate an example from VB here into C# but it said "no printers are installed".
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);
}
I had also tried a snippet from MSDN here but it said it did not recognize the printer name.
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();
}
Print "hello world" server-side in .NET
PrintDocument
objectCode
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With