I have a Windows server running an ASP.NET application and a local printer connected to this machine. I need to print some documents from the server-side code.
So far I know, there's no managed API in .NET that is supported on server-side (service).
System.Printing namespace - is part of the WPF and is not supported to run on server-side as it may produce run-time exceptions (checked on msdn)
System.Drawing.Printing - is part of the WinForms and also not supported to run on server-side (checked on msdn)
The same problem was elaborated with help of Microsoft back in 2009 and the solution was to use an unmanaged XPS Print API as the only supported way back in that time. Problem described and solution with example posted is here: How to Print a Document on a Server via the XpsPrint API
However nowadays this is a problem as the XPS Print API is marked as not supported and may be unavailable in the future (msdn).
So, what is the supported way of printing from the server-side code?
It looks like there are more Win32 APIs that could be probably used, but there's no info on the web and it would probably be a nightmare...
Commercial solutions are accepted. Thank you.
So the best way would be to set up your printer on a print server and then install the print drivers on your web server with a reference to the printer you want to print to.
Then in code you can use System.Drawing.Printing to send the print job to whatever printer you just installed.
PrintDocument p1 = new PrintDocument();
p1.PrinterSettings.PrinterName = "\\PrintServer\NewPrinter";
p.PrintPage += new PrintPageEventHandler(this.Page_Print);
p1.Print();
protected void Page_Print(object sender, PrintPageEventArgs ev)
{
Brush b = new SolidBrush(Color.Black);
Font printFont = new Font("Lucida Sans Typewriter", 10);
ev.Graphics.DrawString("Hello World", printFont, b, x, y, StringFormat.GenericDefault);
}
Where this code will work technechally I would not recommend doing it this way since Microsoft itself says that this isn't supported.
I personally would push all print jobs to the client side. Install the printer locally like you did and then redirect the user to a page that they can print easily.
You can then write JavaScript if desired to call the browser specific print for them (if you want to automate that as well)
Or save a PDF server side and push the file as a download to the user making them download/save and then print the document via Adobe Reader or alternative app.
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