页面应用
<el-dialog title="打印房票" v-model="dialog.printStatus" width="950px" append-to-body>
<div class='rcs' ref="printMesRG">
<div class='res_texts'>
<div>买受人(乙方): {{printUpdataRow.nickname}}</div>
<div></div>
<div>身份证号码 :{{printUpdataRow.cardNum}}</div>
<div>手 机 号 码 :{{printUpdataRow.phone}}</div>
<div>通 讯 地 址 :{{printUpdataRow.adress}}</div>
<div>邮   编 :{{printUpdataRow.postNo}}</div>
</div>
</div>
<template #footer>
<div class="dialog-footer">
<el-button type="primary" @click="downloadPDF">打 印</el-button>
</div>
</template>
</el-dialog>
vue部分
import html2canvas from 'html2canvas'; //div转为图片
import printJS from 'print-js' //打印插件
const printMesRG = ref(null); //ref绑定参数生命
const printUpdataRow = ref({}); //打印模版data
const downloadPDF = async () => {
const node = printMesRG.value
html2canvas(node).then(canvas => {
var pageData = canvas.toDataURL('image/jpeg', 1.0)
printJS({
printable: pageData,
type: "image",
scaleContent: 1,
style:`@media print { @page {size: auto; margin: 0;} body{margin:0; padding: 0;}}`
});
});
}
原理:使用 html2canvas将div内容部分转为图片,再调用print-js打印图片从而实现前端打印操作