Jason Parker
Jason Parker

Reputation: 65

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

Upvotes: 3

Views: 7969

Answers (2)

msoltys
msoltys

Reputation: 111

I had this same error, but just resolved it. I don't think my issue was the same as Jason's but perhaps it will help others with an issue similar to mine. My issue resulted from me specifying 'img' rather than 'image' in:

var imgData = canvas.toDataURL("img/jpeg", 1.0);

This took me a little trial and error to figure out, because the console did not complain about "img" and I am used to abbreviating image as img in other contexts, so I must have just fat fingered it. In a similar vein you also need to make sure you specify jpeg rather than jpg.

Upvotes: 1

Samir
Samir

Reputation: 374

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.

Upvotes: 4

Related Questions