wkhtmltopdf chatjs

9次阅读

共计 2335 个字符,预计需要花费 6 分钟才能阅读完成。

背景
前文 提到了项目中引用了 https://www.chartjs.org/,几经尝试一度以为它们互不兼容。百度谷歌了许久,又自己尝试了多次。终于还是找到了它们配合的点。
wkhtmltopdf
这里面使用的版本必须是 https://github.com/wkhtmltopdf/wkhtmltopdf/releases/0.12.2.1
chatjs
好多文章说 chatjs 必须使用 2.6.0 版本,但是实测 2.5.x 和 2.7.x 都可以通过。下面是一个可以成功在 pdf 中显示的代码示例:
<html>
<head>
<title>chartJS PDF</title>
<script src=”https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js”></script>
</head>
<body>

<!– 必须使用设置了宽度和高度的 div 包住的 canvas 导出 pdf 时候才会显示 –>
<div style=”width: 200px;height: 500px;”>
<canvas id=”myChart” width=”200px” height=”500px” style=”width: 200px; height: 500px;”></canvas>
</div>

<!– 这种在 div 外面的即使设置了宽度高度也不会在 pdf 中显示 –>
<canvas id=”badChart” width=”200px” height=”500px” style=”width: 200px; height: 500px;”></canvas>

<script>

// 官方示例中添加了这段代码 去掉后 pdf 不显示
Function.prototype.bind = Function.prototype.bind || function (thisp) {
var fn = this;
return function () {
return fn.apply(thisp, arguments);
};
};

var ctx = document.getElementById(“myChart”).getContext(‘2d’);

new Chart(ctx, {
type: ‘bar’,
data: {
labels: [“Red”, “Blue”, “Yellow”, “Green”, “Purple”, “Orange”],
datasets: [{
label: ‘# of Votes’,
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
‘rgba(255, 99, 132, 0.2)’,
‘rgba(54, 162, 235, 0.2)’,
‘rgba(255, 206, 86, 0.2)’,
‘rgba(75, 192, 192, 0.2)’,
‘rgba(153, 102, 255, 0.2)’,
‘rgba(255, 159, 64, 0.2)’
],
borderColor: [
‘rgba(255,99,132,1)’,
‘rgba(54, 162, 235, 1)’,
‘rgba(255, 206, 86, 1)’,
‘rgba(75, 192, 192, 1)’,
‘rgba(153, 102, 255, 1)’,
‘rgba(255, 159, 64, 1)’
],
borderWidth: 1
}]
}
// 这里的 option 设置对 pdf 没有影响
});

var ctxm = document.getElementById(“badChart”).getContext(‘2d’);
new Chart(ctxm, {
type: ‘bar’,
data: {
labels: [“NO”,”AF”,”GM”,”DA”],
datasets: [{
label: ”,
// backgroundColor: chartColors(), 这样的自定义获取颜色的函数也会影响在 pdf 中显示
backgroundColor: [
‘rgba(255, 99, 132, 0.2)’,
‘rgba(54, 162, 235, 0.2)’,
‘rgba(255, 206, 86, 0.2)’,
‘rgba(75, 192, 192, 0.2)’,
‘rgba(153, 102, 255, 0.2)’,
‘rgba(255, 159, 64, 0.2)’
],
data: [1,2,3,4]
}]
}
});

</script>
</body>
</html>
样式调整

在实际导出时会遇到 div 间出现了半页的空白,这是由于 div 设置了 overflow-x:visible 样式,将其调整为默认即可。如果影响页面显示,建议给导出单独做一个页面。
表格过宽导致显示被截断,是由于设置了 white-space:nowrap 样式,将其调整为默认即可。如果影响页面显示,建议给导出单独做一个页面。
表格的内容过多大于一页时会出现在第二页的第一行重复显示标题且与第一行重叠。这里需要设置 table 样式 thead, tfoot {display: table-row-group;}
表格的内容过多大于一页时会偶现一行内容被从中间截断,上下页各显示半行,体验特别不好。这里需要使用 wkhtmltopdf 的选项:

wkhtmltopdf –margin-top 10mm –margin-bottom 10mm https://www.baidu.com baidu.pdf
另外,建议开启打印模式,开启打印模式后,表格的奇偶行标色会失效,尝试了一段时间无果后点开 chrome 的打印预览看一下也会失效。所以就没有继续解决。
wkhtmltopdf –print-media-type –margin-top 10mm –margin-bottom 10mm –lowquality https://www.baidu.com baidu.pdf

正文完
 0