wkhtmltopdf -如何从python文件加载变量到HTML文件中的脚本标签



我正在使用pdfkit和wkhtmltopdf在python中生成PDF文件。我已经创建了一个python字典,并传递了我想要在HTML文件的正文中显示的所有变量,它工作得很好。现在我已经添加了谷歌图表,为了做到这一点,我在头部标签中添加了一个脚本标签,它工作了,我可以看到PDF文件中的图表。但是图表的数据是硬编码的,我想把数据作为一个变量从python传递过来。所以我的问题是我如何将变量传递给脚本标签。

这是我的代码。

<head>
<meta charset="utf-8" />
<script src="http://www.gstatic.com/charts/loader.js"></script>
<script>
function init() {
google.charts.load("44", { packages: ["corechart"] });
var interval = setInterval(function () {
if (
google.visualization !== undefined &&
google.visualization.DataTable !== undefined &&
google.visualization.AreaChart !== undefined
) {
clearInterval(interval);
window.status = "ready";
drawChart();
}
}, 100);
}
function drawChart() {
// Define the chart to be drawn.
var data = google.visualization.arrayToDataTable([
["Price", "Size"],
[50, 7],
[60, 8],
[70, 8],
[80, 9],
[90, 9],
[100, 9],
[110, 10],
[120, 11],
[130, 14],
[140, 14],
[150, 15],
]);
var chart = new google.visualization.AreaChart(
document.getElementById("myChart")
);
chart.draw(data, null);
}
</script>
</head>
<body onload="init()">
<div style="width: 950px; height: 500px" id="myChart"></div>
</body>

我试图传递它,就像我在body标签中使用的那样,但它不起作用。

首先,您可以使用google的load语句返回的承诺,
而不是间隔循环。

google.charts.load("44", {
packages: ["corechart"]
}).then(drawChart);

其次,我不懂python。

,但你想做的是将数据作为json写到一个单独的页面的主体。
然后使用本页上的fetch获取该数据并将其显示在图表中。

我认为你可以在python中使用dumps之类的东西将json写入单独的页面。

google.charts.load("44", {
packages: ["corechart"]
}).then(drawChart);
function drawChart() {
fetch('url path to separate page where python data is written').then((response) => response.json()).then((jsonData) => {
var data = google.visualization.arrayToDataTable(jsonData);
var chart = new google.visualization.AreaChart(
document.getElementById("myChart")
);
chart.draw(data, null)
});
}

我这样解决了这个问题。我在python

中以这种方式添加了数组
output_text = template.render(context, data1=data1, data2=data2, data3=data3)

,并在python pdfkit选项中添加了延迟,以便它可以渲染图形

options = {
"page-size": "A4",
"encoding": "UTF-8",
"javascript-delay": 3000,
}

在HTML脚本标签中但我将它作为字符串而不是数组所以我使用eval()

eval("{{data1}}")

这就是我解决问题的方法。

最终工作代码:

<script>
function init() {
google.load("visualization", "44", { packages: ["corechart"] });
var interval = setInterval(function () {
if (
google.visualization !== undefined &&
google.visualization.DataTable !== undefined &&
google.visualization.AreaChart !== undefined
) {
clearInterval(interval);
window.status = "ready";
var data1 = google.visualization.arrayToDataTable(eval("{{data1}}"));
var chart1 = new google.visualization.AreaChart(
document.getElementById("myChart1")
);
chart1.draw(data1, null);
}
}, 1000);
}
</script>
<body onload="init()">
<div class="graph-style" id="myChart1"></div>
</body>

最新更新