美文网首页
html2canvas 踩坑记录

html2canvas 踩坑记录

作者: 1024k纯金 | 来源:发表于2019-05-22 15:51 被阅读0次

    项目中需要将html字符串打印成pdf,找一下网上的解决方案:

    1. 使用html2canvas.js将网页转换为图片
    2. 使用jsPdf.debug.jscanvas生成的图片转换为pdf文件

    但是并不希望html显示在页面上,因此给截取的html节点加了
    "display:none;"
    然后生成的pdf是空白的。一开始一直在以为是生pdf的时候失败了,直到我留意到这个
    "display:none;"
    因为html2canvas第一个参数就是拿到htmldom节点。如果display:none的话这个节点就不存在了呀,顺着这个思路搜了一下,果然:

    可能这个题目不是很好的描述问题。我先描述一下问题所在,由于html2canvas 生成图片所在的html 必须是真实存在的,否则生成canvas为空白。也就是需要生成html不能设置 disabled: none; visibility: hidden;等属性。
    因此表明在调用html2canvas生成canvas 过程中必须dom 节点渲染完成。因此这就会导致在生成canvas 会出现原有html的闪现。这个问题其实也比较好解决,用了一个小技巧,使用top 属性,把html 移除视野top:100%

    参考自--html2canvas 生成图片踩坑记

    我的解决方式跟上述的类似给pdf绘制的根节点加上了决定定位,把html 移出可视范围之外,然后pdf生成完将原来的节点置空。但是找了一下没看到jspdfsave方法的回调。于是点进了源码:

      /**
           * Saves as PDF document. An alias of jsPDF.output('save', 'filename.pdf').
           * Uses FileSaver.js-method saveAs.
           *
           * @memberOf jsPDF
           * @name save
           * @function
           * @instance
           * @param  {string} filename The filename including extension.
           * @param  {Object} options An Object with additional options, possible options: 'returnPromise'.
           * @returns {jsPDF} jsPDF-instance
           */
    
    
          API.save = function (filename, options) {
            filename = filename || 'generated.pdf';
            options = options || {};
            options.returnPromise = options.returnPromise || false;
    
            if (options.returnPromise === false) {
              saveAs(getBlob(buildDocument()), filename);
    
              if (typeof saveAs.unload === 'function') {
                if (global.setTimeout) {
                  setTimeout(saveAs.unload, 911);
                }
              }
            } else {
              return new Promise(function (resolve, reject) {
                try {
                  var result = saveAs(getBlob(buildDocument()), filename);
    
                  if (typeof saveAs.unload === 'function') {
                    if (global.setTimeout) {
                      setTimeout(saveAs.unload, 911);
                    }
                  }
    
                  resolve(result);
                } catch (e) {
                  reject(e.message);
                }
              });
            }
          }; // applying plugins (more methods) ON TOP of built-in API.
          // this is intentional as we allow plugins to override
          // built-ins
    
    

    瞬间明白了设置options.returnPromise === true就会返回一个promise对象,就能快乐的使用.then

    相关文章

      网友评论

          本文标题:html2canvas 踩坑记录

          本文链接:https://www.haomeiwen.com/subject/deruzqtx.html