如何在ChartJS中使用jsPDF将图表导出为PDF



我正在尝试将条形图下载到pdf,但无法运行
尝试将条形图下载为pdf格式。图表给了我很多问题。图形的java脚本,我试过了,但没有成功,请有人帮我解决

<div class="card">
<div class="header">
<h2>Bar Chart</h2>                            
</div>
<div class="body" id="myChart">
<div class="sales-bars-chart" style="height: 320px;"> </div>
</div>
</div>
const myChart = new chart(
document.getElementById('myChart'),
config
);
function downloadPDF(){
const convas = document.getElementById('myChart');
const canvasImage = convas.toDataURL('image/jpeg', 1.0);
console.log(canvasImage)
let pdf = new jsPDF();
pdf.setFontsize();
pdf.setFontsize(20);
pdf.addImage(canvasImage, 'jpeg', 15,15,280,150);
pdf.save('salerecoed.pdf');
}

这是带工作示例的代码笔。https://codepen.io/stockinail/pen/OJENbwM

需要一个额外的插件来为画布的背景上色,如CHARt.JS文档中所述https://www.chartjs.org/docs/latest/configuration/canvas-background.html:

const plugin = {
id: 'custom_canvas_background_color',
beforeDraw: (chart) => {
const {ctx} = chart;
ctx.save();
ctx.globalCompositeOperation = 'destination-over';
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, chart.width, chart.height);
ctx.restore();
}
};

必须将插件添加到图表配置中,如下所示:

const myChart = new Chart(ctx, {
type: 'bar',
plugins: [plugin], // <<--- adds plugin to color the background of the canvas
data: chartData
});

最新更新