Js calls the iframe implementation of the method to print the content of the page


1. Program description

  1. this program can select the area of the page to print, and print in the mode of iframe;
  2. the difference from original print() is that the contents of the currently visited page can be completely retained after the page is unprinted.

2. Code part

  1. JS function:
function do_print(id_str)//Id-str prints the id of the region
{
var el = document.getElementById(id_str);
var iframe = document.createElement('IFRAME');
var doc = null;
iframe.setAttribute('style', 'position:absolute;width:0px;height:0px;left:-500px;top:-500px;');
document.body.appendChild(iframe);
doc = iframe.contentWindow.document;
//Introduction of proprietary CSS styles for printing, www.111Cn.net as the case may be
doc.write("<LINK rel="stylesheet" type="text/css" href="css/print.css">");
doc.write('<div>' + el.innerHTML + '</div>');
doc.close();
iframe.contentWindow.focus();
iframe.contentWindow.print();
if (navigator.userAgent.indexOf("MSIE") > 0)
{
     document.body.removeChild(iframe);
}
}
  1. HTML:
//Print area:
<div id="print_box">
......
</div>
//Call to print
<button onclick="javascript:do_print('print_box');"> print </button>

3. The test

Click the print button on the page to test the print;

In addition to the above methods we can also use jquery to example, the code is as follows

<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="jquery.PrintArea.js"></script>
<script>
$(document).ready(function(){
  $("input#biuuu_button").click(function(){
  $("div#myPrintArea").printArea();
});
});
</script>
<input id="biuuu_button" type="button" value=" print "></input>
<div id="myPrintArea">..... Text print .....</div>

To implement region printing we can try the following method

Here’s a super simple way to print a page, not just the entire page, but an area of the page

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script language="javascript">
function printdiv(printpage){
 var headstr="<html><head><title></title></head><body>";
 var footstr="</body>";
 var newstr=document.all.item(printpage).innerHTML;
 var oldstr=document.body.innerHTML;
 document.body.innerHTML=headstr+newstr+footstr;
 window.print();
 document.body.innerHTML=oldstr;
 return false;
}
</script>
<title>div print</title>
</head>
<body>
<input type="button" onClick="printdiv('div_print');" value="  print  ">
<div id="div_print">
<h1 style="Color:Red"> Printed area: www.jb51.net</h1>
</div>
 This area is unprintable!
</body>
</html>