reactjscanvashtml5-canvaskonvajsreact-konva

Export Canvas from React Konva to SVG & PDF?


Currently, I can only use jpeg & png exports like:

stageRef.current?.getStage().toDataURL({ mimeType: 'image/jpeg', quality: 1 })
stageRef.current?.getStage().toDataURL({ mimeType: 'image/png', quality: 1 })

I want to export Canvas to svg as well as pdf like Figma does it.

I found out about Data URIs which led to MIME_types. In there, they have written application/pdf & image/svg+xml should work but when I do that I still get a .png image.

Is there any way to achieve .svg & .pdf from Canvas in Konva?


Solution

  • stage.toDataURL() is using canvas.toDataURL() API to do the export. Most of the browsers support only jpg and png formats.

    For SVG or PDF exports you have to write your own implementation.

    For PDF exports you may use external libraries to generate a PDF file with an image from stage.toDataURL() method. As a demo take a look into Saving Konva stage to PDF demo.

    There are no built-in methods for SVG exports in Konva library. You have to write your own implementation. If you use basic shapes such as Rect, Circle and Text without any fancy filters, writing such conversions shouldn't be hard, because there are similar tags in SVG spec.