jsPDF与Cordova - 添加图像 [英] jsPDF with Cordova - Adding images

查看:889
本文介绍了jsPDF与Cordova - 添加图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用jsPDF库生成PDF(),似乎表明有一个问题的jsPDF显示图像在科尔多瓦(见评论),但作者从来没有张贴的跟进。有没有人能够使用jsPDF与Cordova和正确添加图像到生成的PDF?我的代码如下,任何帮助或建议将非常感谢。

  function demoReceipt(){
var img =新图片();

img.onError = function(){
alert('Can not 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();

//下一步保存到设备的本地文件系统
//需要cordova插件添加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 ){
var fileEntry = entry;
console.log(entry);

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

console.log(写入文件);
writer.write(pdfOutput );
},function(error){
console.log(error);
});

},function(error){
console.log(error);
});
},function(error){
});
},function(event){
console.log(evt.target.error.code);
});
}


解决方案

从此博文: https://coderwall.com/p/nc8hia 。在该帖子中使用的0.90版本和我从 https://使用的版本之间似乎存在显着差异github.com/MrRio/jsPDF 但是解决方案几乎是一样的。
首先,在MyRio的版本中,您可以获得PDF生成工作,而无需修复Igor的帖子中提到的Blob问题。所有你需要的是通过调用doc.ouput()生成PDF输出,然后使用Cordova文件系统插件保存它。所以我想我不必创建Blob(这是我错了)。

Igor(从coderwall帖子)回复我的问题,一些额外的代码,但当我搜索jspdf。 js文件从MyRio版本,我看到代码(更紧凑的版本)已经在代码行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创建代码是在这段代码。所以我注释掉了返回新的Blob([ab],{类型:应用程序/ 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(在FF13 WinXP上测试)
console.debug (情况3);
return new Blob([ab],{type:application / pdf});

}
else
{
//我们被拧了,blob构造函数完全不受支持
console.debug(Errore);
}
}

然后当我生成pdfOutput时,我更改了

  var pdfOutput = doc.output(); 

  var pdfOutput = doc.output(blob); 


我希望这篇文章能够帮助遇到相同问题的其他人。


I am trying to generate a PDF using the jsPDF library (https://github.com/MrRio/jsPDF) from within a mobile Cordova app. I am currently testing the app on an Android 4.0.4 device but it also needs to run on Windows mobile 8. The text in the PDF document is shown correctly however any images are scrambled. See image below

I did find this page (https://coderwall.com/p/nc8hia) that seemed to indicate there is a problem with jsPDF displaying images in Cordova (see comments) but the author never posted the follow-up. Has anyone been able to use jsPDF with Cordova and properly add images to the generated PDF? My code is below, any assistance or advice would be greatly appreciated.

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

解决方案

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.

这篇关于jsPDF与Cordova - 添加图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆