Skip to content

打印页面中的元素

原理:

  1. 利用html2canvas模块将元素转换为canvas
  2. canvas生成图片,并按比例设置图片宽高
  3. 调用window.open()打开新标签页并获得标签页对象page,在新页面写入此图片page.document.write(img.outerHTML)
  4. 关闭标签页输入流:page.document.close(),使用实例触发打印:page.print()
  5. 关闭标签页page.close()

html2canvas

操作步骤

  1. 引入html2canvas模块:
bash
npm i html2canvas --save
  1. 在页面中使用:
javascript
import html2canvas from 'html2canvas'

export function print(elemId) {
  html2canvas(document.getElementById(elemId), {
    allowTaint: false,
    useCORS: true,
  }).then(canvas => {
    //将图片保存到变量
    let image = canvas.toDataURL("image/jpeg");
    let img = document.createElement('img');
    img.src = image
    img.style.width = '100vw'
    img.style.height = `${100 * img.height / img.width}vw`
    var h = window.open('打印窗口', "_blank");
    h.document.write(img.outerHTML);
    h.document.close();
    setTimeout(() => {
      h.print();
      h.close();
    }, 1000)
  });
}