Search code examples
javascriptreactjsreact-componentreact-chartjsreact-pdf

Best library to convert React components to PNG/PDF?


I have implemented a react web app which creates charts using Chart.js library. Now I want to convert this charts to PNG/PDF formats and save them. I came across a lot of libraries but facing some or the other issue with them. Can you suggest which library would be perfect for this kind of work ?

App.js

class CreateChart extends Component {
// call to get chartData object
    render() {
        return (
          <div className="App">
            <header className="App-header">
              REACT CHARTS
            </header>
                <CreateChart chartData={this.state.chartData} />
          </div>
        );
      }
}

Chart.js

class CreateChart extends Component {
    componentDidMount() {
            this.myChart = new Chart(
                this.chartRef.current,
                this.props.chartData
            );
    }
    
    render() {
           return <canvas ref={this.chartRef} />
    }
}

Solution

  • I suggest you to add an id on your html element (let's say topdf) :

    render() { return <canvas id="topdf" ref={this.chartRef} /> }}.
    

    Then you can use the html2canvas library to get the image dataURI of your charts. After that, you can use the jsPDF library to make a document and use the .addImage(your_image_data_URI) function.

    Exemple :

    html2canvas(document.querySelector("#topdf"), { 
          scale: 3, // use the desired scale
          allowTaint: true,
          useCORS: true
        }).then(canvas => { 
    
          // Your IMAGE_DATA_URI
          var imgData = canvas.toDataURL('image/jpeg');
    
          // Make pdf
          var doc = new jsPDF({ options });
    
          // add image
          doc.addImage(imgData, 'JPEG');
    
          // Save document
          doc.save('charts.pdf'); 
    
          // ....
    

    This only work onInit runtime, or after runtime.