正常情况下的打印是使用 window.print(); 直接整页打印,但如果需要打印网页中定义的部分内容,则可使用如下的方法:
1、在页面的代码头部处加入JavaScript:
<script language=javascript>
function doPrint() {
bdhtml=window.document.body.innerHTML;
sprnstr="<!--startprint-->";
eprnstr="<!--endprint-->";
prnhtml=bdhtml.substr(bdhtml.indexOf(sprnstr)+17);
prnhtml=prnhtml.substring(0,prnhtml.indexOf(eprnstr));
window.document.body.innerHTML=prnhtml; window.print();
}
</script>
也就是在需要用户打印保存的正文所对应的html处附加上。同时,如果采用小偷程序获得远程数据并需打印,可将此等数据置于该定义标签之内即可。
3、截取内容部分已完成,现在加个“打印”的链接:
<a href="#" onClick="doPrint()">打印</a>
完整HTML示例:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8">
</head>
<script type="text/javascript">
function my_print(){ //直接调用浏览器打印功能
bdhtml=window.document.body.innerHTML; //定义打印区域起始字符,根据这个截取网页局部内容
sprnstr="<!--startprint-->"; //打印区域开始的标记
eprnstr="<!--endprint-->"; //打印区域结束的标记
prnhtml=bdhtml.substr(bdhtml.indexOf(sprnstr)+17);
prnhtml=prnhtml.substring(0,prnhtml.indexOf(eprnstr)); //还原网页内容
window.document.body.innerHTML=prnhtml; //开始打印
window.print();}
</script>
<body>
<a href="#" onClick="my_print();" ><span> 打 印</span></a><br>
<!--startprint-->
<img src="test.jpg" style="height: 150px;width:150px"/>
<!--endprint-->
</body>
</html>打印带滚动条的table时,出现了只显示一张的情况
<div class="container query-table" id="query-table"> <div class="table-responsive tableResponsive" id="queryTable" style="overflow: scroll;height: 100%;"> <!--startprint--> <table class="table text-center" id="printTable" style="border-left: none;"> <thead class="tableHeader"></thead> <tbody class="tableBody"></tbody > </table > <!--endprint--> </div> </div>
解决办法:
/*dom显示高度的设置*/
html, body {height: 100%;}
#query-table {height: 100%;}
#queryTable {height: 100%;}
/*打印高度的设置*/
@media print {html, body {height: inherit;}
#query-table {height: inherit;}
#queryTable {height: inherit !important;}}实现分页打印:
window.print() 实现分页打印主要通过样式来控制,样式如下:
style="page-break-after:always"
如果打印两页只需要给第一页加上该样式即可,不需要给第二页加上,否则第二页在打印时会多走一张空白纸,具体代码如下:
<div class="container a4-endwise" id="page1" style="page-break-after:always;">第一页被打印的内容</div> <div class="container a4-endwise" id="page2" >第二页被打印的内容</div>
去掉页眉页脚及打印链接:
<style media="print">
@page {size: auto;/* auto is the initial value */margin: 0mm; /* this affects the margin in the printer settings */}
</style>