Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send MVC actionresult to printer

I have a controller with an action:

SomeController/ActionToBePrinted

ActionToBePrinted() returns an html view.

This action is called from a normal mvc razor view when pressing a button - how would I go about sending the content of the view to a printer when the button is pressed?

Aloha, Hugo

like image 973
Hugo Forte Avatar asked Nov 28 '11 14:11

Hugo Forte


2 Answers

You cant send direct to the printer.

  1. I suggest you to create a custom ActionResult, that returns a PDF file or something like that. ASP.NET MVC Action Results and PDF Content

  2. You can show a html page as well and open the print dialog using javascript like this

<a href="javascript:window.print()">Click to Print This Page</A>

But always the user has to start the print process, you cant do this programmatically.

like image 54
dknaack Avatar answered Oct 15 '22 05:10

dknaack


You can perform a GET request (e.g. use window.open() and pass in URL or use AJAX) and put the returned HTML contents into a new window. Then use

Window.print(). Then simply close the window when you are done.

You could tie this directly into a single view by adding something in the body, but I prefer to use JavaScript in these cases. This keeps the design acting as a re-useable object or service that can be used across multiple views. In other words, you setup the controller-model, but no view. Instead, JavaScript steps in as the View.

Keep in mind that HTML is not a print format. So if you need to control the layout, you should be using a print technology such as PDF. XSLT provides an excellent means to create both HTML and PDF output using the same data, albeit it's a lot more work to create XSLT templates than it is to slap down window.print

Personally, I have an MVC page acting as a service that takes URL parameters. The page hooks into Adobe XSL-FO and uses the params to drive the output.

like image 42
P.Brian.Mackey Avatar answered Oct 15 '22 05:10

P.Brian.Mackey