Sometimes, you’ll want to allow users the ability to print only a part of your page; for example, a table but not the various links around the page. It’s possible to use a printing stylesheet, but this can cause severe headaches when you need different parts printed at different times. Really, we want to be able to just say element.printElement(), and have it just work. That’s what the MooTools function below does. It’s loosely based around the concepts outlined at this website.
[sourcecode language=”javascript”]Element.implement({
printElement: function(docTitle) {
var strName = ‘printer-‘ + (new Date()).getTime();
var styles = [];
$$(‘link[type=text/css]’).each(function(style) {
styles.push(‘‘);
});
var title = docTitle || document.title;
var that = this.getParent();
var iframe = new IFrame({
name: strName,
styles: {
width: 1,
height: 1,
position: ‘absolute’,
left: -9999
},
events: {
load: function() {
var doc = window.frames[strName].document,
win = window.frames[strName];
var f = function() {
if (!doc.head) {
f.delay(10);
return;
}
// We need to delay printing so that styles are applied.
(function() {
doc.title = title;
// IE7 won’t let us adopt() here for some reason, and we can’t do anything to the head.
doc.body.innerHTML = styles.join(”) + that.innerHTML;
(function() {
win.focus(); // IE needs the window to be focused.
win.print();
}).delay(100);
}).delay(200);
};
f();
}
}
}).inject($(document.body));
(function() {
iframe.dispose();
}).delay(30000);
}
});[/sourcecode]
Leave a Reply