我正在尝试将 html 表格转换为 pdf。我试过使用 jspdf。它适用于 plain table 。但是当表格中有图像时不起作用。现在我正在尝试至少转换为 Canvas ,然后再转换为 pdf。但是当有图像时它也不起作用。
<html>
<head>
<style>
button{
display:block;
height:20px;
margin-top:10px;
margin-bottom:10px;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js" ></script>
<script>
window.takeScreenShot = function() {
html2canvas(document.getElementById("target"), {
onrendered: function (canvas) {
document.body.appendChild(canvas);
},
width:320,
height:220
});
}
</script>
</head>
<body>
<div id="target">
<table>
<tr><td> <img src="https://www.w3schools.com/images/w3schools_green.jpg" alt="W3Schools.com"> </td>
<td>saf</td></tr>
<tr><td>saff</td>
<td>wdqwewe</td></tr>
</table>
</div>
<button onclick="takeScreenShot()">to image</button>
<body>
</html>
最佳答案
你的问题很简单,请补充
allowTaint:true,
像这样的选项
window.takeScreenShot = function() {
html2canvas(document.getElementById("target"), {
onrendered: function (canvas) {
document.body.appendChild(canvas);
},
allowTaint:true,
useCORS: true,
width:320,
height:220
});
}
它会解决你的问题
ps: allowTaint: 是否允许跨域图片污染 Canvas
[更新] 作为@ℊαα,更好的答案是使用 您需要在选项中将 useCORS 属性设置为 true。这将在 CORS 服务时加载图像。
关于javascript - 使用 html2canvas 将 HTML 表格转换为 Canvas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44093763/