npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

recharts-to-png

v2.4.0

Published

This package converts a Recharts chart to a png.

Downloads

42,700

Readme

npm Node.js CI CodeQL Netlify Status GitHub

recharts-to-png

A wrapper around html2canvas that will convert any element to an image with the useGenerateImage hook.

Originally written specifically to transform Recharts charts to PNG.

Inspired by these Stack Overflow questions and answers from peter.bartos and AlbertMunichMar. Special thanks to HarmNullix for helping to improve the performance of this library.

Install

npm install recharts-to-png

Demo

Hooks

See the demo here.

It implements useGenerateImage and useCurrentPng with different chart types and file-saver.

Open in StackBlitz

Class Components

For usage with class components, implement CurrentPng component with render props.

Edit reacharts-to-png-class-render-props

Usage

useGenerateImage

useGenerateImage is a React hook that returns a tuple. The first parameter is a promise that will return a string if the image is valid. The second parameter is an object with two properties: ref, which is required to be attached to the target HTML element, and isLoading, which is optional and changes state from false to true while the image is being generated.

You can pass arguments to useGenerateImage:

options?: HTML2CanvasOptions;
quality?: number;
type?: string;
// Implement useGenerateImage to get an image of any element (not just a Recharts component)
const [getDivJpeg, { ref }] = useGenerateImage<HTMLDivElement>({
  quality: 0.8,
  type: 'image/jpeg',
});

const handleDivDownload = useCallback(async () => {
  const jpeg = await getDivJpeg();
  if (jpeg) {
    FileSaver.saveAs(jpeg, 'div-element.jpeg');
  }
}, [getDivJpeg]);

return <div ref={ref}>{/* content goes here */}</div>;

useCurrentPng

useCurrentPng is a React hook that returns a tuple. The first parameter is a promise that will return a string if the PNG is valid. The second parameter is an object with two properties: ref, which is required to be attached to the target Recharts component, and isLoading, which is optional and changes state from false to true while the PNG is being generated.

function MyApp(props) {
  // useCurrentPng usage (isLoading is optional)
  const [getPng, { ref, isLoading }] = useCurrentPng();

  // Can also pass in options for html2canvas
  // const [getPng, { ref }] = useCurrentPng({ backgroundColor: '#000' });

  const handleDownload = useCallback(async () => {
    const png = await getPng();

    // Verify that png is not undefined
    if (png) {
      // Download with FileSaver
      FileSaver.saveAs(png, 'myChart.png');
    }
  }, [getPng]);

  return (
    <>
      <ComposedChart data={props.data} ref={ref}>
        <XAxis dataKey="name" />
        <YAxis />
        <Tooltip />
        <Legend />
        <CartesianGrid stroke="#f5f5f5" />
        <Area type="monotone" dataKey="amt" fill="#8884d8" stroke="#8884d8" />
        <Bar dataKey="pv" barSize={20} fill="#413ea0" />
        <Line type="monotone" dataKey="uv" stroke="#ff7300" />
        <Brush dataKey="name" height={30} stroke="#8884d8" />
      </ComposedChart>
      <br/>
      <button onClick={handleDownload}>
        {isLoading ? 'Downloading...' : 'Download Chart'}
      </button>
    </>
  );

Passing a callback to canvas.toBlob()

In addition to returning a string, the promises also accept an optional callback that will be passed to canvas.toBlob(), allowing you to add your own custom logic.

export type UseGenerateImage<T extends HTMLElement = HTMLDivElement> = [
  (callback?: BlobCallback) => Promise<string | undefined>,
  {
    isLoading: boolean;
    ref: React.MutableRefObject<T | null>;
  },
];

Here's an example using the callback to copy the image to the clipboard:

const [getDivPng, { ref }] = useGenerateImage<HTMLDivElement>({
  type: 'image/png',
});

const handleDivCopyToClipboard = useCallback(async () => {
  // Pass in optional callback for canvas.toBlob
  await getDivPng((blob) => {
    blob &&
      navigator.clipboard.write([
        new ClipboardItem({
          // The key is determined dynamically based on the blob's type.
          [blob.type]: blob,
        }),
      ]);
  });
}, [getDivPng]);

return <div ref={ref}>{/* content goes here */}</div>;

CurrentPng

Per user request, CurrentPng implements the same functionality as useCurrentPng but as a class component using render props. See background in this issue.

// index.tsx
ReactDOM.render(
  <CurrentPng>{(props) => <RenderPropsExample {...props} />}</CurrentPng>,
  rootElement
);

// RenderPropsExample.tsx
export default class RenderPropsExample extends React.Component<CurrentPngProps, State> {
  state: State = {
    chartData: [],
  };

  componentDidMount() {
    this.setState({
      chartData: getData(100),
    });
  }

  handleDownload = async () => {
    const png = await this.props.getPng();

    if (png) {
      FileSaver.saveAs(png, 'chart.png');
    }
  };

  render() {
    return (
      <>
        <h4>
          <code>Example: Download chart with React.Component Render Props </code>
        </h4>
        <ResponsiveContainer width="100%" height={300}>
          <ComposedChart data={this.state.chartData} ref={this.props.chartRef}>
            <XAxis dataKey="name" />
            <YAxis />
            <Tooltip />
            <Legend />
            <CartesianGrid stroke="#f5f5f5" />
            <Area type="monotone" dataKey="amt" fill="#8884d8" stroke="#8884d8" />
            <Bar dataKey="pv" barSize={20} fill="#413ea0" />
            <Line type="monotone" dataKey="uv" stroke="#ff7300" />
            <Brush dataKey="name" height={30} stroke="#8884d8" />
          </ComposedChart>
        </ResponsiveContainer>
        <br />
        <button disabled={this.props.isLoading} onClick={() => this.handleDownload()}>
          {this.props.isLoading ? (
            <span className="download-button-content">
              <i className="gg-spinner" />
              <span className="download-button-text">
                <code>Downloading...</code>
              </span>
            </span>
          ) : (
            <span className="download-button-content">
              <i className="gg-software-download" />
              <span className="download-button-text">
                <code>Download Chart</code>
              </span>
            </span>
          )}
        </button>
      </>
    );
  }
}

Contributing/Developing

  1. Fork/clone the repository

  2. Install dependencies

    npm i
  3. Build recharts-to-png in watch mode

    npm run watch
  4. Start the demo to observe your changes

    npm run demo:app
  5. Ensure all tests pass

    npm run test