如何调起打印
npm install printJS
pnpm install printJS
<template>
<div id="printJS">
需要打印的内容
<el-button type="primary" @click="onclick">
</div>
</template>
<script setup lang="ts">
import printJS from 'print-js'
const onclick = () => {
printJS({
printable: 'printJS', // 绑定div的id
type: 'html',
documentTitle: ``,
style: 'body {margin-top: 0; background-color: #fff}',
})
}
</script>
如何让打印的样式不失效
首先需要将打印的内容转化为canvas
转化插件html2canvas
npm install html2canvas
pnpm install html2canvas
<template>
<div id="printJS">
需要打印的内容
<el-button type="primary" @click="onclick">
</div>
</template>
<script setup lang="ts">
import printJS from 'print-js'
import html2canvas from "html2canvas";
async function onclick() {
const dom:any = document.getElementById('printJS');
const canvas = await html2canvas(dom, {
scale: 4,
windowWidth: dom.scrollWidth,
width: dom.clientWidth,
height: dom.clientHeight
});
const dataUrl = canvas.toDataURL('image/png') // canvas生成图片
nextTick(() => {
printJS({
printable: dataUrl, // base64的图片路径
type: 'image', // 类型改为图片类型
documentTitle: ``,
style: 'body {margin-top: 0; background-color: #fff}',
})
})
}
</script>