Vue front-end implements printing function

introduction

Recently, when I was writing the ERP function background, I found that the front-end was needed to realize printing and document printing, so I queried some methods to implement the front-end printing operation.

Plug-in download

1.html2canvas
2.print-js

Page usage

// 由于我要打印的页面是在 el-dialog 里面,因此需要获取 el-dialog 的宽高,防止打印不全
import html2canvas from 'html2canvas';
import printJS from 'print-js';

// 如果打印的内容中存在可滚动的表格,可以在 this.$nextTick 前把表格的高度设为 100% ,再在 this.$nextTick 里面设置回原来的表格高度
dayin () {
    
    
	this.$nextTick(() => {
    
    
      const printContent = document.getElementsByClassName('el-dialog')[0] as HTMLElement;

      // 获取dom 宽度 高度
      const width = printContent.clientWidth;
      const height = printContent.clientHeight;

      // 创建一个canvas节点
      const canvas = document.createElement('canvas') as any;

      // 定义任意放大倍数,支持小数;越大,图片清晰度越高,生成图片越慢。
      const scale = 4;
      // 定义canvas 宽度 * 缩放
      canvas.width = width * scale;
      // 定义canvas高度 *缩放
      canvas.height = height * scale;
      canvas.style.width = width * scale + 'px';
      canvas.style.height = height * scale + 'px';
      // 获取context,设置scale
      canvas.getContext('2d').scale(scale, scale);

      // 获取滚动轴滚动的长度
      const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
      // 获取水平滚动轴的长度
      const scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft;

      html2canvas(printContent, {
    
    
        canvas,
        backgroundColor: null,
        useCORS: true,
        windowHeight: document.body.scrollHeight,
        // 解决水平偏移问题,防止打印的内容不全
        scrollX: -scrollLeft,
        scrollY: -scrollTop
      })
        .then((canvas) => {
    
    
          const url = canvas.toDataURL('image/png');
          const style = '@page{size: auto; margin: 1cm}';
          printJS({
    
    
            printable: url,
            type: 'image',
            documentTitle: '', // 标题
            style
          });
        })
        .catch((err) => {
    
    
          console.error(err);
        });
    });
}

There are online image resources in the printed content. If you do not want to configure the server, you can close the browser to obtain the cache file to ensure that each time you obtain the online file, there will be no cross-domain errors when printing images. Note that the front end
Insert image description here
cannot Get the event that you clicked to print or cancel. You can only get the event of whether you closed the print box.

If there are any inaccuracies in the article, you are welcome to point them out.

Guess you like

Origin blog.csdn.net/m0_64344940/article/details/128405517