Search code examples
javascriptsvghtml5-canvaspdfmake

How to handle SVG and canvas in pdfmake & html2pdfmake


I am using html2pdfmake to convert a div to pdf. My div contains tables and also contains some svg charts. But i am not getting the svg into the pdf. I tried converting it using base64 but is paste the base64 code into the pdf.

I converted my svg to base64 like :

var html = d3.select('#idOfSVG').select("svg").attr("version", 1.1).attr("xmlns", "http://www.w3.org/2000/svg").node().parentNode.innerHTML;
var imgsrc = 'data:image/svg+xml;base64,'+ btoa(html);
var base_image = new Image();
base_image.src = imgsrc;
canvas = document.createElement('canvas');
canvas.id = 'canvas'
document.body.appendChild(canvas);
canvas.width = 500;
canvas.height = 500;
canvas.getContext('2d').drawImage(base_image,0,0);

Then i added the same into the content.

Also when i used ParseHtml(content,document.getElementById("myPDFDiv"))

My div myPDFDiv gets deleted from the DOM.

Any help will be highly appreciated !!


Solution

  • You can use html2pdfmake, it iterates all the elements in the div and make JSON for the same which you can use with pdfmake.

    You can add SVG support by adding a switch case for SVG like :

    Case 'SVG' : 
     addImage(cnt,e);
    
    function addImage (cnt,e) {
                //Serialize the svg element and then put it in a canvas
    //Then update the cnt object
    var url = canvas.toDataURL('image/png');
            cnt.push({image: url,
                  width: 200,
                  height: 250,
                  margin: [ 20, 0, 0, 0 ]
            });
    
    
    }
    

    Hope it helps !!