Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot add image to pdf using jspdf. Returns getJpegSize error

I am having trouble adding an image to a pdf using jspdf. The error I get reads as follows: Error: getJpegSize could not find the size of the image

Here is the code:

$scope.makePDF = function () {
    var imgData = 'data:image/jpeg;base64,' + btoa('../img/myImage.jpg');
    var doc = new jsPDF();
    doc.setFontSize(12);
    doc.addImage(imgData, 'JPEG', 15, 40, 180, 180);
like image 282
Jason Parker Avatar asked Dec 09 '25 20:12

Jason Parker


1 Answers

The problem here is that you had not loaded the image data. "btoa" creates a Base64 encoded ASCII string from '../img/myImage.jpeg'.

To get the image data you need create image data from canvas or from a physical image.

Change

var doc = new jsPDF();
doc.setFontSize(12);
doc.addImage(imgData, 'JPEG', 15, 40, 180, 180);

To

var img = new Image(),
    canvas = document.createElement("canvas"),
    ctx = canvas.getContext("2d");

img.onload = function () {
    ctx.drawImage(img, 0, 0 );
    var imgData = canvas.toDataURL('image/jpeg');
    var doc = new jsPDF();
    doc.setFontSize(12);
    doc.addImage(imgData, 'JPEG', 15, 40, 180, 180);
}

img.src = '../img/myImage.jpg';

I hope it helps.

like image 122
Samir Avatar answered Dec 11 '25 10:12

Samir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!