Mandeep Singh Mandeep Singh - 1 year ago 721
Javascript Question

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 ='#idOfSVG').select("svg").attr("version", 1.1).attr("xmlns", "").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'
canvas.width = 500;
canvas.height = 500;

Then i added the same into the content.

Also when i used

My div
gets deleted from the DOM.

Any help will be highly appreciated !!

Answer Source

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' : 

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 !!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download