Core JavaScript

Printing a Page

This JavaScript example demonstrates how to print a page.

PrintPage.html

<!DOCTYPE html>
<html>
<head>
    <title>Print a Page</title>
    <script type="text/javascript" src="PrintPage.js">
    </script>
    <style>
		#idBackground {
			background-color:#F0F0F0;
		}
		#idButton {
			margin:.25in;
		}
    	#idPrintPage {
    		width:8.5in;
    		height:11in;
    		position:absolute;
    		background-color:#FFFFFF;
    	}
    	#idInsideBleed {
    		width:8.25in;
    		height:10.75in;
    		position:absolute;
    		left:0.125in;
    		top:0.125in;
    		background-color:#F8F8F8;
    		border: 1px solid black;
    	}
    	#idContent {
    		text-align: center;
    	}
    </style>
</head>
<body id="idBackground">
	<input id="idButton" type="button" onclick="PrintPage('idPrintPage')"
		value="Print" />
	<!-- Actual Physical Page -->
	<!-- For best results, scale to 100% with no margin in broswer. -->
	<div id="idPrintPage">
		<!-- Content Area -->
		<!-- To check printing layout, use border: 1px solid black; -->
		<div id="idInsideBleed">
			<h1 id="idContent">Content</h1>
		</div>
	</div>
</body>
</html>

PrintPage.js

function PrintPage(id) {
	// Get the contents that are to be printed.
	var qPrintContents = document.getElementById(id).innerHTML;
	// Store the original body content for restoration.
	var qOriginalContents = document.body.innerHTML;
	// Set the body to the print content.
	document.body.innerHTML = qPrintContents;
	// Open the print dialogue
	window.print();
	// Restore the original contents in the body.
	document.body.innerHTML = qOriginalContents;
}
 

Output

 
 

© 2007–2024 XoaX.net LLC. All rights reserved.