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

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

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.

  1. const svg = scatterChartRef.current.chart.getSVG()
  2. const imageBuffer = Buffer.from(svg)
  3. const MyDocument = () => (
  4. <Document>
  5. <Page size="A4" style={styles.page}>
  6. <View style={styles.section}>
  7. <Image src={imageBuffer} debug={false} />
  8. </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对象。

  1. const svgString = scatterChartRef.current.chart.getSVG();
  2. // 使用DOMParser解析来自svgString的新svg元素
  3. const parser = new DOMParser();
  4. const svgElem = parser.parseFromString(svgString, "image/svg+xml").documentElement;
  5. // 使用toDataURL扩展生成Base64字符串
  6. const b64 = svgElem.toDataURL();
  7. return <Image src={b64} debug={false} />;
英文:

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

  1. const svgString = scatterChartRef.current.chart.getSVG();
  2. // Use DOMParser to parse new svg element from svgString
  3. const parser = new DOMParser();
  4. const svgElem = parser.parseFromString(svgString, &quot;image/svg+xml&quot;).documentElement;
  5. // Use toDataURL extension to generate Base64 string
  6. const b64 = svgElem.toDataURL();
  7. 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:

确定