WWW FAQs: How do I add a print button to a web page?

2007-05-29: "I want to add a 'print' button or link to my web page, to help users who are confused and don't know how to use their browser's print button. How do I do that?"

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>

I've tested this code successfully in Internet Explorer, Safari and Firefox.
This page is simple, but it has one problem: if JavaScript is turned off, then the page contains a print button that doesn't do anything. And that's confusing.

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>

The document.write method outputs the HTML for the print button at that point in the page. Note the use of single quotes for the attributes of the input element. It's legal, even in XHTML Strict, and it's much more pleasant to write it this way rather than escaping the double-quotes.
What if you want an ordinary link rather than a form-style button? That's easy too— just use a javascript: URL as the href attribute, like this:


<html>
<head>
<title>Print Test</title>
</head>
<body>
<h1>Print Test</h1>
<a href="javascript:window.print()">Print This Page</a>
</body>
</html>

Share |

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-2014 Boutell.Com, Inc. All Rights Reserved.