Search code examples
javascriptjqueryimagejspdf

pdf is not generated using jspdf


Code:

var doc = jsPDF();
var getImageFromUrl = function(url, callback) {
  var img = new Image();

  img.onError = function() {
    alert('Cannot load image: "'+url+'"');
  };
  img.onload = function() {
    callback(img);
  };
  img.src = url;
}
var createPDF = function(imgData) {




  doc.addImage(imgData, 'JPEG', 10, 10, 50, 50, 'monkey'); 
  doc.addPage(); 

}
var image = "some image url"
 getImageFromUrl(image, createPDF);
doc.text(35, 25, "Some extra text")
 doc.output('datauri');

No images are shown in pdf output? How to solve this issue? As the image is generating inside a function, will this be the reason for not generating the image? I want last 2 lines of code outside the function createPDF


Solution

  • you have too put last two line inside the callback function in order to work. If you don't want this than you could use some flag.

    var flag=0
        var createPDF = function(imgData) {
    
    
    
    
      doc.addImage(imgData, 'JPEG', 10, 10, 50, 50, 'monkey'); 
      doc.addPage(); 
    
    
     if(flag==0)
        doc.output('datauri');
    
    
    
    }
    
    
       var image = "some image url"
      flag =1 ;
         getImageFromUrl(image, createPDF);
        doc.text(35, 25, "Some extra text")
    
    
    
         flag=0;