Search code examples
javascriptjqueryhtmlpdf-generationjspdf

HTML image to pdf convertor in javascript


HTML CODE:

<img class="imagepdf "src="www.images.com/someimage" alt="Smiley face" height="42" width="42">

I want to convert this image to pdf format. I am using jspdf() for this but i am not getting my output ?Can someone give me live example on fiddle for pdf conversion for chrome.


Solution

  • Here is code from it's github site

    var getImageFromUrl = function(url, callback) {
        var img = new Image();
    
        img.onError = function() {
            alert('Cannot load image: "'+url+'"');
        };
        img.onload = function() {
            callback(img);
        };
        img.src = url;
    }
    
    
    var createPDF = function(imgData) {
        var doc = new jsPDF();
    
    
    
        doc.addImage(imgData, 'JPEG', 10, 10, 50, 50, 'monkey');
        doc.addImage('monkey', 70, 10, 100, 120); // use the cached 'monkey' image, JPEG is optional regardless
    
    
    
        doc.output('datauri');
    }
    
    getImageFromUrl('thinking-monkey.jpg', createPDF);
    

    If you are working in chrome security restrictions that prevent it from loading images from a url so just add this line and it will be working fine
    img.crossOrigin = " ";
    It will be fine for chrome alse