Js implementation of local page print preview principle and sample code

  • 2020-03-30 03:30:46
  • OfStack

Recently a friend asked js how to print preview, today to explain, first understand the principle of printing, in fact, the local printing page is very simple. Just make a starting mark for the part you need to print, and write whatever you want. I'll write here < ! - startprint - > What needs to be printed

< ! - endprint - > Because the tag is not need to let the user see so add comments! The specific implementation code is as follows:


<!DOCTYPE html> 
<html> 
<head> 
<title> Print preview simple implementation </title> 
</head> 
<body> 
<div> 
 This is a body  The content does not need to print, the specific page design according to their own requirements. If you need more than one page tag, Can be generated dynamically tag 
</div> 
<!--startprint--> 
<div> 
 This is what I need to print  
</div> 
<!--endprint--> 
<script type="text/javascript"> 
function preview() 
{ 
var bdhtml=window.document.body.innerHTML;//Gets the HTML code for the current page
var startStr="<!--startprint-->";//Set the print start area
var endStr="<!--endprint-->";//Set the end of print area
var printHtml=bdhtml.substring(bdhtml.indexOf(startStr)+startStr.length,bdhtml.indexOf(endStr));//Get the page to print from the tag

window.document.body.innerHTML=printHtml;//Pages that need to be printed
window.print(); 
window.document.body.innerHTML=bdhtml;//Reduction of interface
} 
preview(); 
</script> 
</body> 
</html>

Related articles: