SoFunction
Updated on 2025-03-06

JS uses the print method of window object to implement the pagination printing function

Recently, I used the web online printing function in my project. After research, I used the printing method of Window objects supported by JS itself. This method has better compatibility and has no problem using it in IE and Firefox browsers.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http:///TR/xhtml1/DTD/"> 
<html xmlns="http:///1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>Untitled document</title> 
<script language="javascript"> 
//Print the code function Print()  
 {  
  var printStr = "<html><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8'></head><body >"; 
  var content = ""; 
  var str = ('page1').innerHTML;  //Get the page element that needs to be printed, set the style page-break-after:always, which means to start dividing from the next line.  content = content + str; 
  str = ('page2').innerHTML;  //Get the page element that needs to be printed  content = content + str; 
  printStr = printStr+content+"</body></html>";            
  var pwin=("","print"); //If it is a local test, you need to create it first. If it is used in the domain, you do not need to  (printStr); 
  ();     //This sentence is very important, it cannot be achieved without it  ();  
 } 
</script> 
</head> 
<body > 
<div><input type="button" value="Print" onclick="Print()" /></div> 
<div > 
  <table width="100%" border="0" cellpadding="0" cellspacing="0" style="page-break-after:always" > 
  <tr><td>Print content on the first page</td></tr> 
  </table> 
</div> 
<div > 
  <table width="100%" border="0" cellpadding="0" cellspacing="0"  > 
  <tr><td>Print content on the second page</td></tr> 
  </table> 
</div> 
</body> 
</html> 

Summarize

The above is the JS introduced to you by the editor using the print method of the window object to realize the pagination printing function. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support for my website!