使用html2canvas与jsPDF导出含SVG内容为PDF时提示无法加载SVG数据
问题根因
- 你的SVG标签缺失必备的
xmlns="http://www.w3.org/2000/svg"属性,单独渲染时浏览器会自动补全,但jsPDF内部转义SVG为data URL时不会自动补全,导致解析失败 - jsPDF内置的
html()方法调用的html2canvas实例默认配置未适配SVG渲染场景,即便你单独引入了html2canvas也不会默认复用
最优解决方案
既然你已经验证单独使用html2canvas可以正常渲染SVG,直接绕过jsPDF的html方法,手动把DOM转成canvas后再插入PDF,兼容性最高,修改后的完整代码如下:
<!DOCTYPE html> <html> <head></head> <body> <div id="printId"> test <!-- 补充xmlns属性 --> <svg xmlns="http://www.w3.org/2000/svg" height="100" width="100"> <circle cx="50" cy="50" r="40" /> </svg> </div> <script src="../../../script/jsPDF/jspdf-2.3.1.umd.min.js"></script> <script src="../../../script/jsPDF/html2canvas-1.3.2.min.js"></script> <script> function saveAsPDF() { const { jsPDF } = window.jspdf; const source = document.getElementById("printId"); // 先手动调用html2canvas转DOM为canvas html2canvas(source, { scale: 2, // 提高导出清晰度,可自定义 useCORS: true }).then(canvas => { const imgData = canvas.toDataURL('image/png'); const pdf = new jsPDF('p', 'mm', 'a4'); // 计算图片尺寸适配A4纸,A4宽度210mm const imgWidth = 210; const imgHeight = canvas.height * imgWidth / canvas.width; pdf.addImage(imgData, 'PNG', 0, 0, imgWidth, imgHeight); pdf.save("test.pdf"); }); } </script> <input type='submit' onclick='saveAsPDF();' value='save'> </body> </html>
可选方案(不推荐)
如果你一定要用jsPDF的html()方法,也可以在配置项中传入html2canvas的自定义配置:
pdf.html(source, { callback: function (pdf) { pdf.save("test.pdf"); }, html2canvas: { scale: 2, useCORS: true } });
这种方案兼容性不如手动转canvas的方式稳定。
内容的提问来源于stack exchange,提问作者klm123
相关产品推荐
相关产品推荐

