Opensource, CMS, PHP, MySql, Drupal, Frameworks

Tuesday, February 15, 2011

print page content using drupal and javascript

Create a javascript file: print_page.js

var PrinterTool = {};
PrinterTool.windowSettings = 'toolbar = no, location = no,' + ' status = no, menu = no, scrollbars = yes, width = 650, height = 400';
PrinterTool.print = function (tagID) { 
     var target = document.getElementById(tagID);
     var title = document.title;
     if(!target || target.childNodes.length === 0) {
         alert("Nothing to Print");
         return;
     }
     var content = target.innerHTML;
     var text = '<html><head><title>' + title + 
                     '</title><body>' + content + '</body></html>';
     printerWindow = window.open('', '', PrinterTool.windowSettings);
     printerWindow.document.open();
     printerWindow.document.write(text);
     printerWindow.document.close();
   printerWindow.print();
};


Call the function with ID.  Paste following code in your tpl file/ block
<a href="javascript:PrinterTool.print('main')" >Print</a>

Ref book: Drupal 6 JavaScript and jQuery