title: Convert SVG to an image/png using JS/PHP
body: <p>In my case I use Highcharts for rendering charts. This library gives the charts in SVG. I want to save an image/png from this SVG, saved server side, so I can use it there. First I use the canvg parser (<a href="https://github.com/gabelerner/canvg" rel="nofollow">https://github.com/gabelerner/canvg</a>) to grab the content of the SVG element.</p>
  
  <p>In my case I've got more than one chart on the page. A requirement hereby is to grab all of them, save server side and use them in a single PDF document. </p>
  
  <p>The code (js) for this:</p>
  
  <pre><code>//  get the svg data from the chart holder
  var svg = document.getElementById(DOMId).children[0].innerHTML;
  
  //  create a target canvas element
  var target = document.getElementById('target1');
  
  //  bind svg data to the target canvas element
  canvg(target, svg);
  
  //  convert svg data to an image/png;base64 format
  var img = target.toDataURL('image/png');
  img = img.replace('data:image/png;base64,', '');
  
  //  post data to application so the file can be saved
  var bindata = "bindata=" + img;
  $.ajax({
      type: 'POST',
      url: 'path-to-handler',
      data: bindata,
      success: function(data) { chartExported(data); }
  });
  </code></pre>
  
  <p>In the handler (php), I do this:</p>
  
  <pre><code>$image = imagecreatefromstring(base64_decode(
      str_replace(' ', '+', $request-&gt;getPostParameter('bindata')
  )));
  
  if ($image !== false) {
      imagepng($image, $filename);
      imagedestroy($image);
      return $this-&gt;renderText('success');
  }
  else {
      return $this-&gt;renderText('error');
  }
  </code></pre>
  
  <p>The resulting image is just a full black something.</p>
  
  <p>If I use the following for alpha correcting, the image is completely white.</p>
  
  <pre><code>imagealphablending($image, false);
  imagesavealpha($image, true);
  </code></pre>
  
  <p>I can't seem to figure out which step is not correct.</p>
  
  <p>Thanks in advance...</p>