打印功能

两种方法:

方法一:

<div class='print'>

 *****

</div>

//获取要打印的html内容

var printer = document.getElementsByClassName('print')[0]

//新建body,将打印内容赋值给新建的body

window.document.body.innerHTML = printer

//调用浏览器print方法

window.print()

//刷新页面,回到原来的页面

window.reload()

存在的问题:

内容打印不全:参与项目使用了elementUI组件库,虽然在打印事件内,动态修改了表格的宽度,但依然会表格内容打印不全。所以,抛弃了这个方法

方法二:

兼容:IE10+/FF/Chrome

引用了print-js、html2canvas两个依赖包

import printJs from 'print-js'

import html2canvas from 'html2canvas'

<div class='print'>

 *****

</div>

var printer = document.getElementsByClassName('print')[0]

var opts = {

    width: printer.clientWidth,

    height: printer.clientHeight,

    logging:false

}

html2canvas(printer, opts).then((canvas)=>{

  printJs(canvas.toDataURL(),'image')

})

遇到的问题:

打印出来字体偏小

      解决方法:

     1、为打印设置专门的样式

     2、将打印默认设置为横向打印,因需要引用第三方插件,个人觉得代价比较大,所以采用了第一种解决方法。

          打算用css规则设置横向打印, @media print {@page {size: landscape;}},但无效果,个人推测这个规则在用window.print方法时有效

依赖包API地址

print-js:http://printjs.crabbly.com/#documentation

html2canvas: https://html2canvas.hertzen.com/configuration

猜你喜欢

转载自www.cnblogs.com/respect2017/p/9234755.html
今日推荐