使用Cordova的jsPDF - 添加图片

5
我正在尝试使用jsPDF库(https://github.com/MrRio/jsPDF)在移动Cordova应用程序中生成PDF。我目前正在Android 4.0.4设备上测试该应用程序,但它还需要在Windows mobile 8上运行。PDF文档中的文本显示正确,但是任何图像都会变形。请参见下面的图片:

Image of PDF that was generated

我发现了这个网页(https://coderwall.com/p/nc8hia),它似乎表明jsPDF在Cordova中显示图像存在问题(见评论),但作者从未发布后续内容。有人能够在Cordova中使用jsPDF并正确地将图像添加到生成的PDF中吗?我的代码如下,任何帮助或建议将不胜感激。
function demoReceipt() {
    var img = new Image();

    img.onError = function() {
        alert('Cannot load image: "' + url + '"');
    };
    img.onload = function() {
        createPdf2(img);
    };
    img.src = 'img/testlogo.png';
}



function createPdf2(myLogo) {
    //  var doc = new jsPDF('p', 'pt', 'jontype');

    var doc = new jsPDF('p', 'pt', 'letter');

    doc.setProperties({
        title : 'Fueling Receipt',
        author : 'Jon Hoffman',
        creater : 'Jon Hoffman'
    });

    doc.addImage(myLogo, 'PNG', 5, 5, 140, 30);
    doc.setFontSize(12);
    doc.text(10, 40, 'Sample PDF receipt');
    doc.setFontSize(8);
    doc.text(10, 45, 'Smaller text - new');

    var pdfOutput = doc.output();

    //NEXT SAVE IT TO THE DEVICE'S LOCAL FILE SYSTEM
    //Requires  cordova plugin add org.apache.cordova.file
    console.log("file system...");
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {

        console.log(fileSystem.name);
        console.log(fileSystem.root.name);
        console.log(fileSystem.root.fullPath);

        fileSystem.root.getDirectory("myPDFs", {
            create : true,
            exclusive : false
        }, function(dir) {

            fileSystem.root.getFile("myPDFs/test.pdf", {
                create : true
            }, function(entry) {
                var fileEntry = entry;
                console.log(entry);

                entry.createWriter(function(writer) {
                    writer.onwrite = function(evt) {
                        console.log("write success");
                    };

                    console.log("writing to file");
                    writer.write(pdfOutput);
                }, function(error) {
                    console.log(error);
                });

            }, function(error) {
                console.log(error);
            });
        }, function(error) {
        });
    }, function(event) {
        console.log(evt.target.error.code);
    });
}
1个回答

5
我在这篇博客文章的帮助下解决了问题:https://coderwall.com/p/nc8hia。该文章中使用的0.90版本与我从https://github.com/MrRio/jsPDF下载的版本之间似乎存在显着差异,但解决方案基本相同。 首先,在MyRio版本中,您可以通过调用“doc.output()”生成PDF输出并使用Cordova文件系统插件保存PDF生成而无需修复Igor在其文章中指出的Blob问题。因此,我认为我不需要创建Blob(这就是我错了的地方)。
Igor(来自coderwall帖子)通过一些附加代码回答了我的问题,但当我搜索MyRio版本的jspdf.js文件时,我发现代码(更紧凑的版本)已经在代码的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" });

但是我还注意到,Igor在他的初始帖子中修复的Blob创建代码位于该代码块的结尾。因此,我注释掉了“return new Blob([ab], { type:”application/pdf“});”一行,并插入了以下来自Igor帖子的代码,只是稍微更改了变量名称:

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");
       }
 }

当我生成pdfOutput时,我在代码中进行了更改:

var pdfOutput = doc.output();

to

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

它有效了。我希望这篇文章能够帮助到其他遇到同样问题的人。


将生成PDF的代码从var pdfOutput = doc.output();更改为var pdfOutput = doc.output(“blob”);,可以解决在jsPDF版本1.0.209中图片未包含在PDF中的问题。非常感谢! - Clawish
我可以在哪里调用这个blob的try, catch块 - 在doc.addImage(myLogo,'PNG',5,5,140,30);行之前? - Chintan Khetiya
我能够在没有try-catch块的情况下运行。我只需使用“blob”作为变量pdfoutput = doc.output(“blob”);它可以正常工作。 - Chintan Khetiya

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接