How to use package save-svg-as-png to download png image

This post explains how to use the package save-svg-as-png to download the png image of the contents in your svg element in your React component.

Create a basic React App as previously discussed in this post.

Create a component ImageWrapper as shown below:

import React from 'react'


export default class ImageWrapper extends React.Component {

  constructor(props) {
    super(props)
    this.state = {
    }
  }

  render() {
    return (
      <div>
          <svg id={"svg-chart"} viewBox="0 0 10 10" xmlns="http://www.w3.org/2000/svg">
            <rect x="0" y="0" width="100%" height="100%"/>
            <circle cx="50%" cy="50%" r="2" fill="white"/>
          </svg>
      </div>
    )
  }
}

Install the following package in your App with the command:

npm install save-svg-as-png

Modify the code in your App.js file as shown below:

import React, { Component } from "react";
import "./App.css";
import ImageWrapper from "./components/ImageWrapper";

const saveSvgAsPng = require('save-svg-as-png')

const imageOptions = {
  scale: 5,
  encoderOptions: 1,
  backgroundColor: 'white',
}

class App extends Component {

  handleClick = () => {
    saveSvgAsPng.saveSvgAsPng(document.getElementById('svg-chart'), 'shapes.png', imageOptions);
  };

  render() {
    return (
      <div className="App">
        <ImageWrapper />
        <br />
        <button onClick={this.handleClick}>Download Image</button>
      </div>
    );
  }
}

export default App;

Run the App with:

npm start

Click on the button Download Image to test.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.