简体   繁体   English

将MVC actionresult发送到打印机

[英]Send MVC actionresult to printer

I have a controller with an action: 我有一个带动作的控制器:

SomeController/ActionToBePrinted

ActionToBePrinted() returns an html view. ActionToBePrinted()返回一个html视图。

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? 当按下按钮时,从正常的mvc剃刀视图调用此操作 - 当按下按钮时,如何将视图内容发送到打印机?

Aloha, Hugo 阿罗哈,雨果

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. 我建议你创建一个自定义的ActionResult,它返回一个PDF文件或类似的东西。 ASP.NET MVC Action Results and PDF Content ASP.NET MVC操作结果和PDF内容

  2. You can show a html page as well and open the print dialog using javascript like this 您也可以显示一个html页面,并使用这样的JavaScript打开打印对话框

<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 (eg use window.open() and pass in URL or use AJAX) and put the returned HTML contents into a new window. 您可以执行GET请求(例如,使用window.open()并传入URL或使用AJAX)并将返回的HTML内容放入新窗口。 Then use 然后用

Window.print() . 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. 您可以通过在正文中添加内容将其直接绑定到单个视图中,但我更喜欢在这些情况下使用JavaScript。 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. 相反,JavaScript作为View进入。

Keep in mind that HTML is not a print format. 请记住,HTML不是打印格式。 So if you need to control the layout, you should be using a print technology such as PDF. 因此,如果您需要控制布局,则应使用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 XSLT提供了一种使用相同数据创建HTML和PDF输出的绝佳方法,尽管创建XSLT模板要比window.print要多得多。

Personally, I have an MVC page acting as a service that takes URL parameters. 就个人而言,我有一个MVC页面作为一个服务,采取URL参数。 The page hooks into Adobe XSL-FO and uses the params to drive the output. 该页面挂钩到Adobe XSL-FO并使用参数来驱动输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM