借用print-js实现前端打印

1,357 阅读1分钟

print-js官网

说明:可以打印pdf, html, image, json and raw-html.

效果预览:

image.png

打印html为例:

  • 1、安装
yarn add print-js // 本例为1.6.0
  • 2、使用(Home.vue)
import Print from 'print-js';


<template>
  <div id="print-box">
    <div class="ss">什么情况</div>
  </div>
  <button class="no-print" @click="print">打印</button>
</template>

<script lang="ts" setup>
const print = () => {
  Print({
    printable: 'print-box',
    type: 'html',
    documentTitle: '文档标题',
    header: '统计图',
    headerStyle: 'font-weight:400;text-align:center;',
    style: '@page {margin: 0 10mm};', // 不打印页眉和页脚
    honorColor: true, // 是否打印彩色文本
    targetStyles: ['*'] // 允许打印所有样式属性
  })
}
</script>

<style scoped>
button {
  margin-right: 10px;
}
.ss {
  color: #f00;
  text-align: center;
}
</style>

补充说明:注意需要设置targetStyles属性,否则打印出来的文档底部可能会有乱码,而且样式不生效