Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SVG not displayed when using html2canvas

I am working on a project where I need to generate a pdf file (onclick saveFile as PDF) on the client side as some data are not to be sent to the server. I have read about these options available; fileSaver.js and html2canvas, and none seem to help. I also want to point out that I am not so good with javascript. Here is my js code

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

and my 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>

Why cant it shows the SVG file? How can these files be converted to Canvas?could someone shows me with code sample? Any help will be appreciated.

like image 658
Kennan Obura Avatar asked Sep 09 '15 13:09

Kennan Obura


2 Answers

Like already said in other answers: the latest html2canvas support svg elements.

But apparently CSS is not applied and has a bug when is set the css "width" style and svg "width" attribute.

Before the screenshot, I added a treatment to svg elements.

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;
});

Edit: added height based on comment

like image 124
Isabella Lopes Avatar answered Sep 16 '22 18:09

Isabella Lopes


  • Solution 1 : You can use latest html2canvas which will support svg elements.
  • Solution 2 : Before calling html2canvas function you can convert all existing svg elements into canvas elements, which is supported by html2canvas. For this conversion you can use canvg.js.
like image 28
Raghavenda Rai K Avatar answered Sep 20 '22 18:09

Raghavenda Rai K