2

I'm trying to transform an SVG into an image with pdfmake.

const svg = document.getElementById('chart-grafico-pizza').childNodes[0];
const img = document.createElement('img');
const canvas = document.getElementById('teste-canvas');

// get svg data
const xml = new XMLSerializer().serializeToString(svg);

// make it base64
const svg64 = btoa(xml);
const b64Start = 'data:image/svg+xml;base64,';

// prepend a "header"
const image64 = b64Start + svg64;

// set it as the source of the img element
img.src = image64;
// draw the image onto the canvas
(canvas as HTMLCanvasElement).getContext('2d').drawImage(img, 0, 0);

The image is always returned as undefined.

Agi Hammerthief
  • 2,114
  • 1
  • 22
  • 38
  • Have you stepped through this line by line in a debugger to see at what point(s) it is failing? What output do you get when doing that? – Agi Hammerthief Jan 31 '18 at 20:52
  • @AgiHammerthief yeah, the code is working, but the return is undefined – Matheus Azevedo Jan 31 '18 at 21:05
  • @AgiHammerthief How can svg be so great that it can not be transformed? – Matheus Azevedo Jan 31 '18 at 21:31
  • I've come across the same issue. Whilst the pdfmake documentation states that it supports base64 data URIs, it does mention at the top of this documentation page that only "JPEG and PNG formats are supported": https://pdfmake.github.io/docs/0.1/document-definition-object/images/ – camslice Sep 01 '21 at 11:23
  • I've since submitted an issue on the pdfmake GitHub repo: https://github.com/bpampuch/pdfmake/issues/2326 – camslice Sep 01 '21 at 12:42

1 Answers1

1

I don't see any problems with your code, neither with SVG. Your code, which you obviously got from here Drawing an SVG file on a HTML5 canvas works perfectly fine, assuming that your query selectors work. Which probably is exactly the issue here... Since you did not provide your HTML, we can of course not check for that.

https://jsbin.com/qacodugive/1/edit

What do you mean by "the image is undefined"? The variable img clearly isn't. It's a DOM Element at any point in time.

HTML

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>

  <div>SVG here</div>
  <svg height="100">
    <rect width="100" height="100" />
  </svg>

  <div>Canvas here (Click "Run with JS" to render)</div>
  <canvas></canvas>

</body>
</html>

JS

var svg = document.querySelector('svg');
var img = document.createElement('img');
var canvas = document.querySelector('canvas');

// get svg data
var xml = new XMLSerializer().serializeToString(svg);

// make it base64
var svg64 = btoa(xml);
var b64Start = 'data:image/svg+xml;base64,';

// prepend a "header"
var image64 = b64Start + svg64;

// set it as the source of the img element
img.src = image64;

// draw the image onto the canvas
canvas.getContext('2d').drawImage(img, 0, 0);
Patrick Kelleter
  • 2,631
  • 1
  • 13
  • 19