[英]Is there a way to convert react-chartjs-2 chart to pdf?
我正在使用一个名为 reactChartJs2 的库,并且有一个使图表可下载的建议,有没有办法将图表转换为 PDF 或任何其他格式?
这是您需要安装的使用 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"));
答案输出:这里
我收到一个错误,说pdfconverter
不是一个函数。 我只是在顶部添加了import jsPDF from "jspdf"
而不是const pdf = new pdfConverter("l", "pt");
.
我写了const pdf = new jsPDF("l", "pt");
现在它起作用了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.