Home > database >  How to convert SVG to Base64 string in Angular
How to convert SVG to Base64 string in Angular

Time:05-03

i want to convert an svg element to a base64 string.

i followed following tutorial: https://thewebdev.info/2021/08/28/how-to-convert-inline-svg-to-base64-string-with-javascript/

this is the code i used:

HTML:

<svg height="100" width="100">
  <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
</svg>

TypeScript:

constructor (
  @Inject(DOCUMENT) document: Document
) {
  document.querySelector("svg")
}

ngOnInit() {
  const s = new XMLSerializer().serializeToString(document.querySelector("svg"))
  const encodedData = window.btoa(s)
  console.log(encodedData)
}

but i get following error message in vs code at .serializeToString(document.querySelector("svg")):

Argument of type 'SVGSVGElement | null' is not assignable to parameter of type 'Node' TS 2345

CodePudding user response:

The issue here is that svg isn't initialized when ngOnInit is called, hence querySelector returns null.

Move your code in ngAfterViewInit like below :- .

ngAfterViewInit() {
  const svg = document.querySelector("svg");
  if (svg) {
     const s = new XMLSerializer().serializeToString(svg)
     const encodedData = window.btoa(s)
     console.log(encodedData)
  }
}
  • Related