【问题标题】:Is there a way to convert react-chartjs-2 chart to pdf?有没有办法将 react-chartjs-2 图表转换为 pdf?
【发布时间】:2020-01-14 15:43:08
【问题描述】:

我正在使用一个名为 reactChartJs2 的库,并且有人提议让图表可下载,有没有办法将图表转换为 PDF 或任何其他格式?

【问题讨论】:

    标签: reactjs charts react-chartjs


    【解决方案1】:

    这是使用 react-chartjs-2 的示例代码 你需要安装:

    npm i html2canvas
    

    和

    npm i jspdf
    

    代码:

    import React, { Component } from "react";
    import ReactDOM from "react-dom";
    import { Bar } from "react-chartjs-2";
    import html2canvas from "html2canvas";
    const pdfConverter = require("jspdf");
    
    class Chart extends Component {
      cData = {
        labels: ["L 1", "L 2", "L 3", "L 4", "L 5"],
        datasets: [
          {
            label: "Label",
            data: [100, 150, 123, 170, 162],
            backgroundColor: ["red", "green", "yellow", "blue", "orange", "red"]
          }
        ]
      };
    
      div2PDF = e => {
        /////////////////////////////
        // Hide/show button if you need
        /////////////////////////////
    
        const but = e.target;
        but.style.display = "none";
        let input = window.document.getElementsByClassName("div2PDF")[0];
    
        html2canvas(input).then(canvas => {
          const img = canvas.toDataURL("image/png");
          const pdf = new pdfConverter("l", "pt");
          pdf.addImage(
            img,
            "png",
            input.offsetLeft,
            input.offsetTop,
            input.clientWidth,
            input.clientHeight
          );
          pdf.save("chart.pdf");
          but.style.display = "block";
        });
      };
    
      render() {
        return (
          <div>
            <div className="div2PDF">
              <Bar
                data={this.cData}
                options={{
                  title: {
                    display: true,
                    text: "Chart to PDF Demo",
                    fontSize: 32
                  },
                  legend: {
                    display: true,
                    position: "right"
                  }
                }}
                height={200}
              />
            </div>
            <div>
              <button onClick={(e) => this.div2PDF(e)}>Export 2 PDF</button>
            </div>
          </div>
        );
      }
    }
    
    export default Chart;
    
    ReactDOM.render(<Chart />, document.getElementById("root"));
    

    答案输出:HERE

    【讨论】:

      【解决方案2】:

      我收到一条错误消息,提示 pdfconverter 不是函数。我刚刚添加 import jsPDF from "jspdf" 位于顶部,而不是 const pdf = new pdfConverter("l", "pt");。

      我写了const pdf = new jsPDF("l", "pt");,现在它可以工作了。

      【讨论】:

        猜你喜欢
        • 2019-09-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-18
        • 1970-01-01
        • 2022-07-06
        • 1970-01-01
        相关资源
        最近更新 更多