Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET printing on server side from asp.net

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.

like image 324
awen Avatar asked Jun 06 '16 09:06

awen


1 Answers

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.

like image 114
Neil Busse Avatar answered Oct 06 '22 22:10

Neil Busse