问题
- 使用vue-print-nb打印el表格的时候会出现各种奇怪的样式问题,不好解决
- 缩放问题:表格太长后面会显示不下出现滚动条。
- 表格错位问题:表格头与表格体会出现错位
- 表格边框问题:表格的边框1px不会不显示的问题。
- 使用 html2canvas+printJs 可以完美解决这些问题
- 安装
npm install --save html2canvas
npm install --save print-js
- html部分
<!-- 直接调用方法,html2canvas转换成canvas然后通过printJs打印 -->
<button @click="onPrint()">
<span>打印</span>
</button>
<el-table ref="gatprintArea">
<el-table-column>
</el-table-column>
</el-table>
function onPrint() {
const printContent = this.$refs.gatprintArea.$el;
const width = printContent.clientWidth + 2;
const height = printContent.clientHeight + 2;
const canvas = document.createElement('canvas');
const scale = 10;
canvas.width = width * scale;
canvas.height = height * scale;
canvas.style.width = width * scale + 'px';
canvas.style.height = height * scale + 'px';
canvas.getContext('2d').scale(scale, scale);
const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
const scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft;
html2canvas(printContent, {
canvas,
backgroundColor: null,
useCORS: true,
windowHeight: document.body.scrollHeight,
scrollX: -scrollLeft,
scrollY: -scrollTop
}).then((canvas) => {
const url = canvas.toDataURL('image/png')
printJs({
printable: url,
type: 'image',
documentTitle: '',
style: '@page{size:auto;margin: 0cm 1cm 0cm 1cm;}'
})
}).catch(err=>{
console.error(err);
})
}