Home > Blockchain >  Html-to-Image SVG export
Html-to-Image SVG export

Time:07-20

I need to be able to export everything inside a Div into an exportable SVG file. I'm using html-to-image library to do this. The issue I'm having is that the generated SVG path isn't correct and does not work as an SVG file. Tried a few things, but am stuck. Below is the entire code that you can run to test it out.

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <body>



    <!-- 1. Constructing a Div -->
    <div id="capture" style="padding: 10px; background: #f5da55">
        <h4 style="color: #000; ">Hello world!</h4>
    </div>


    <!-- 2. Using HTML-to-Image to convert that Div to SVG -->
      <script src="https://cdnjs.cloudflare.com/ajax/libs/html-to-image/1.9.0/html-to-image.js"></script>
      <script type="text/javascript">
        
      
      function filter (node) {
        return (node.tagName !== 'i');
      }

      htmlToImage.toSvg(document.getElementById('capture'), { filter: filter })
        .then(function (dataUrl) {

      //--3. the following Alert shows the generated SVG file for reference, but the SVG path generated is wrong
          alert(dataUrl);

          
        });
      </script>
  </body>
</html>

CodePudding user response:

I tried your code and it seems that it’s working well. The path seems correct and it can be used as an SVG image. Can you explain what exactly wrong with the path and how did you used the generated image?

function filter (node) {
    return (node.tagName !== 'i');
}

htmlToImage.toSvg(document.getElementById('capture'), {filter: filter})
  .then(function (dataUrl) {
    document.getElementById('generated-svg').src = dataUrl     });
<h2>Original div</h2>    
<!-- 1. Constructing a Div -->
<div id="capture" style="padding: 10px; background: #f5da55">
    <h4 style="color: #000; ">Hello world!</h4>
</div>

<h2>Generated SVG (img tag)</h2>
<img src="" id="generated-svg">

<script src="https://cdnjs.cloudflare.com/ajax/libs/html-to-image/1.9.0/html-to-image.js"></script>

Generated data uri

data:image/svg xml;charset=utf-8,
<style></style>

Hello world!

CodePudding user response:

Returned dataUrl from html-to-image is url encoded. So, you need to decode and also need to ommit the first mimie-type string which is the part before the comma ,. In this example, I splitted the data string with , and decode the svg string.

 <div id="svg">
 </div>

 htmlToImage.toSvg(document.getElementById('capture'), { filter: filter 
       })
        .then(function (dataUrl) {
          let svg = decodeURIComponent(dataUrl.split(',')[1])
          console.log(svg);
          document.getElementById('svg').innerHTML = svg          
        });
  • Related