英文:
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.
答案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, "image/svg+xml").documentElement;
// Use toDataURL extension to generate Base64 string
const b64 = svgElem.toDataURL();
return <Image src={b64} debug={false} />
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论