jQuery Print Preview plugin provides your site visitors a quick, instant print preview of the active page before actually printing. The preview can be invoked using a button on the page or by pressing Ctrl+P keyboard shortcut. You can see the plugin in action here.
Implementing Print Preview
Prerequisites:
- Print stylesheet: If your website already has a
print.css
stylesheet that would do, if not, create one and link it in your page header using this code:
<link rel="stylesheet" href="/path-to/print.css" type="text/css" media="print" />
- jQuery: If you have a copy of jQuery on your server, use that, or else use the below code to get an online minifed copy:
<script src="http://cdn.jquerytools.org/1.2.5/full/jquery.tools.min.js"> </script>
Using the plugin:
print-preview.css
and jquery.print-preview.js
contains the code that generates the preview. These files can be found inside ‘src’ folder in the downloadable tarball.
<link rel="stylesheet" href="print-preview.css" type="text/css" media="screen"> <script src="jquery.print-preview.js" type="text/javascript" charset="utf-8"> </script>
This is the JavaScript that invokes the preview:
<script type="text/javascript"> $ (function () { // Add a print preview link $('#aside').prepend('<a class="print-preview">Print this page</a>'); // Initialize plugin $('a.print-preview').printPreview(); // Trigger when Ctrl+P is pressed $(document).bind('keydown', function(e) { var code = (e.keyCode ? e.keyCode : e.which); if (code == 80 && !$('#print-modal').length) { $.printPreview.loadPrintPreview(); return false; } }); }); </script>
Supported Browsers:
This plugin works with pretty much all browsers.
- Opera
- Safari
- Firefox
- Google Chrome
- Internet Explorer 6, 7, 8 and 9
Download: jQuery Print Preview plugin
One thought on “Give Your Site Visitors a Quick Print Preview Option, Ctrl+P Hotkey”
Hi! Big thanks for this. Its really awesome!
However I noticed that the below statement was executed multiple times.
$(‘head’).append(” +
‘@media print {‘ +
‘/* — Print Preview –*/’ +
‘#print-modal-mask,’ +
‘#print-modal {‘ +
‘display: none !important;’ +
‘}’ +
‘}’ +
”
);
As a result, multiple style tags were appended.
It would be better if you can assign an ID for this.
So that you can check if this DOM was already appended.
Keep it up! 😎