How to convert/save d3.js graph to pdf/jpeg

前端 未结 4 1282
执笔经年
执笔经年 2020-11-27 15:13

I\'m working on a client-side/javascript function to save or convert an existing D3-SVG graph into a file. I\'ve searched a lot and found some recommendations, mainly using

4条回答
  •  孤独总比滥情好
    2020-11-27 15:57

    As pointed out by @Premasagar in this comment on this question Convert SVG to image (JPEG, PNG, etc.) in the browser

    If the borwser supports both SVG and canvas you can use this technique https://svgopen.org/2010/papers/62-From_SVG_to_Canvas_and_Back/index.html

    function importSVG(sourceSVG, targetCanvas) {
        // https://developer.mozilla.org/en/XMLSerializer
        svg_xml = (new XMLSerializer()).serializeToString(sourceSVG);
        var ctx = targetCanvas.getContext('2d');
    
        // this is just a JavaScript (HTML) image
        var img = new Image();
        // http://en.wikipedia.org/wiki/SVG#Native_support
        // https://developer.mozilla.org/en/DOM/window.btoa
        img.src = "data:image/svg+xml;base64," + btoa(svg_xml);
    
        img.onload = function() {
            // after this, Canvas’ origin-clean is DIRTY
            ctx.drawImage(img, 0, 0);
        }
    }
    

提交回复
热议问题