Link Search Menu Expand Document

Ruby: HTML/CSS to Image

Generate a png, jpg or webp images with Ruby. Renders exactly like Google Chrome. Want to see how it works? Give the live demo a try.

Live demo Get an API Key


Table of contents

Generating images with Ruby

The API takes your HTML/CSS and runs it inside a real instance of Google Chrome to convert your html into an image. Use Ruby to send the API your HTML/CSS. You’ll get back the URL to your generated image.

For more details on how this works, see Creating an image.

{
  "url": "https://hcti.io/v1/image/be4c5118-fe19-462b-a49e-48cf72697a9d"
}

Image generated with Ruby.

Authentication with Ruby

The API uses HTTP Basic authentication.

Your username is your User ID and your password is your API Key. Both of these are available from the dashboard. The Ruby code sample demonstrates how to authenticate your request.

You can signup for a free API key to get started.

Free API Key for Ruby


Ruby example code

This Ruby code example sends an HTTP POST to the https://hcti.io/v1/image API. Converting your HTML/CSS to an image with Ruby.

This example uses the HTTParty gem. Install with gem install httparty, or add it to your Gemfile.

require "httparty"
# Retrieve your user id and api key from the Dashboard
auth = { username: 'user_id', password: 'api_key' }

html = "<div class='ping'>Pong ✅</div>"
css = ".ping { padding: 20px; font-family: 'sans-serif'; }"

image = HTTParty.post("https://hcti.io/v1/image",
                      body: { html: html, css: css },
                      basic_auth: auth)

# => {"url"=>"https://hcti.io/v1/image/bde7d5bf-f7bb-49d9-b931-74e5512b8738"}

Ruby on Rails example with caching

This example shows a common setup for a Rails application. Add this file to your lib folder, such as app/lib/html_css_to_image.rb. You’ll then be able to use it from any of your models.

This example uses Rails built in caching:

  • The cache key is a SHA of your html/css and google fonts.
  • You’ll only generate a unique image once.
  • If your HTML changes at all, a new image will be created. Subsequent calls using the same HTML/CSS parameters will return the cached URL rather than creating a new image.
module HtmlCssToImage
  # User ID and API Key are stored as environment variables.
  AUTH = { username: ApplicationConfig["HCTI_API_USER_ID"],
           password: ApplicationConfig["HCTI_API_KEY"] }.freeze

  FALLBACK_IMAGE = "https://thepracticaldev.s3.amazonaws.com/i/g355ol6qsrg0j2mhngz9.png".freeze

  CACHE_EXPIRATION = 6.months

  def self.url(html:, css: nil, google_fonts: nil)
    image = HTTParty.post("https://hcti.io/v1/image",
                          body: { html: html, css: css, google_fonts: google_fonts },
                          basic_auth: AUTH)

    image["url"] || FALLBACK_IMAGE
  end

  def self.fetch_url(html:, css: nil, google_fonts: nil)
    cache_key = "htmlcssimage/#{html}/#{css}/#{google_fonts}"
    cached_url = Rails.cache.read(cache_key)

    return cached_url if cached_url.present?

    image_url = url(html: html, css: css, google_fonts: google_fonts)
    unless image_url == FALLBACK_IMAGE
      Rails.cache.write(cache_key, image_url, expires_in: CACHE_EXPIRATION)
    end

    image_url
  end
end

This class can then be used like this.

## Fetch from cache or create an image.
HtmlCssToImage.fetch_url(html: "<div>Hello, world</div>", css: "div { background-color: blue; }", google_fonts: "Roboto")

## Or without caching.
HtmlCssToImage.url(html: "<div>Hello, world</div>", css: "div { background-color: blue; }", google_fonts: "Roboto")

Rendering a Rails view

This can be useful from within a controller. To render a view from Rails and pass it to the API, use render_to_string from within a controller action.

With this, you can create an image from a template and redirects the user to the image.

html = render_to_string("path/to/view", formats: :html, layout: false)
redirect_to HtmlCssToImage.fetch_url(html: html, google_fonts: "Roboto|Roboto+Condensed"), status: :found

Real world example

Take a look at dev.to’s source code to see how they implemented this for generating social cards. Code on GitHub.


Need help?

Talk to a human. Please email us support@htmlcsstoimage.com with any questions and we’ll gladly help you get started.


Back to top

Built with extensive integration tests and serious care for developer happiness.
© 2018-2020 Code Happy, LLC.

Page last modified: Jul 13 2020 at 10:24 PM.

Edit this page on GitHub.