安装需要依赖
npm i html2canvas --save
npm i jspdf --save
npm i print-js --save
页面导入
import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'
import printJS from 'print-js'
实现方法
// 纸张的边距
const margin = 30
// 先把需要打印的页面内容转为canvas,避免各种样式问题
const canvas = await html2canvas(this.$refs['content'])
// 计算canvas内容在A4纸张上的宽度和高度
// a4纸的尺寸[595.28, 841.89]
const imgWidth = 841.89 - margin * 2
const imgHeight = 841.89 / (canvas.width / canvas.height) - margin * 2
// 将canvas转换成图片地址
const pageData = canvas.toDataURL('image/jpeg', 1.0)
// 初始化pdf
// l:横向 p:纵向
// 测量单位("pt","mm", "cm", "m", "in" or "px")
const pdf = new jsPDF('l', 'pt', 'a4')
// 将图片写入pdf中
pdf.addImage(pageData, 'JPEG', margin, margin, imgWidth, imgHeight)
// pdf增加空白页
pdf.addPage()
// 打印pdf
printJS({
printable: pdf.output('bloburi'),
type: 'pdf',
scanStyles: false,
})