前端几种打印推荐
目录
前端几种打印推荐
前端打印
window.print() 使用js自带的打印。
//(1)首先获得元素的html内容(这里建议如果有样式最好是用内联样式的方式)
var newstr = document.getElementById(myDiv).innerHTML;//得到需要打印的元素HTML
//(2)保存当前页面的整个html,因为window.print()打印操作是打印当前页的所有内容,所以先将当前页面保存起来,之后便于恢复。
var oldstr = document.body.innerHTML;//保存当前页面的HTML
//(3)把当前页面替换为打印内容HTML
document.body.innerHTML = newstr;
//(4)执行打印操作
window.print();
//(5)还原当前页面
document.body.innerHTML = oldstr;
这种打印方式很麻烦 虽然可以实现局部打印,需要写行内样式,可能还会影响原来的body。
vue-print-nb 插件
<div id="printTest" >
<p>打印内容</p>
</div>
<button v-print="'#printTest'">打印</button>
这个打印插件我有用过。它在单页面打印做的不错。缺点封装不方便,打印样式不好看,支持参数较少,不满足使用需求。
print-js 插件
let style = `@page {
size: A4 auto;
margin:0 10px;
}
body::before{
content: '';
display: black;
border-bottom: 2px solid rgb(55, 55, 55);
position: fixed;
top: -2px;
width: calc(100% - 18px);
height: 1px;
}
body::after{
content: '';
display: black;
border-bottom: solid 2px #fff;
position: absolute;
top: -2px;
width: calc(100% - 18px);
height: 1px;
}
`
// type:'image' printable:[src,src,src]
// type:'html' printable:dom 会丢失样式。用的时候自己调整吧
// type:'pdf' printable:url 线上地址
printJS({
printable: urls,
type: 'image',
style: style,
targetStyles: ['*'],
scanStyles: false,
})
感觉使用还是print-js 好用一些。方便封装,传入一个dom元素就可以了。
使用html2canvas转html 为图片,需要注意的是,内容过长分页会被截断。
可以使用position: fixed;来定义表头。