在项目中,打印是不可或缺的功能,网页版的打印功能一直比较薄弱,但也不是不能用;我们可以打印网页上部分内容,来实现相应的报表、单据的打印。

比如本站的文章页面,点击打印机图标,就可以将当前阅读的文章打印出来,或者保存成pdf文件(这个针对chrome谷歌浏览器),实现原理是通过js将页面中不需要打印的内容进行移除,并添加需要打印的内容,然后通过调用window.pint()进行打印,代码如下:

<!-- 指定区域打印实现 -->

<script type="text/javascript">

   var bodyhtml;

   function printPage() {

      //获取当前页的html代码

      bodyhtml = window.document.body.innerHTML;

      // 要打印的部分

      var a="<html><head>";

      var b="</head><body>";

      var c="</body></html>"

      var d="<p><h3>"+$("title").html().replace("_奥非域","")

      +"</h3>"+$(".post-meta").html()+"</p>";

      var printhtml = a+$("head").html()+b+d+$(".post-content").html()+c;

      //alert(printhtml);

      document.body.innerHTML=printhtml;

      setTimeout("CloseAfterPrint();",0);

      return false;

   }

   function CloseAfterPrint(){

      if(tata=document.execCommand("print")){

         document.body.innerHTML=bodyhtml;

      }

      else setTimeout("CloseAfterPrint();",1000);

   }

</script>

测试了ie11和chrome,效果不错,下图是chrome浏览器下保存pdf的效果。