Search code examples
imagehtml5-canvasbase64jspdftodataurl

How to get base64 image data without call canvas toDataURL?


I'm on a project which requires to support ie9 or ie10.
I'm using d3.js for data visualization.
Now I need to provide a function to export the chart as pdf.
I have been investigate into possible solutions. It seems that canvas + jsPdf is the way to go, below is some code I write.
But the problem is that when toDataURL gets called, it will cause security errors on IE9 and IE10. So I'm wondering if there's some work around to get base64 image data without using canvas since jsPdf only needs base64 image data???

  1. createObjectURL to the root svg element

    svgElement = $('svg').get(0); 
    serializer = new XMLSerializer();
    str = serializer.serializeToString(svgElement);
    
    DOMURL = window.URL || window.webkitURL || window;
    url = DOMURL.createObjectURL(new Blob([str], {type: 'image/svg+xml;charset=utf-8'}));
    
  2. draw an image using canvas

    img = new Image();
    img.onload = function(){
        ctx.drawImage(img, 0, 0);
    
        imgData = $canvas.get(0).toDataURL("image/jpeg");
        DOMURL.revokeObjectURL(url);  
    
        pdf = new jsPDF('landscape', 'pt', 1000, 800);
        pdf.addImage(imgData, 'JPEG', 0, 0);
        pdf.save('download.pdf');
    };
    img.src = url;
    

Solution

  • I finally find the solution which is to use an open source project: canvg