17 May, 2012

How to set print area in JSP/HTML page for printer

This is one the interesting topic related to print the specific data from a jsp/html page. Directly to printer, without other browser data. I have done a quite obvious way in javascript for set the print area for printing. I faced this problem in my development team with me, for set a specific area for print.

Caution:-  Use of JavaScript may not be  always acceptable, due to client. If user/client disable the script setting in browser these may not work properly. But, every browsers are support script by default.  

As we know, window. Print() is used for print in JavaScript. There are so many ways to do a printing task in jsp/html page. Out of all I have mentioned 2 process below with advantage & disadvantage.  Put the below function in script area of your page:-

Procedure-1
function setDivPrint(val){
var printdata=document.getElementById('printarea').innerHTML;
var srcOriginalContent=document.body.innerHTML;
document.body.innerHTML=printdata;
window.print();
document.body.innerHTML=srcOrigionalContent;
}
Here ‘printarea ‘ is the id of printable div. It has some limitation, with getting the cancel button click event and some more. I am not mentioning all here. But in procedure-2 is so eminent than procedure-1.

Procedure-2

function setDivPrint(val){
var printdata=document.getElementById('printarea').innerHTML;
var printwindow=window.open('','','left=0,top=0,width=1000,height=780,toolbar=0,scrollbars=0,status=0');
printwindow.document.write(printdata);
printwindow.document.close();
printwindow.focus();
printwindow.print();
printwindow.close();
}

Here ‘printarea ‘ is the id of printable div. .This method is recommended to use. In this method no need to get the cancel or print button event. Suppose the user click on cancel, then the main original page should come, but it may not coming with the Procedure-1 . So, No need to face this problem in Procedure-2.

No comments:

Post a Comment