It's easy to add a print button! JavaScript provides the window.print method, which instructs the browser to print the current page. The user will, of course, see their usual printer-selection dialog box and so on, which gives them an opportunity to cancel. If you're looking for a way to force the user to print, don't bother. There isn't one. And there shouldn't be.
Here's an example of a web page with a JavaScript print button:
<html>
<head>
<title>Print Test</title>
</head>
<body>
<h1>Print Test</h1>
<input type="button"
onClick="window.print()"
value="Print This Page"/>
</body>
</html>
We can fix the problem by generating the print button itself with JavaScript. That way, if JavaScript is turned off, the button doesn't appear. Because there's nothing worse than a button that doesn't work!
Of course, the user can just use her web browser's normal print button instead.
Here's the code for a page with a print button that appears only when JavaScript is actually available.
This example also hides the print button in the actual printed version of the page, thanks to the use of CSS code specifically for the "print" media type.
<html>
<head>
<title>Print Test</title>
</head>
<body>
<style type="text/css" media="print">
.printbutton {
visibility: hidden;
display: none;
}
</style>
<h1>Print Test</h1>
<script>
document.write("<input type='button' " +
"onClick='window.print()' " +
"class='printbutton' " +
"value='Print This Page'/>");
</script>
</body>
</html>
<html>
<head>
<title>Print Test</title>
</head>
<body>
<h1>Print Test</h1>
<a href="javascript:window.print()">Print This Page</a>
</body>
</html>
Legal Note: yes, you may use sample HTML, Javascript, PHP and other code presented above in your own projects. You may not reproduce large portions of the text of the article without our express permission.
Got a LiveJournal account? Keep up with the latest articles in this FAQ by adding our syndicated feed to your friends list!
Follow us on Twitter | Contact Us
Copyright 1994-2012 Boutell.Com, Inc. All Rights Reserved.
