Recharts component to PNG

前端 未结 3 1980
梦如初夏
梦如初夏 2021-01-13 00:13

I currently have a Recharts component that I would like to export as a PNG file.

                    

        
3条回答
  •  孤街浪徒
    2021-01-13 01:00

    I was able to solve my problem by delving into the Recharts component. Recharts renders as an SVG under a wrapper so all I had to do was convert properly to save as both HTML or SVG

    // Exports the graph as embedded JS or PNG
    exportChart(asSVG) {
    
        // A Recharts component is rendered as a div that contains namely an SVG
        // which holds the chart. We can access this SVG by calling upon the first child/
        let chartSVG = ReactDOM.findDOMNode(this.currentChart).children[0];
    
        if (asSVG) {
            let svgURL = new XMLSerializer().serializeToString(chartSVG);
            let svgBlob = new Blob([svgURL], {type: "image/svg+xml;charset=utf-8"});
            FileSaver.saveAs(svgBlob, this.state.uuid + ".svg");
        } else {
            let svgBlob = new Blob([chartSVG.outerHTML], {type: "text/html;charset=utf-8"});
            FileSaver.saveAs(svgBlob, this.state.uuid + ".html");
        }
    }
    

    I am using FileSaver.js for the save prompt.

提交回复
热议问题