Powered by AppSignal & Oban Pro
Would you like to see your link here? Contact us

Resvg example

livebooks/example.livemd

Resvg example

Mix.install([
  {:resvg, "~> 0.4"},
  {:req, "~> 0.5"},
  {:kino, "~> 0.9"}
])

Helpers & Glob

defmodule H do
  def kino_image_from_buffer(buffer) do
    binary = :erlang.list_to_binary(buffer)
    Kino.Image.new(binary, :png)
  end

  def download!(url) do
    %{body: body} = Req.get!(url)
    body
  end

  def download_as!(url, path) do
    %{body: body} = Req.get!(url)
    File.write!(path, body)
  end
end

path = __DIR__

Convert a svg to png

rustacean_svg =
  H.download!(
    "https://raw.githubusercontent.com/mrdotb/resvg_nif/master/test/support/rustacean.svg"
  )

{:ok, buffer} = Resvg.svg_string_to_png_buffer(rustacean_svg, resources_dir: path)
H.kino_image_from_buffer(buffer)

Set a background color

{:ok, buffer} =
  Resvg.svg_string_to_png_buffer(rustacean_svg, background: "gold", resources_dir: path)

H.kino_image_from_buffer(buffer)

Use a custom font

# Download roboto.ttf
roboto_path = "#{path}/roboto.ttf"

font_file =
  H.download_as!(
    "https://raw.githubusercontent.com/mrdotb/resvg_nif/master/test/support/fonts/Roboto-Regular.ttf",
    roboto_path
  )

svg_string = """
  
    
      #text {
        fill: black;
        font-family: 'Roboto';
        font-size: 45px;
        text-anchor: middle;
      }
    
    Roboto
  
"""

{:ok, buffer} =
  Resvg.svg_string_to_png_buffer(svg_string, resources_dir: path, font_files: [roboto_path])

H.kino_image_from_buffer(buffer)

Composition with svg and :resources_dir

H.download_as!(
  "https://raw.githubusercontent.com/mrdotb/resvg_nif/master/test/support/mdn-logo.png",
  "#{path}/mdn-logo.png"
)

svg_string = """
  
    
    
  
"""

{:ok, buffer} =
  Resvg.svg_string_to_png_buffer(svg_string, resources_dir: path, font_files: [roboto_path])

H.kino_image_from_buffer(buffer)

Clip path

svg_string = """
  
    
      
        
      
    
    
  
"""

{:ok, buffer} =
  Resvg.svg_string_to_png_buffer(svg_string, resources_dir: path, font_files: [roboto_path])

H.kino_image_from_buffer(buffer)