VUE + TS 中使用html2canvas和iframe实现打印功能


HTML
  <div id="#printArea">需要打印的区域</div>  
  <div class="print">
          <iframe id='iframe' style="display:none;"></iframe>
     </div>
JAVASCRIPT
  页面引入  html2canvasjquery
  import html2canvas from 'html2canvas';
       import $ from 'jquery';
 
  
  // 打印
   private onPrint() {
         const el: any = $('#printArea')[0];
         const iframe = window.frames[0];
         iframe.document.close();
         html2canvas(el, {
           scale: 1,
           width: el.offsetWidth,
           height: el.offsetHeight,
           allowTaint: true,
           useCORS: true,
         }).then(function (canvas) {
              const context: any = canvas.getContext('2d');
              context.mozImageSmoothingEnabled = false;
              context.webkitImageSmoothingEnabled = false;
              context.msImageSmoothingEnabled = false;
              context.imageSmoothingEnabled = false;
              const src64: any = canvas.toDataURL();
              const newImg: any = document.createElement('img');
              newImg.crossOrigin = 'Anonymous';
              newImg.src = src64;
              iframe.document.write('<img src="' + newImg.src + '" />');
              setTimeout(() => {
                  iframe.window.print();
              });
         });
      }
结果展示
    
 
(表格部分文本域使用了div 代替了el-textarea ,否则会导致html2canvas截取的文本域出现无法换行问题)
 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM