Rendering SVGs in React-pdf
I had a requirement to display a QR Code on a document created with React-pdf and it turned out to be trickier than expected as most of the image rendering I’ve done before with React-pdf was mostly just jpeg or png files. Here’s what I did to get there.
First, I made use of the qrcode.react package which seemed like the go-to way of generating QR codes in the DOM with React. It exports a QRCodeSVG
component which (as the name suggests) renders the QR Code as SVG. But then I wondered how to make this work with the Image
component from react-pdf. My first attempt was to do it inline by passing the Data URI image to the src
prop. It would be something like below:
The above works well because the image in question is png file, which react-pdf supports. Trying to put a SVG Data URI won’t work. So, the only option left was to somehow find a way to convert the SVG on the fly to a supported format (say, png) then pass it to the Image
component.
Enter the canvg package, used to render my SVG on a canvas; then afterward I can take it to be used with the HTMLCanvasElement.toDataURL()
method to get a PNG. Below a util function to do that:
Next will be how to get an SVG string from theQRCodeSVG
component. You can get this using the renderToString
method from react-dom/server
To recapitulate it all, we start with an empty state (for the data URI string). Then weuseEffect
to first render the SVG, get its string representation, convert it png as specified above, then finally we’re able to use react-pdf’s Image
component. Below final code: