How to take website screenshots in Ruby and Rails
Capture website screenshots and PDFs from Ruby with Net::HTTP, and from Rails with Active Job and Active Storage.
3 min read
Grover and Ferrum are the usual ways to screenshot pages from Ruby, and both mean running headless Chrome next to your app. shotsmith takes that off your servers: you make an HTTP request with Net::HTTP and get the image back.
1. Get an API key
Create a free account (100 renders a month, no card). In Rails, put the key in your credentials or an environment variable such as SHOTSMITH_ACCESS_KEY.
2. A screenshot with Net::HTTP
require "net/http"
require "uri"
uri = URI("https://shotsmith.dev/v1/take")
uri.query = URI.encode_www_form([
["access_key", "YOUR_ACCESS_KEY"],
["url", "https://shotsmith.dev/sample"],
["full_page", "true"],
["block_cookie_banners", "true"],
["format", "png"]
])
res = Net::HTTP.get_response(uri)
raise res.body unless res.is_a?(Net::HTTPSuccess)
File.binwrite("capture.png", res.body)
URI.encode_www_form takes a list of pairs, so repeated parameters, such as several hide_selectors, work as expected.
3. Thumbnails with Active Job and Active Storage
Screenshots take a second or two, so capture them in a background job and attach them with Active Storage. This job retries network timeouts, and raises the API’s error_code for anything else, so it shows up in your job dashboard:
require "net/http"
class CaptureThumbnailJob < ApplicationJob
queue_as :default
retry_on Net::OpenTimeout, Net::ReadTimeout, wait: 5.seconds, attempts: 3
def perform(site)
uri = URI("https://shotsmith.dev/v1/take")
uri.query = URI.encode_www_form(
access_key: ENV.fetch("SHOTSMITH_ACCESS_KEY"),
url: site.url,
format: "webp",
image_width: 640,
block_cookie_banners: true,
block_ads: true
)
res = Net::HTTP.get_response(uri)
unless res.is_a?(Net::HTTPSuccess)
error = JSON.parse(res.body)
raise "#{error['error_code']}: #{error['error_message']}"
end
site.thumbnail.attach(
io: StringIO.new(res.body),
filename: "#{site.id}.webp",
content_type: res["Content-Type"]
)
end
end
Call it when a site is created or its URL changes: CaptureThumbnailJob.perform_later(site). Your model needs has_one_attached :thumbnail.
4. PDFs of your own pages
To turn a Rails view into a PDF, render it to a string and send it as html in a POST request, rather than exposing a public URL for the API to fetch:
html = ApplicationController.render(template: "invoices/show", assigns: { invoice: invoice }, layout: "pdf")
res = Net::HTTP.post(
URI("https://shotsmith.dev/v1/take"),
{ html: html, format: "pdf", pdf_paper_format: "a4", pdf_print_background: true }.to_json,
"X-Access-Key" => ENV.fetch("SHOTSMITH_ACCESS_KEY"),
"Content-Type" => "application/json"
)
raise JSON.parse(res.body)["error_message"] unless res.is_a?(Net::HTTPSuccess)
invoice.pdf.attach(io: StringIO.new(res.body), filename: "#{invoice.number}.pdf", content_type: "application/pdf")
Link stylesheets and images by absolute URL, or inline them, since the page is rendered on our servers. More in the invoice PDF guide.
5. Errors and long renders
Errors are JSON with a stable error_code, listed in the error reference, and failed renders aren’t billed. Synchronous requests must finish within 18 seconds. For slow pages and videos, use async rendering and receive the result in a controller action.