点按钮进行浏览器打印与下载

103 阅读1分钟

记录

打印

image.png
  const onPrint = () => {
    const el = document.getElementById('tables');
    const iframe = document.createElement('IFRAME');
    let doc = null;
    iframe.setAttribute('style', 'position:absolute;width:0px;height:0px;left:500px;top:500px;');
    document.body.appendChild(iframe);
    doc = iframe?.contentWindow.document;
    // 引入打印的专有CSS样式,根据实际修改
    doc.write(el.innerHTML);
    doc.close();
    // 获取iframe的焦点,从iframe开始打印
    iframe?.contentWindow.focus();
    iframe?.contentWindow.print();
    if (navigator.userAgent.indexOf('MSIE') > 0) {
      document.body.removeChild(iframe);
    }
  };

下载

export async function downLoad(url: String) {
  const iframe = document.createElement('iframe');
  iframe.src = BASE_URL + url;
  document.body.appendChild(iframe);
  setTimeout(() => {
    document.body.removeChild(iframe);
  }, 1000);
  return true;
}