In this article I will explain with an example, how to print View in ASP.Net MVC.
Controller
The Controller consists of following Action method.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
}
View
HTML Markup
The View consists of a HTML Button.
The Button has been assigned with an
onclick event handler which will be used to call the
PrintView JavaScript function.
JavaScript function to Print View
Inside the
PrintView JavaScript function, the HTML Button is referenced using its id and Button is made hidden.
Next, the HTML Body is referenced using its TagName.
And, the
JavaScript window.open function is called and the window height and width are set.
Then, the HTML contents of the body are written to the window using document.write method and the document is closed.
Finally, the window is printed using
JavaScript print function and Button is again made visible.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
<span style="font-size: 10pt; font-weight: bold; font-family: Arial;">
Hello,
<br />
This is <span style="color: #4A0089;">Mudassar Khan</span>.<br />
Hoping that you are enjoying my articles!
</span>
</div>
<br />
<input id="btnPrint" type="button" value="Print" onclick="PrintView()" />
<script type="text/javascript">
function PrintView() {
// Referencing the Print Button.
var btnPrint = document.getElementById("btnPrint");
// Hiding the Print Button.
btnPrint.style.display = "none";
// Referencing the HTML Body.
var body = document.getElementsByTagName("body")[0];
// Creating a new window.
var printWindow = window.open('', '', 'height=400,width=800');
// Writting the contents of Body in window.
printWindow.document.write(body.innerHTML);
// Closing the document.
printWindow.document.close();
// Printing the window.
printWindow.print();
// Showing the Print Button.
btnPrint.style.display = "block";
}
</script>
</body>
</html>
Screenshot
Browser Compatibility
* All browser logos displayed above are property of their respective owners.
Demo
Downloads