### Install Dependencies Source: https://github.com/brammitch/recharts-to-png/blob/main/README.md Run this command to install all necessary project dependencies. ```bash npm i ``` -------------------------------- ### Start Demo Server Source: https://github.com/brammitch/recharts-to-png/blob/main/README.md Run this command to start the demo server, allowing you to observe your changes in real-time. ```bash npm run demo ``` -------------------------------- ### Install recharts-to-png Source: https://github.com/brammitch/recharts-to-png/blob/main/README.md Install the library using npm. ```bash npm install recharts-to-png ``` -------------------------------- ### Custom Hook Example Source: https://context7.com/brammitch/recharts-to-png/llms.txt Example of how to create a custom hook that utilizes `useCurrentPng` with predefined options. ```APIDOC ## Custom Hook Example ### Description This example demonstrates how to create a custom hook, `useChartExport`, that wraps `useCurrentPng` and applies specific default configurations like background color and scale. ### Usage ```typescript import { useCurrentPng, UseCurrentPng } from 'recharts-to-png'; // Custom hook with predefined options function useChartExport(): UseCurrentPng { return useCurrentPng({ backgroundColor: '#ffffff', scale: 2 }); } // Usage of the custom hook function MyChartComponent() { const [getPng, { isLoading, ref }] = useChartExport(); // ... rest of your chart component using ref and getPng return ( <> {/* Your Recharts chart with ref attached */} ); } ``` ``` -------------------------------- ### Run Development Server (npm, yarn, pnpm, bun) Source: https://github.com/brammitch/recharts-to-png/blob/main/examples/next/README.md Execute these commands to start the Next.js development server. Open http://localhost:3000 in your browser to view the application. ```bash npm run dev # or yarn dev # or pnpm dev # or bun dev ``` -------------------------------- ### Custom Hook Example with UseCurrentPng Source: https://context7.com/brammitch/recharts-to-png/llms.txt Example of creating a custom hook 'useChartExport' that utilizes 'useCurrentPng' with predefined background color and scale. ```typescript function useChartExport(): UseCurrentPng { return useCurrentPng({ backgroundColor: '#ffffff', scale: 2 }); } ``` -------------------------------- ### Use Callback with canvas.toBlob() Source: https://github.com/brammitch/recharts-to-png/blob/main/README.md The `useGenerateImage` hook (similar to `useCurrentPng`) allows passing a callback to `canvas.toBlob()`. This example demonstrates using the callback to copy the generated image to the clipboard. ```ts export type UseGenerateImage = [ (callback?: BlobCallback) => Promise, { isLoading: boolean; ref: React.MutableRefObject; }, ]; ``` ```tsx const [getDivPng, { ref }] = useGenerateImage({ 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
{/* content goes here */}
; ``` -------------------------------- ### Use `useGenerateImage` to Download as JPEG Source: https://context7.com/brammitch/recharts-to-png/llms.txt Use the `useGenerateImage` hook to capture an HTML element as a JPEG image with specified quality and background color. Attach the returned `ref` to the target element and call the generated function to get a data URL for saving. ```tsx import FileSaver from 'file-saver'; import { useCallback } from 'react'; import { useGenerateImage } from 'recharts-to-png'; export function DashboardExport() { // Capture as JPEG at 80% quality; strongly-typed for HTMLDivElement const [getDivJpeg, { ref, isLoading }] = useGenerateImage({ quality: 0.8, type: 'image/jpeg', // Pass any html2canvas option, e.g. a custom background colour options: { backgroundColor: '#ffffff' }, }); const handleDownload = useCallback(async () => { const jpeg = await getDivJpeg(); if (jpeg) { // jpeg is a data URL: "data:image/jpeg;base64,வைக்" FileSaver.saveAs(jpeg, 'dashboard.jpeg'); } }, [getDivJpeg]); return ( // Attach `ref` to whatever element you want to capture

My Dashboard

Any HTML content here will be captured.

); } ``` -------------------------------- ### Use useGenerateImage Hook Source: https://github.com/brammitch/recharts-to-png/blob/main/README.md Implement useGenerateImage to get an image of any HTML element. Attach the returned ref to the target element. The hook accepts optional html2canvas options, quality, and image type. ```tsx // Implement useGenerateImage to get an image of any HTML element const [getDivJpeg, { ref }] = useGenerateImage({ quality: 0.8, type: 'image/jpeg', }); const handleDivDownload = useCallback(async () => { const jpeg = await getDivJpeg(); if (jpeg) { FileSaver.saveAs(jpeg, 'div-element.jpeg'); } }, [getDivJpeg]); return
{/* content goes here */}
; ``` -------------------------------- ### Use useCurrentPng Hook Source: https://github.com/brammitch/recharts-to-png/blob/main/README.md Use the `useCurrentPng` hook to get a function to generate a PNG from a Recharts chart. Attach the returned `ref` to your chart component. The `isLoading` state indicates if the PNG is being generated. ```jsx 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 ( <>
); } ``` -------------------------------- ### Capture Recharts Chart with `useCurrentPng` Hook Source: https://context7.com/brammitch/recharts-to-png/llms.txt Use `useCurrentPng` in functional components to capture a Recharts chart. Attach the returned `ref` to your Recharts chart component and call `getPng` to get the image data. This hook is specifically designed for Recharts and automatically targets the chart's parent element. ```tsx import FileSaver from 'file-saver'; import { useCallback, useState } from 'react'; import { Area, Bar, Brush, CartesianGrid, ComposedChart, Legend, Line, ResponsiveContainer, Tooltip, XAxis, YAxis, } from 'recharts'; import { useCurrentPng } from 'recharts-to-png'; const sampleData = Array.from({ length: 20 }, (_, i) => ({ name: `Page ${i + 1}`, uv: Math.floor(Math.random() * 4000), pv: Math.floor(Math.random() * 2400), amt: Math.floor(Math.random() * 2400), })); export function ComposedChartDownload() { // Optionally pass html2canvas options, e.g. { backgroundColor: '#000' } const [getPng, { ref, isLoading }] = useCurrentPng(); const handleDownload = useCallback(async () => { const png = await getPng(); if (png) { // png is "data:image/png;base64,વું" FileSaver.saveAs(png, 'composed-chart.png'); } }, [getPng]); return ( <> {/* Attach ref directly to the Recharts chart component */} ); } ``` -------------------------------- ### useGenerateImage - Basic Usage Source: https://context7.com/brammitch/recharts-to-png/llms.txt Demonstrates how to use the `useGenerateImage` hook to capture an HTML element as a JPEG image and trigger a download using `file-saver`. It shows how to configure output quality and type, and how to attach the ref to the target element. ```APIDOC ## useGenerateImage - Basic Usage This hook captures any HTML element as an image. It returns an async function to generate the image, a ref to attach to the target element, and a loading state indicator. ### Parameters - `options` (object) - Optional configuration for image generation: - `quality` (number) - The quality of the image (0 to 1). Defaults to 1. - `type` (string) - The MIME type of the image (e.g., 'image/png', 'image/jpeg'). Defaults to 'image/png'. - `options` (object) - Additional options passed directly to `html2canvas`. ### Returns - `getDivJpeg` (function) - An async function that resolves to a data URL string of the captured image. - `{ ref: RefObject, isLoading: boolean }` - An object containing: - `ref`: A React ref object to attach to the HTML element you want to capture. - `isLoading`: A boolean indicating if the image generation is in progress. ### Example ```tsx import FileSaver from 'file-saver'; import { useCallback } from 'react'; import { useGenerateImage } from 'recharts-to-png'; export function DashboardExport() { // Capture as JPEG at 80% quality; strongly-typed for HTMLDivElement const [getDivJpeg, { ref, isLoading }] = useGenerateImage({ quality: 0.8, type: 'image/jpeg', // Pass any html2canvas option, e.g. a custom background colour options: { backgroundColor: '#ffffff' }, }); const handleDownload = useCallback(async () => { const jpeg = await getDivJpeg(); if (jpeg) { // jpeg is a data URL: "data:image/jpeg;base64, ..." FileSaver.saveAs(jpeg, 'dashboard.jpeg'); } }, [getDivJpeg]); return ( // Attach `ref` to whatever element you want to capture

My Dashboard

Any HTML content here will be captured.

); } ``` ``` -------------------------------- ### Build in Watch Mode Source: https://github.com/brammitch/recharts-to-png/blob/main/README.md Execute this command to build the recharts-to-png project and automatically recompile on file changes. ```bash npm run watch ``` -------------------------------- ### Run Tests Source: https://github.com/brammitch/recharts-to-png/blob/main/README.md Execute this command to ensure all project tests pass. ```bash npm run test ``` -------------------------------- ### useGenerateImage - BlobCallback for Clipboard Source: https://context7.com/brammitch/recharts-to-png/llms.txt Illustrates using the `BlobCallback` option with `useGenerateImage` to intercept the generated image `Blob` and write it directly to the system clipboard. ```APIDOC ## useGenerateImage with BlobCallback — Copy to clipboard The image-generation functions accept an optional `BlobCallback` that is forwarded to `canvas.toBlob()`. This allows intercepting the raw `Blob` before the data URL resolves, enabling use cases like writing directly to the system clipboard. ### Parameters - `BlobCallback` (function) - A callback function that receives the generated `Blob` object as its argument. This function is executed before the data URL is returned. ### Example ```tsx import { useCallback } from 'react'; import { useGenerateImage } from 'recharts-to-png'; export function CopyableCard() { const [getDivPng, { ref }] = useGenerateImage({ type: 'image/png', }); const handleCopyToClipboard = useCallback(async () => { // Pass a BlobCallback; the return value (data URL) is still available if needed await getDivPng((blob) => { if (!blob) return; navigator.clipboard.write([ new ClipboardItem({ // key must match the blob's MIME type [blob.type]: blob, }), ]); }); }, [getDivPng]); return (

This card can be copied to your clipboard as a PNG image.

); } ``` ``` -------------------------------- ### Use `useGenerateImage` with `BlobCallback` to Copy to Clipboard Source: https://context7.com/brammitch/recharts-to-png/llms.txt Utilize the `useGenerateImage` hook with a `BlobCallback` to intercept the generated image `Blob`. This allows for direct manipulation, such as writing the image to the system clipboard using the Clipboard API. ```tsx import { useCallback } from 'react'; import { useGenerateImage } from 'recharts-to-png'; export function CopyableCard() { const [getDivPng, { ref }] = useGenerateImage({ type: 'image/png', }); const handleCopyToClipboard = useCallback(async () => { // Pass a BlobCallback; the return value (data URL) is still available if needed await getDivPng((blob) => { if (!blob) return; navigator.clipboard.write([ new ClipboardItem({ // key must match the blob's MIME type [blob.type]: blob, }), ]); }); }, [getDivPng]); return (

This card can be copied to your clipboard as a PNG image.

); } ``` -------------------------------- ### Importing TypeScript Types for recharts-to-png Source: https://context7.com/brammitch/recharts-to-png/llms.txt Import necessary types for using the useGenerateImage and useCurrentPng hooks, and for configuring html2canvas. ```typescript import type { UseGenerateImage, UseGenerateImageArgs, UseCurrentPng, CurrentPngProps, } from 'recharts-to-png'; import type { Options as HTML2CanvasOptions } from 'html2canvas'; ``` -------------------------------- ### CurrentPngProps for Component Source: https://context7.com/brammitch/recharts-to-png/llms.txt Props injected by the component when used as a render prop, providing chart reference and PNG generation function. ```APIDOC ## Component (Render Props) ### Description When using the `` component as a render prop, it injects `chartRef`, `getPng`, and `isLoading` into its child function. This allows for direct access to the chart's ref and PNG generation capabilities within the render prop. ### Usage ```typescript import { CurrentPng } from 'recharts-to-png'; import { LineChart, Line, XAxis, YAxis } from 'recharts'; {({ chartRef, getPng, isLoading }) => ( <> )} ``` ### Injected Props - **chartRef** (React.RefObject) - A ref object to be attached to the Recharts chart component. - **getPng** ((options?: Partial) => Promise) - A function that generates the PNG image of the chart. It accepts optional html2canvas options. - **isLoading** (boolean) - A flag indicating whether the image generation is currently in progress. ``` -------------------------------- ### Defining UseGenerateImage Hook Arguments Source: https://context7.com/brammitch/recharts-to-png/llms.txt Specifies the arguments accepted by the useGenerateImage hook, including html2canvas options, image quality, and MIME type. ```typescript type UseGenerateImageArgs = { options?: HTML2CanvasOptions; // html2canvas configuration quality?: number; // 0.0–1.0, applies to lossy formats like image/jpeg type?: string; // MIME type, default "image/png" }; ``` -------------------------------- ### Defining CurrentPngProps for Render Props Source: https://context7.com/brammitch/recharts-to-png/llms.txt Defines the props injected by the component when used as a render prop, providing chart reference and PNG generation capabilities. ```typescript interface CurrentPngProps { chartRef: React.RefObject; getPng: (options?: Partial) => Promise; isLoading: boolean; } ``` -------------------------------- ### useGenerateImage Hook Source: https://context7.com/brammitch/recharts-to-png/llms.txt Hook for generating an image from any HTML element. It returns a function to generate the image and an object containing loading state and a ref. ```APIDOC ## useGenerateImage Hook ### Description Provides functionality to generate an image from any HTML element. It returns a tuple containing a function to trigger image generation and an object with the current loading state and a ref to attach to the target element. ### Usage ```typescript import { useGenerateImage } from 'recharts-to-png'; const [getPng, { isLoading, ref }] = useGenerateImage({ options: { backgroundColor: '#ffffff' }, quality: 0.8, type: 'image/jpeg' }); // Attach the ref to your target HTML element
{/* Content to be captured */}
// Call getPng to generate the image ``` ### Arguments - **options** (HTML2CanvasOptions) - Optional - Configuration options for html2canvas. - **quality** (number) - Optional - The quality of the image, ranging from 0.0 to 1.0. Applies to lossy formats like image/jpeg. - **type** (string) - Optional - The MIME type of the image, defaults to "image/png". ``` -------------------------------- ### Capture Recharts Chart with `CurrentPng` Class Component Source: https://context7.com/brammitch/recharts-to-png/llms.txt Use the `CurrentPng` component with the render-props pattern in class components. It injects `chartRef`, `getPng`, and `isLoading` into its child render function. Ensure `chartRef` is attached to the Recharts chart component. ```tsx import FileSaver from 'file-saver'; import React from 'react'; import ReactDOM from 'react-dom'; import { Area, Bar, Brush, CartesianGrid, ComposedChart, Legend, Line, ResponsiveContainer, Tooltip, XAxis, YAxis, } from 'recharts'; import { CurrentPng, CurrentPngProps } from 'recharts-to-png'; interface State { chartData: Array>; } class ChartWithDownload extends React.Component { state: State = { chartData: Array.from({ length: 10 }, (_, i) => ({ name: `Page ${i}`, uv: Math.floor(Math.random() * 4000), pv: Math.floor(Math.random() * 2400), amt: Math.floor(Math.random() * 2400), })), }; handleDownload = async () => { // this.props.getPng() resolves to "data:image/png;base64,વું" or undefined const png = await this.props.getPng(); if (png) { FileSaver.saveAs(png, 'chart.png'); } }; render() { const { chartRef, isLoading } = this.props; return ( <> {/* chartRef must be attached to the Recharts chart component */} ); } } // Mount: wrap class component with CurrentPng to inject render-prop values ReactDOM.render( {(props) => } , document.getElementById('root') ); ``` -------------------------------- ### CurrentPng Class Component with Render Props Source: https://github.com/brammitch/recharts-to-png/blob/main/README.md The `CurrentPng` class component provides the same functionality as `useCurrentPng` using render props. It's suitable for class-based React components. The `chartRef` should be attached to the Recharts component. ```tsx // index.tsx ReactDOM.render( {(props) => }, rootElement ); ``` ```tsx // RenderPropsExample.tsx export default class RenderPropsExample extends React.Component { 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 ( <>

Example: Download chart with React.Component Render Props


); } } ``` -------------------------------- ### Defining UseCurrentPng Hook Return Type Source: https://context7.com/brammitch/recharts-to-png/llms.txt Defines the return type for the useCurrentPng hook, similar to useGenerateImage but with a more generic ref type. ```typescript type UseCurrentPng = [ (callback?: BlobCallback) => Promise, { isLoading: boolean; ref: React.MutableRefObject } ]; ``` -------------------------------- ### Defining UseGenerateImage Hook Return Type Source: https://context7.com/brammitch/recharts-to-png/llms.txt Defines the return type for the useGenerateImage hook, including the image generation function and loading state. ```typescript type UseGenerateImage = [ (callback?: BlobCallback) => Promise, { isLoading: boolean; ref: React.MutableRefObject } ]; ``` -------------------------------- ### useCurrentPng Hook Source: https://context7.com/brammitch/recharts-to-png/llms.txt Hook specifically for Recharts charts, providing image generation capabilities. It returns a function to generate the PNG and an object with loading state and a ref. ```APIDOC ## useCurrentPng Hook ### Description Hook designed for Recharts charts to generate a PNG image. It returns a tuple containing a function to generate the PNG and an object with the current loading state and a ref to attach to the Recharts chart component. ### Usage ```typescript import { useCurrentPng } from 'recharts-to-png'; import { LineChart, Line, XAxis, YAxis } from 'recharts'; const [getPng, { isLoading, ref }] = useCurrentPng(); // Attach the ref to your Recharts chart // Call getPng to generate the image ``` ### Arguments This hook does not accept any arguments directly but relies on the `ref` to be attached to a Recharts component. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.