目录下载依赖使用print-js实现打印功能需要打印的内容按钮调用打印函数打印函数调整打印字体大小参数总结print-js官网链接:https://printjs.crabbly.com/下载依赖n...
目录
下载依赖使用print-js
实现打印功能
需要打印的内容
按钮调用打印函数
打印函数
调整打印字体大小
参数
总结
print-js官网链接: https://printjs.crabbly.com/
下载依赖
npm install print-js --save
在package.json文件中增加print-js依赖。
"dependencies": {
"axIOS": "^0.19.2",
"babel-polyfill": "^6.26.0",
"element-ui": "^2.15.6",
"file-saver": "^2.0.5",
"pinyin-match": "^1.2.2",
"print-js": "^1.6.0",
"vue": "^2.5.2",
"vue-router": "^3.0.1",
"vuex": "^3.1.2",
"xlsx": "^0.17.0",
"xlsx-style": "^0.8.13"
},

使用print-js
在需要打印的页面对应文件中引入print-js
import printJS from 'print-js'
实现打印功能
需要打印的内容
需要把表格打印出来,在表格外套一个div,并给一个id值。
<div class="data-card" id="mytable1">
<el-table size="mini" :key="num" id="mytable"
:header-cell-style="tableHeaderColor"
:span-method="arraySpanMethod"
:cell-style="cellStyle"
ref="table"
:data="tableDataDetail"
border
stripe
style="width: 100%">
<el-table-column
align="center"
:label="title">
</el-table-column>
</el-table>
</div>
按钮调用打印函数
定义一个按钮,点击调用打印函数。
<el-button @click="handleDownload()">下载</el-button>
打印函数
不同浏览器打印样式不同,使用navigator.userAgent进行了判断。
printJS是引用的print-js对象
printtable为标签元素id
type有html,json,pdf等。
header是用于HTML、图像或JSON打印的可选标题。它将被放置在页面的顶部。此属性将接受文本或原始HTML。
style为自定义的样式
handlePrint () {
let userAgent = navigator.userAgent;
//判断是否Firefox浏览器
if (userAgent.indexOf("Firefox") > -1) {
console.log('Firefox')
printJS({
printable: 'mytable1', // 标签元素id
type: 'html',
header: '',
style: `@page {size:auto;margin-top:100px; margin-left:15px; margin-right: 15px;}
thead th {
border-top: 1px solid #000;
border-right: 1px solid #000;
border-left: 1px solid #000;
}
tbody td {
border: 1px solid #000;
}
tbody {
text-align: center;
}
table {
border-collapse: collapse;
}`,
});
}
//判断是否chorme浏览器
if (userAgent.indexOf("Chrome") > -1){
console.log('Chrome')
printJS({
printable: 'mytable1', // 标签元素id
type: 'html',
header: '',
documentTitle: '',
style: `@page {size:auto;margin-top:100px; margin-left:5px; margin-right: 15px;}
thead th {
border-top: 1px solid #000;
border-right: 1px solid #000;
border-left: 1px solid #000;
}
tbody td {
border: 1px solid #000;
}
tbody {
text-align: center;
}
table {
border-collapse: collapse;
}`,
});
}
//判断是否IE浏览器
if (!!window.ActiveXObject || "ActiveXObject" in window) {
console.log('IE')
printJS({
printable: 'mytable1', // 标签元素id
type: 'html',
header: '',
style: `@page {size:auto;margin-top:100px; margin-left:15px; margin-right: 15px;}
thead th {
border-top: 1px solid #000;
border-right: 1px solid #000;
border-left: 1px solid #000;
}
tbody td {
border: 1px solid #000;
}
tbody {
text-align: center;
}
table {
border-collapse: collapse;
}`,
});
}
},
调整打印字体大小
修改print-js文件

修改font_size数值(小于一定数值之后chrome浏览器内打印字体不会变小)

参数
总结
到此这篇关于vue+element-ui前端使用print-js实现打印功能(可自定义样式)的文章就介绍到这了,更多相关vue+element-ui使用print-js打印内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!










