浏览器打印特定元素的方法

<!-- 
适用于VUE项目
需要导入print.JS和html2canvas
 -->
    <div id="printTable" ref="printTable">
		任意内容
	</div>
	<button @click='print'>打印<button>
    // 打印物品
    print() {
      var t = window.devicePixelRatio   // 获取下载的缩放 125% -> 1.25    150% -> 1.5
      if (t != 1) {   // 如果进行了缩放,也就是不是1
        document.body.style.zoom = -0.6 * t + 1.55;   // 就去修改页面的缩放比例,这个公式我自己算的,不准确,勉强。
      }
      const printContent = this.$refs.printTable;
      const width = printContent.clientWidth;
      const height = printContent.clientHeight;
      const canvas = document.createElement('canvas');
      const scale = 4;
      canvas.width = width * scale; // 定义canvas 宽度 * 缩放
      canvas.height = height * scale; // 定义canvas高度 *缩放
      canvas.style.width = width * scale + 'px';
      canvas.style.height = height * scale + 'px';
      canvas.getContext('2d').scale(scale, scale);
      const scrollTop = document.documentElement.scrollTop || document.body.scrollTop; // 获取滚动轴滚动的长度
      const scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft;
      this.printerLoading = true
      html2canvas(printContent, {
        canvas,
        backgroundColor: null,
        useCORS: true,
        windowHeight: document.body.scrollHeight,
        scrollX: -scrollLeft, // 解决水平偏移问题,防止打印的内容不全
        scrollY: -scrollTop
      }).then((canvas) => {
        this.printerLoading = false
        const url = canvas.toDataURL('image/png')
        printJS({
          printable: url,
          type: 'image',
          documentTitle: '', // 标题
          style: '@media print{@page {size:landscape;margin: 0cm 1cm 0cm 1cm;border:5px #f80 solid;}}'
        })
      }).catch(err => {
        this.printerLoading = false
        console.error(err);
      })
    },
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值