Converting SVG to PNG in Javascript

8,978 views
Skip to first unread message

Kai Chang

unread,
Dec 9, 2011, 1:00:13 AM12/9/11
to d3...@googlegroups.com
At a meetup tonight, a d3 user was interested in ways to save d3 visualizations as PNGs. The way I've used is canvg to draw an SVG onto a canvas element:


Then extract the base64 image string from the canvas using this technique:


Finally, if you want a preview, you can put the the base64 string into an <img> tag:
<img src="data:image/png;base64,<BASE64 STRING HERE>" />

There are some alternate solutions in these threads:

http://groups.google.com/group/d3-js/browse_thread/thread/1068fdc00a2fb04a/30be7d1d15cfeba1
http://news.ycombinator.com/item?id=2575219

This is another tool that I've seen suggested, but haven't tried:

http://html2canvas.hertzen.com/

The last thread I know of on this topic was from August, so let us know if you've found new techniques since then! Client or server-side.

Jamie Popkin

unread,
Dec 9, 2011, 11:16:53 AM12/9/11
to d3...@googlegroups.com
For the server side there's phantomjs.
I'm looking forward to giving it a shot soon.

Jamie

--
Jamie Popkin
Little Earth

Nelson Minar

unread,
Dec 9, 2011, 12:01:37 PM12/9/11
to d3...@googlegroups.com
I've used PhantomJS with some success. The main drawback is (on Linux) it uses the X Server to do rendering, which means you're stuck with its crappy rendering engine and fonts. I didn't spend a lot of time tweaking it. Some rough notes here:


Ian Johnson

unread,
Dec 9, 2011, 12:16:17 PM12/9/11
to d3...@googlegroups.com

We also had more than a few issues getting phantomjs to do what we wanted.
Batik has turned out to work well albeit a little slow on the server side. The advantage is more for generating vector pdfs than pngs.

Thanks for the links Kai!

Josh Bloom

unread,
Dec 10, 2011, 9:27:07 PM12/10/11
to d3...@googlegroups.com
I'm using http://code.google.com/p/wkhtmltopdf/ to create a PDF of my generated visualization. Additionally I'm snapshotting the PDF as a PNG for use in a timelapse movie down the road. 

For PDF to PNG conversion I'm using imageMagick. 

-josh
Reply all
Reply to author
Forward
0 new messages