Send MVC actionresult to printer

17,832

Solution 1

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.

Solution 2

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.

Share:
17,832
Hugo Forte
Author by

Hugo Forte

Just another c#/js/rails/node developer;-)

Updated on September 15, 2022

Comments

  • Hugo Forte
    Hugo Forte over 1 year

    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

  • Hugo Forte
    Hugo Forte over 12 years
    Thanks a lot for the quick answer!
  • Hugo Forte
    Hugo Forte over 12 years
    Thanks a lot for the quick answer!