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
You cant send direct to the printer.
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
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.
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.
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