Matheus Azevedo
Matheus Azevedo

Reputation: 121

pdfmake - Transform SVG to image64 in ANGULAR 4

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.

Upvotes: 2

Views: 2494

Answers (1)

Patrick Kelleter
Patrick Kelleter

Reputation: 2771

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

Upvotes: 1

Related Questions