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> 
<title> Print preview simple implementation </title> 
 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 
 This is what I need to print  
<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.document.body.innerHTML=bdhtml;//Reduction of interface

Related articles: