vue导出当前页pdf

getPdf.js

import html2Canvas from 'html2canvas';
import JsPDF from 'jspdf';
  /**
   * @description: 导出pdf
   * @param {String} id 携带跳转的id参数 
   * @return:
   */
  async getPdf(_this) {
    let userAgent = navigator.userAgent;
    // 判断浏览器内核是否是是否是火狐或IE
    if (userAgent.indexOf('Firefox') > -1 || !!window.ActiveXObject || 'ActiveXObject' in window) {
      alert('PDF导出暂不支持您的浏览器,请更换谷歌chrome内核浏览器');
      return;
    }
    _this.pdfExportLoading = true;
    var title = _this.htmlTitle;
    const pdfDom = document.querySelector('#pdfDom');
    // mainFrame = document.querySelector('#mainFrame'),
    // const iframeCanvas = await html2Canvas(mainFrame);
    // pdfDom.appendChild(iframeCanvas);

    _this.$nextTick(() => {
      html2Canvas(pdfDom, {
          useCORS: true
         }
        ).then(function (canvas) {
          // pdfDom.removeChild(iframeCanvas);
          let contentWidth = canvas.width;
          let contentHeight = canvas.height;
          let pageHeight = contentWidth / 592.28 * 841.89;
          let leftHeight = contentHeight;
          let position = 0;
          let imgWidth = 595.28;
          let imgHeight = 592.28 / contentWidth * contentHeight;
          let pageData = canvas.toDataURL('image/jpeg', 1.0);
          let PDF = new JsPDF('', 'pt', 'a4');
          if (leftHeight < pageHeight) {
            PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight);
          } else {
            while (leftHeight > 0) {
              PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight);
              leftHeight -= pageHeight;
              position -= 841.89;
              if (leftHeight > 0) {
                PDF.addPage();
              }
            }
          }
          PDF.save(title + '.pdf');
          _this.pdfExportLoading = false;
        }
        );
    });
  }

组件中标注某个元素 id="pdfDom" 此标注元素做为html2Canvas方法中的第一个参数,
pdfExportLoading、htmlTitle导出文件名

<div class="table-page-search-wrapper" id="pdfDom">
....

  data() {
    return {
      htmlTitle:"",
      pdfExportLoading: false
}
}

调用 传入当前实例对象 至于方法挂在哪 自由决定

getPdf(this)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容