admin管理员组

文章数量:1401849

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

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);
Share Improve this question edited Jul 16, 2014 at 16:19 Jason Parker asked Jul 15, 2014 at 22:46 Jason ParkerJason Parker 652 silver badges6 bronze badges 1
  • Just a note: btoa() is not supported in older browsers and most of IE. – ArtOfCode Commented Jul 16, 2014 at 17:32
Add a ment  | 

2 Answers 2

Reset to default 4

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.

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 plain 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.

本文标签: javascriptCannot add image to pdf using jspdf Returns getJpegSize errorStack Overflow