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

  • 2020-03-30 02:12:55
  • OfStack

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;');
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>');
if (navigator.userAgent.indexOf("MSIE") > 0)

2) HTML:

//Print area:
<div id="print_box">
//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> 
<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

<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;
 return false;
<title>div print</title>
<input type="button" onClick="printdiv('div_print');" value="  print  ">
<div id="div_print">
<h1 style="Color:Red"> Printed area: www.jb51.net</h1>
 This area is unprintable! 

Related articles: