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