互联网技术 · 2024年2月15日

实现web页面的单页和批量打印方法

打印事件:window.print()

1.单页打印(布局打印):

function printCnt(){

//1.获取当前页的html代码

var body = window.document.body.innerHTML;

//2.要打印的部分(#print里面的内容就是要打印的内容)

window.document.body.innerHTML =document.getElementById(“print”).innerHTML;

window.print();

window.document.body.innerHTML = body;

//重新载入当前文档:

location.reload();

}

注意:location.reload();要加,因可解决JS window.print()第二次点击事件失效问题

2.批量打印

注意点:

(1).控制网页的分页:page-break-after:always

注意:避免在表格、浮动元素、带有边框的块元素中使用分页属性

(2).给每个分页的内容要加一个高度,防止变样

 

 

 

报告单1

 

 

报告单2

 

 

 

(3).如果使用window.open(“showPrint.html”,”print”); 打印预览页面的话

//如果是本地测试,需要先新建Print.html,如果是在域中使用,则不需要

// res 是后端返回的需要打印的xxx.html页面

var pwin=window.open(res,”print”);

pwin.document.write(res);

pwin.document.close();//这个是必须的

注意:pwin.document.close(); 可以关闭showPrint.html的页面,使其第二次打印的时候不会跳转到showPrint.html

文章来源:田珊珊个人博客

来源地址:http://www.tianshan277.com/757.html

OpenMagic API

Need more than content? Move into the product flow.

If you are here for model access, pricing, developer docs, or the future API console, the dedicated product path now lives on api.openmagic.ai.