[javascript] Add image in pdf using jspdf

I am using jspdf to convert an image into a PDF.

I have converted the image into a URI using base64encode. But the problem is that there are no errors or warnings shown in the console.

A PDF is generated with the text Hello World on it but no image is added in it.

Here is my code.

function convert(){
        var doc = new jsPDF();
        var imgData = 'data:image/jpeg;base64,'+ Base64.encode('Koala.jpeg');
        console.log(imgData);
        doc.setFontSize(40);
        doc.text(30, 20, 'Hello world!');
        doc.output('datauri');
        doc.addImage(imgData, 'JPEG', 15, 40, 180, 160);

    }

This question is related to javascript jquery image jspdf

The answer is


if you have

ReferenceError: Base64 is not defined

you can upload your file here you will have something as :

data:image/jpeg;base64,/veryLongBase64Encode....

on your js do :

var imgData = 'data:image/jpeg;base64,/veryLongBase64Encode....'
var doc = new jsPDF()

doc.setFontSize(40)
doc.addImage(imgData, 'JPEG', 15, 40, 180, 160)

Can see example here


No need to add any extra base64 library. Simple 5 line solution -

var img = new Image();
img.src = path.resolve('sample.jpg');

var doc = new jsPDF('p', 'mm', 'a3');  // optional parameters
doc.addImage(img, 'JPEG', 1, 2);
doc.save("new.pdf");

I had the same issue with Base64 not being defined. I went to an online encoder and then saved the output into a variable. This probably is not ideal for many images, but for my needs it was sufficient.

function makePDF(){
    var doc = new jsPDF();
    var image = "data:image/png;base64,iVBORw0KGgoAA..";
    doc.addImage(image, 'JPEG', 15, 40, 180, 160);
    doc.save('title');
}

The above code not worked for me. I found new solution :

 var pdf = new jsPDF();
 var img = new Image;
 img.onload = function() {
     pdf.addImage(this, 10, 10);
     pdf.save("test.pdf");
 };
 img.crossOrigin = "";  
 img.src = "assets/images/logo.png";

This worked for me in Angular 2:

var img = new Image()
img.src = 'assets/sample.png'
pdf.addImage(img, 'png', 10, 78, 12, 15)

jsPDF version 1.5.3

assets directory is in src directory of the Angular project root


I find it useful.

var imgData = 'data:image/jpeg;base64,verylongbase64;'

var doc = new jsPDF();

doc.setFontSize(40);
doc.text(35, 25, "Octonyan loves jsPDF");
doc.addImage(imgData, 'JPEG', 15, 40, 180, 180);

http://mrrio.github.io/jsPDF/


In TypeScript, you can do:

private getImage(imagePath): ng.IPromise<any> {
    var defer = this.q.defer<any>();
    var img = new Image();
    img.src = imagePath;
    img.addEventListener('load',()=>{
       defer.resolve(img);
    });


    return defer.promise;
} 

Use the above function to getimage object. Then the following to add to pdf file:

pdf.addImage(getImage(url), 'png', x, y, imagewidth, imageheight);

In plain JavaScript, the function looks like this:

function (imagePath) {
        var defer = this.q.defer();
        var img = new Image();
        img.src = imagePath;
        img.addEventListener('load', function () {
            defer.resolve(img);
        });
        return defer.promise;
    };

Though I'm not sure, the image might not be added because you create the output before you add it. Try:

function convert(){
    var doc = new jsPDF();
    var imgData = 'data:image/jpeg;base64,'+ Base64.encode('Koala.jpeg');
    console.log(imgData);
    doc.setFontSize(40);
    doc.text(30, 20, 'Hello world!');
    doc.addImage(imgData, 'JPEG', 15, 40, 180, 160);
    doc.output('datauri');
}

You defined Base64? If you not defined, occurs this error:

ReferenceError: Base64 is not defined


For result in base64, before convert to canvas:

var getBase64ImageUrl = function(url, callback, mine) {

                    var img = new Image();

                    url = url.replace("http://","//");

                    img.setAttribute('crossOrigin', 'anonymous');

                    img.onload = function () {
                        var canvas = document.createElement("canvas");
                        canvas.width =this.width;
                        canvas.height =this.height;

                        var ctx = canvas.getContext("2d");
                        ctx.drawImage(this, 0, 0);

                        var dataURL = canvas.toDataURL(mine || "image/jpeg");

                        callback(dataURL);
                    };
                    img.src = url;

                    img.onerror = function(){

                        console.log('on error')
                        callback('');

                    }

            }

   getBase64ImageUrl('Koala.jpeg', function(img){
         //img is a base64encode result
         //return img;
          console.log(img);

          var doc = new jsPDF();
              doc.setFontSize(40);
              doc.text(30, 20, 'Hello world!');
              doc.output('datauri');
              doc.addImage(img, 'JPEG', 15, 40, 180, 160);
    });

First you need to load the image, convert data, and then pass to jspdf (in typescript):

loadImage(imagePath): ng.IPromise<any> {
    var defer = this.q.defer<any>();
    var img = new Image();
    img.src = imagePath;
    img.addEventListener('load',()=>{
            var canvas = document.createElement('canvas');
            canvas.width = img.width;
            canvas.height = img.height;

            var context = canvas.getContext('2d');
            context.drawImage(img, 0, 0);

            var dataURL = canvas.toDataURL('image/jpeg');

            defer.resolve(dataURL);
    });

    return defer.promise;
}

generatePdf() {
    this.loadImage('img/businessLogo.jpg').then((data) => {
        var pdf = new jsPDF();
        pdf.addImage(data,'JPEG', 15, 40, 180, 160);
        pdf.text(30, 20, 'Hello world!');
        var pdf_container =  angular.element(document.getElementById('pdf_preview'));
        pdf_container.attr('src', pdf.output('datauristring'));
    });
}

maybe a little bit late, but I come to this situation recently and found a simple solution, 2 functions are needed.

  1. load the image.

    function getImgFromUrl(logo_url, callback) {
        var img = new Image();
        img.src = logo_url;
        img.onload = function () {
            callback(img);
        };
    } 
    
  2. in onload event on first step, make a callback to use the jspdf doc.

    function generatePDF(img){
        var options = {orientation: 'p', unit: 'mm', format: custom};
        var doc = new jsPDF(options);
        doc.addImage(img, 'JPEG', 0, 0, 100, 50);}
    
  3. use the above functions.

    var logo_url = "/images/logo.jpg";
    getImgFromUrl(logo_url, function (img) {
        generatePDF(img);
    });
    

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to image

Reading images in python Numpy Resize/Rescale Image Convert np.array of type float64 to type uint8 scaling values Extract a page from a pdf as a jpeg How do I stretch an image to fit the whole background (100% height x 100% width) in Flutter? Angular 4 img src is not found How to make a movie out of images in python Load local images in React.js How to install "ifconfig" command in my ubuntu docker image? How do I display local image in markdown?

Examples related to jspdf

How to set image to fit width of the page using jsPDF? how to use html2canvas and jspdf to export to pdf in a proper and simple way Exporting PDF with jspdf not rendering CSS Where to change default pdf page width and font size in jspdf.debug.js? Export HTML table to pdf using jspdf How to export the Html Tables data into PDF using Jspdf Export HTML page to PDF on user click using JavaScript jsPDF multi page PDF with HTML renderer Add image in pdf using jspdf Generate pdf from HTML in div using Javascript