H5 打印

174 阅读1分钟

以vue2为例 原生打印 内容包含打印前打印结束的监听、改变打印样式设置打印大小间距

<template>
</template>
<script>
export default {
  data() {return {}},
  computed: {},
  watch: {},
  methods:{
      print(){
          alert("执行打印")
          window.print()
      },
      beforeprintback(){
          alert("准备开始打印")
      },
      afterprintback(){
          alert("结束打印")
      }
  },
  created() {}, //生命周期 - 创建属性
  mounted(){
      //添加打印监听
      window.addEventListener('beforeprint',this.beforeprintback)
      window.addEventListener('afterprint',this.afterprintback)
  }, //生命周期 - 操作属性
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {
      //去掉打印监听
      window.removeEventListener('afterprint',this.afterprint)
      window.removeEventListener('afterprint',this.afterprintback)
  }, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能,这个函数会触发
}
</script>
<style lang="scss" scoped>
  // 打印样式
  @media print {
    @page {
      /* 纵向打印 */
      // size: portrait;

      /* 横向打印 */
      size: landscape;

      /* 去掉页眉页脚*/
      margin-top: 0;
      margin-bottom: 0;
    }
    /* 告诉浏览器在渲染它时不要对框进行颜色或样式调整 */
    * {
      -webkit-print-color-adjust: exact !important;
      -moz-print-color-adjust: exact !important;
      -ms-print-color-adjust: exact !important;
      print-color-adjust: exact !important;
    }

    /*打印不显示打印按钮*/
    .print-button-container {
      display: none !important;
    }

    /* 伪类 :first 用于匹配到文档的第一页, 首页上页边距设置为 10cm */
    @page :first {
      margin-top: 10cm;
    }

    /* 通过分别设置左页和右页不同的左右页面距,为装订边留出更多的空间 */
    /**/
    @page :left {
      margin-left: 2.5cm;
      margin-right: 2.7cm;
    }
    @page :right {
      margin-left: 2.7cm;
      margin-right: 2.5cm;
    }
  }
</style>