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.
require "htmlcsstoimage"
# Retrieve your user id and api key from https://htmlcsstoimage.com/dashboard
client = HTMLCSSToImage.new(user_id: "user-id", api_key: "api-key")
Alternatively, you can set ENV["HCTI_USER_ID"] and ENV["HCTI_API_KEY"]. These will be loaded automatically.
To see additional methods available with the Ruby gem, see the documentation here.
Example with HTTParty
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 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.
require "htmlcsstoimage"
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?
client = HTMLCSSToImage.new
image = client.create_image(html: html, css: css, google_fonts: google_fonts)
if image.success?
Rails.cache.write(cache_key, image.url, expires_in: CACHE_EXPIRATION)
end
image.url
end
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.