我有一个下载 PDF 的代码。在我的本地主机上,正在下载 PDF 并显示一切正常:
但是当我将代码上传到生产环境时,PDF 就像那样(不显示图中的图例和 %:
这是在 PDF 中打印图形和图例的代码:
import _ from "lodash";
import { createCanvas, loadImage } from "canvas";
import * as ChartJs from "chart.js";
import ChartDataLabels from "chartjs-plugin-datalabels";
ChartJs.register(ChartDataLabels);
async function getConformityChart(req, res) {
const { c, nc, na, si } = req.query;
const values = [Number(c), Number(nc), Number(na), Number(si)];
let total = !si
? values[0] + values[1] + values[2]
: values[0] + values[1] + values[2] + values[3];
const data = {
labels: [
"Conforme",
"Não aplicável",
"Em observação",
"Orientação Inicial",
],
datasets: [
{
label: "Conformity DataSet",
data: [c || 0, na || 0, nc || 0, si || 0],
backgroundColor: ["#00c77c", "#5f7da3", "#fe8f24", "#1755c9"],
},
],
};
const chartJsOptions = {
type: "doughnut",
data: data,
options: {
devicePixelRatio: 1,
animation: false,
responsive: false,
events: [],
elements: {
arc: {
borderWidth: 0,
},
},
plugins: {
legend: {
position: "bottom",
labels: {
boxWidth: 20,
padding: 30,
color: "#555",
font: {
size: 20,
weight: "500",
},
},
},
datalabels: {
formatter: (val, ctx) => {
const perc = val / total;
return perc < 0.03 ? "" : `${Math.round(perc * 100, 1)}%`;
},
color: "#fff",
font: {
size: 22,
weight: "700",
},
},
},
},
};
const canvas = createCanvas(600, 400);
const ctx = canvas.getContext("2d");
const el = { getContext: () => ctx };
const chart = new ChartJs.Chart(el, chartJsOptions);
const tempBuf = await canvas.toBuffer("image/png", {
compressionLevel: 6,
filters: canvas.PNG_ALL_FILTERS,
});
res.writeHead(200, {
"Content-Type": "image/png",
"Content-Length": tempBuf.length,
});
res.end(tempBuf);
}
export default {
getConformityChart,
};
我不知道为什么在生产服务器上会发生这种情况,但是当我在本地服务器上这样做时,它工作正常。 任何人都可以帮助我吗?谢谢!