In this article I will explain with an example, how to print DIV in ASP.Net Core.
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
{
public IActionResult Index()
{
return View();
}
}
View
HTML Markup
The View consists of a HTML DIV and HTML Button.
The Button has been assigned with an
onclick event handler which will be used to call the
PrintHTML JavaScript function.
JavaScript function to Print HTML DIV
Inside the
PrintHTML JavaScript function, the HTML DIV is referenced using its id.
And, the
JavaScript window.open function is called and the window height and width are set.
Then, the HTML contents of the HTML DIV are written to the window using document.write method and the document is closed.
Finally, the window is printed using
JavaScript print function.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div id="dvContents">
<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 type="button" value="Print" onclick="PrintHTML()" />
<script type="text/javascript">
function PrintHTML() {
// Referencing the HTML DIV.
var dvContents = document.getElementById("dvContents");
// Creating a new window.
var printWindow = window.open('', '', 'height=400,width=800');
// Writting the contents of HTML DIV in window.
printWindow.document.write(dvContents.innerHTML);
// Closing the document.
printWindow.document.close();
// Printing the window.
printWindow.print();
}
</script>
</body>
</html>
Screenshot
Browser Compatibility
* All browser logos displayed above are property of their respective owners.
Demo
Downloads