0

I have a react project displaying a Highcharts chart. I want to export the chart into a PDF.

  const svg = scatterChartRef.current.chart.getSVG()
  const imageBuffer = Buffer.from(svg)

  const MyDocument = () => (
    <Document>
      <Page size="A4" style={styles.page}>
        <View style={styles.section}>
          <Image src={imageBuffer} debug={false} />
        </View>

unfortunately this does not work, i'm assuming because react-pdf wants png or jpg image.

how can i convert my chart to png/jpg?

it seems the built in highcharts export methods only allow to trigger the download of a png or jpg, not provide a reference in code to a png/jpg buffer.

https://react-pdf.org/components#image

Julien
  • 212
  • 1
  • 18
  • 53

1 Answers1

2

Instead of converting your chart to a buffer, you can convert the chart to a URL object.

    const svgString = scatterChartRef.current.chart.getSVG();

    // Use DOMParser to parse new svg element from svgString
    const parser = new DOMParser(); 
    const svgElem = parser.parseFromString(svgString, "image/svg+xml").documentElement;

    // Use toDataURL extension to generate Base64 string
    const b64 = svgElem.toDataURL();

    return <Image src={b64} debug={false} />
hoangdv
  • 15,138
  • 4
  • 27
  • 48
  • i saw this solution before and couldn't figure it out. `svgElem.toDataURL is not a function` – Julien Jun 06 '23 at 12:22
  • `documentElement` provides an `HTMLElement`, but `toDataURL` exists only on `HTMLCanvasElement` – Julien Jun 06 '23 at 12:52
  • @Julien Hmm, could you replace `.documentElement` with `.firstElementChild` or `.children[0]`? and try again. – hoangdv Jun 07 '23 at 01:12