将Highcharts图表图像转换为PNG/JPG缓冲区以在react-pdf中显示。

huangapple go评论91阅读模式
英文:

convert HIghcharts chart image to png/jpg buffer to display in react-pdf

问题

I have a react project displaying a Highcharts chart.
我有一个React项目,显示了一个Highcharts图表。

I want to export the chart into a PDF.
我想将图表导出为PDF。

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

const MyDocument = () => (




unfortunately this does not work, i'm assuming because react-pdf wants png or jpg image.
不幸的是,这不起作用,我猜是因为react-pdf需要png或jpg图像。

how can i convert my chart to png/jpg?
我如何将我的图表转换为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.
似乎内置的Highcharts导出方法只允许触发png或jpg的下载,而不提供代码中的png/jpg缓冲区的引用。

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

英文:

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

答案1

得分: 2

而不是将您的图表转换为缓冲区,您可以将图表转换为URL对象。

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

    // 使用DOMParser解析来自svgString的新svg元素
    const parser = new DOMParser(); 
    const svgElem = parser.parseFromString(svgString, "image/svg+xml").documentElement;

    // 使用toDataURL扩展生成Base64字符串
    const b64 = svgElem.toDataURL();

    return <Image src={b64} debug={false} />;
英文:

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, &quot;image/svg+xml&quot;).documentElement;

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

    return &lt;Image src={b64} debug={false} /&gt;

huangapple
  • 本文由 发表于 2023年6月6日 11:07:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76411206.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定