4

I'm trying to export a <svg> element sitting in DOM to a PDF file, generated on client side. I tried with different libraries, and pdfmake is so close to what I want. Any working example with this library or any other library would be helpful.

    downloadPdf = function() {
        //var docDefinition = { content: 'This is an sample PDF'};
        var html = d3.select("svg")
          .attr("version", 1.1)
          .attr("xmlns", "http://www.w3.org/2000/svg")
          .node().parentNode.innerHTML;
        console.log(btoa(html));
        var imgsrc = 'data:image/svg+xml;base64,'+btoa(html);
        var docDefinition = {content: [{image: imgsrc}]}
        pdfMake.createPdf(docDefinition).open('Sample.pdf');    
   }    

1 Answer 1

4

pdfMake does not support vector graphics. In this case you need to take the bypass through canvas with fabricJS or canvg, once you've imagery you can place it in pdfMake

// Create fabric instance
var canvas = new fabric.StaticCanvas( undefined, {
    width: 500,
    height: 500,
} );

// Load SVG document; add to canvas;
fabric.parseSVGDocument(<svg element>,function(objects, options) {
    var g = fabric.util.groupSVGElements( objects, options );
    var data = "";

    // ADD ELEMENTS
    canvas.add( g );

    // EXPORT TO DATA URL
    data = canvas.toDataURL({
        format: "jpeg"
    });

    console.log(data);

// REVIVER
},function(svg,group) {
    // possiblitiy to filter the svg elements or adapt the fabric object
});
1
  • 1
    I wish I could upvote more than once. Thank you very much for pointing me to this solution. Actually I tried both of the plugins. With canvg, one of the labels in highchart piechart was overlapping a value. Tried fabricJS, it was better. Finally I used a simpler solution from this fiddle: jsfiddle.net/willkoehler/1p81fbzs It is possible to have some pitfalls, but works for my case just fine.
    – lyubeto
    Commented Jan 26, 2017 at 14:27

Not the answer you're looking for? Browse other questions tagged or ask your own question.