How to print the page using javascript?

1) Print Window On Load:
using page load we can print easily print the page:
<script type=”text/javascript”>
window.onload = function() { window.print(); }
</script>

2) Ater clicking the link also we can print the page:
<a href=”javascript:window.print()”>Print This Page</a>

3) Print Div Content Using JavaScript
instead of printing an entire page we can print a section from the page (based on DIV ID).


<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Print Page Example</title>
<script language="javascript" type="text/javascript">
function printPage(divID) {
//Get the HTML of div
var divElements = document.getElementById(divID).innerHTML;
//Get the HTML of whole page
var oldPage = document.body.innerHTML;
//Reset the page's HTML with div's HTML only
document.body.innerHTML =
"<html><head><title></title></head><body>" +
divElements + "</body>";
//Print Page
window.print();
//Restore orignal HTML
document.body.innerHTML = oldPage;
}
</script>

</head>
<body>
<form id="frmPrint">
<div id="printSection" style="width: 100%; background-color: Green; height: 200px">
Print me TheBlogReaders.com
</div>
<div id="noprintSection" style="width: 100%; background-color: Yellow; height: 200px">
THIS SECTION NOT PRINTING
</div>
<input type="button" value="Print First Section" onclick="javascript:printPage('printSection')" />
</form>
</body>
</html>

Written by 

I am Sakthivel Madesh, a certified Salesforce Advanced Developer & Administrator working on Salesforce Technology since 2011. I am currently working in Techforce Services as Sr. Salesforce Developer. I have worked on multiple technologies Like PHP, Java, Salesforce, I am very passionate about Salesforce and to earn 15x Salesforce Certification. I love Trailhead for learning Salesforce Skill and Become a Trailhead 5x Ranger too. I Love to Learn & Share my Salesforce knowledge to Salesforce Learners/Beginner using My Blog and Salesforce Community.

Leave a Reply