14

我正在做一个项目,我需要在客户端生成一个 pdf 文件(onclick saveFile as PDF),因为某些数据不会发送到服务器。我已阅读有关这些可用选项的信息;fileSaver.js 和 html2canvas,似乎都没有帮助。我还想指出,我不太擅长 javascript。这是我的js代码

<script type="text/javascript">
    $(document).ready(function() {
        $("#saveOutput").click(function() {
            $("#Screenshot").html2canvas({ 
                onrendered: function(canvas) {
                    var png = canvas.toDataURL()
                    window.open(png);
                }
            });
        });
    });
</script>

和我的 HTML

<div id="Screenshot">
    <p>This is it</p>
    <svg xmlns:xlink="http://www.w3.org/1999/xlink" width="250" height="250" style="height: 250px; width: 250px;">       
          <circle id="1" cx="100" cy="100" r="25" fill="#A52A2A"></circle>
    </svg>
</div>
<div id="content">
    <a class="button" id="saveOutput" href="#">Save as File</a>
</div>

为什么它不能显示 SVG 文件?如何将这些文件转换为 Canvas?有人可以向我展示代码示例吗?任何帮助将不胜感激。

4

4 回答 4

29

就像在其他答案中已经说过的那样:最新的 html2canvas 支持 svg 元素。

但显然 CSS 没有应用,并且在设置 css“width”样式和 svg“width”属性时有一个错误。

在截屏之前,我为 svg 元素添加了处理。

var svgElements = document.body.querySelectorAll('svg');
svgElements.forEach(function(item) {
    item.setAttribute("width", item.getBoundingClientRect().width);
    item.setAttribute("height", item.getBoundingClientRect().height);
    item.style.width = null;
    item.style.height= null;
});

编辑:根据评论添加高度

于 2019-12-03T17:41:55.173 回答
6
  • 解决方案 1:您可以使用支持 svg 元素的最新 html2canvas。
  • 解决方案 2:在调用 html2canvas 函数之前,您可以将所有现有的 svg 元素转换为 html2canvas 支持的 canvas 元素。对于此转换,您可以使用 canvg.js。
于 2017-08-31T10:03:20.123 回答
0

面临同样的问题。

将所有 CSS 移动到容器元素 ( div) 中,并将 CSS(在我的例子中,position:absolute;)应用于容器元素而不是 svg 元素。

正如 Isabella Lopes 正确指出的那样,高度和宽度需要用作属性而不是样式。

于 2021-06-06T09:14:56.543 回答
-1

尝试通过以下链接下载最新版本的 html2canvas

https://github.com/niklasvh/html2canvas/releases

目前它的版本是 0.5.0-alpha1

我试过了,它对我有用。

于 2016-08-28T09:41:57.437 回答