How can I convert an SVG string to file or PNG in Ruby?

I am posting an SVG string from a browser (Javascript) to a server with Rails (Ruby). I want to convert this string to PNG with transparency or at least SVG file so I can convert it afterwards

Any ideas? I installed RMagick, but I'm still not sure how to create a file from a string.

Any other solution to achieve this?

The idea is to dynamically create simple "logos"

+3


source to share


2 answers


With RMagick, just read the line in the image instance with Image.from_blob + defines the SVG format

require "RMagick"

svg_string='
<svg xmlns="http://www.w3.org/2000/svg"  width="120" height="120" viewPort="0 0 120 120" version="1.1">
  <rect width="150" height="150" fill="rgb(0, 255, 0)" stroke-width="1" stroke="rgb(0, 0, 0)" />
  <line x1="20" y1="100" x2="100" y2="20" stroke="black" stroke-width="2"/>
</svg>'

img = Magick::Image.from_blob(svg_string) {
  self.format = 'SVG'
  self.background_color = 'transparent'
}
img.write "example_out.png"

      

How to convert SVG string to file or PNG in Ruby



Edit

If the string is just an SVG path, there is a way Magick::Draw.path

to "rebuild" the vector graphics. Doc and examples here .

+6


source


We did it with some SVGs generated with c3 / d3. We ended up using Capybara to visit a webpage, which rendered the SVG and then saved a snapshot of the page.



0


source







All Articles