react实现打印功能

1.首先需要个库

import html2canvas from 'html2canvas'

2.封装

/* 
打印封装
id:dom的ID选择器
*/
export const handlePrint = (id: any) => {
  // 先用html2canvas将页面整个转为一张截图,再打印,防止出现echarts无法打印
  const dom = document.getElementById(id) as any;
  html2canvas(dom, {
    scale: 2,
    width: dom.offsetWidth,
    height: dom.offsetHeight,
  }).then((canvas) => {
    const context = canvas.getContext('2d') as any;
    context.mozImageSmoothingEnabled = false;
    context.webkitImageSmoothingEnabled = false;
    context.msImageSmoothingEnabled = false;
    context.imageSmoothingEnabled = false;
    const src64 = canvas.toDataURL();
    const contentWidth = canvas.width;
    const contentHeight = canvas.height;
    const imgWidth = 800; // 根据纸张宽度设定
    const imgHeight = (800 / contentWidth) * contentHeight;
    const img = new Image();
    const div = document.createElement('div');
    div.appendChild(img);
    img.setAttribute('src', src64);
    img.setAttribute('width', imgWidth as any);
    img.setAttribute('height', imgHeight as any);
    img.setAttribute('id', 'imgs');
    div.setAttribute('id', 'printImg');
    document.body.appendChild(div);
    window.document.body.innerHTML = (window as any).document.getElementById('printImg').innerHTML;
    img.onload = () => {
      window.print();
      window.location.reload();
    };
  });
};

3.去除页脚样式

//直接在样式中加入
@page {
  margin-top: 0;
  margin-bottom: 0
}

4.引入并调用方法即可

你可能感兴趣的:(前端,JavaScript,react)