Neh
Neh

Reputation: 33

Image is not getting displayed when adding image to a PDF

I am trying to create PDF with Image. I have URL of Image as below:

var url = "https://firebasestorage.googleapis.com/v0/b/dicom-poc.appspot.com/o/images%2FNiouCzjBYna8Wx1VO2x3UST5tDc2%2F2020-10-07%2F05%3A03%3A58%2Fvisualization%2FL-CC.png?alt=media&token=dce8859a-3427-432b-8176-590e9569aad9"

and my code is here:

var pdf = new jsPDF();
var img = new Image();
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
img = document.createElement('img');
img.src = url;
img.onload = function(){
   canvas.height = img.height;
   canvas.width = img.width;
   var dataURL = canvas.toDataURL('image/png')
   var base64 = dataURL.replace(/^data:.+;base64,/, '');  
   pdf.text("Hi");
   pdf.addImage(base64,'PNG',5,5,50,50);
   pdf.save("download.pdf");
}

After running above code PDF is getting downloaded successfully with text "Hi" but image is not there. I have tried multiple solutions suggested by people but no result. Could you please guide me for same.

Thanks in advanace!

Upvotes: 3

Views: 1215

Answers (1)

Musa
Musa

Reputation: 97682

You did not draw anything on the canvas.

var pdf = new jsPDF();
var img = new Image();
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
img = document.createElement('img');
img.src = url;
img.onload = function(){
   canvas.height = img.height;
   canvas.width = img.width;
   ctx.drawImage(img, img.width, img.width);
   var dataURL = canvas.toDataURL('image/png')
   var base64 = dataURL.replace(/^data:.+;base64,/, '');  
   pdf.text("Hi");
   pdf.addImage(base64,'PNG',5,5,50,50);
   pdf.save("download.pdf");
}

Upvotes: 2

Related Questions