前文 提到了项目中引用了https://www.chartjs.org/,几经尝试一度觉得它们互不兼容。百度谷歌了许久,又本身尝试了屡次。终于仍是找到了它们配合的点。html
这里面使用的版本必须是https://github.com/wkhtmltopdf/wkhtmltopdf/releases/0.12.2.1git
好多文章说chartjs必须使用2.6.0版本,可是实测2.5.x和2.7.x均可以经过。下面是一个能够成功在pdf中显示的代码示例:github
<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>
wkhtmltopdf --margin-top 10mm --margin-bottom 10mm https://www.baidu.com baidu.pdf
另外,建议开启打印模式,开启打印模式后,表格的奇偶行标色会失效,尝试了一段时间无果后点开chrome的打印预览看一下也会失效。因此就没有继续解决。ajax
wkhtmltopdf --print-media-type --margin-top 10mm --margin-bottom 10mm --lowquality https://www.baidu.com baidu.pdf