jsPDF with Cordova - Adding images

两盒软妹~` 提交于 2019-12-05 13:15:22

I solved the issue with help from this blog post: https://coderwall.com/p/nc8hia. There does seems to be significant differences between the 0.90 version used in that post and the version that I am using from https://github.com/MrRio/jsPDF however the solution is pretty much the same. First off, in the version from MyRio, you can get the PDF generation working without fixing the Blob issue noted in Igor’s post. All you need is to generate the PDF output by calling “doc.ouput()” and then save it using the Cordova filesystem plugin. So I thought I did not have to create the Blob (this is where I was wrong).
Igor (from the coderwall post) responded back to my question with some additional code but when I searched the jspdf.js file from MyRio version, I saw that the code (more compact version) was already in the code on lines 734 – 738:

var data = buildDocument(), len = data.length,
    ab = new ArrayBuffer(len), u8 = new Uint8Array(ab);

while(len--) u8[len] = data.charCodeAt(len);
return new Blob([ab], { type : "application/pdf" });

But I also notice that the blob creation code that Igor fixed in his initial post was at the end of this block of code. So I commented out the “return new Blob([ab], { type : “application/pdf”});” line and put in the following code from Igor’s post with minor variable name changes:

try
{
    var blob = new Blob([ab], {type: "application/pdf"});
    console.debug("case 1");
    return blob;
 }
 catch (e)
 {
     window.BlobBuilder = window.BlobBuilder ||
                                          window.WebKitBlobBuilder ||
                                          window.MozBlobBuilder ||
                                          window.MSBlobBuilder;
     if (e.name == 'TypeError' && window.BlobBuilder)
     {
         var bb = new BlobBuilder();
         bb.append(ab);
         console.debug("case 2");
         return bb.getBlob("application/pdf");

      }
      else if (e.name == "InvalidStateError")
      {
          // InvalidStateError (tested on FF13 WinXP)
          console.debug("case 3");
          return new Blob([ab], {type: "application/pdf"});

       }
       else
       {
           // We're screwed, blob constructor unsupported entirely
           console.debug("Errore");
       }
 }

Then when I generate that pdfOutput, in my code, I changed

var pdfOutput = doc.output();

to

var pdfOutput = doc.output(“blob”);

and it worked. I hope this post is able to help out others experiencing the same issues.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!