Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

To convert HTML to an image in Rails, render the HTML and use a browser engine to turn its layout into pixels. Ferrum controls Chrome or Chromium from Ruby, so you can render a Rails view, load it in a headless browser, and save a PNG, JPEG, or WebP screenshot. The key production requirements are a usable browser binary, deliberate capture dimensions, and a reliable signal that the page’s fonts, images, and JavaScript have finished rendering.

What the conversion involves

A Rails template renderer produces HTML; it does not produce a picture of how a browser would display that HTML. For a faithful image, the HTML must be laid out by a browser engine, which resolves CSS, fonts, images, and JavaScript before capturing the rendered pixels. Ferrum is a Ruby interface to Chrome or Chromium through the Chrome DevTools Protocol. Its project README describes the prerequisite simply: “All you need is Ruby and Chrome or Chromium.”

The workflow is therefore: render a complete document, make its assets available to the browser, load the document in Chrome or Chromium, wait for the content you need, and capture the appropriate bounds. The example below writes the rendered Rails view to a temporary file and opens it in Ferrum. That keeps the example independent of a public URL for the HTML itself, but it does not automatically make remote or relative assets available; those need to be handled as described below.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Convert a Rails view with Ferrum

1. Install Ferrum and Chrome or Chromium

Add Ferrum to the application’s Gemfile and install it:

#1 Best Overall
Sale
Philips 24 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 241V8LB
  • CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
  • WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
  • A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents
bundle add ferrum
bundle install

Install Chrome or Chromium in the development and production environments where the job will run. The executable must be discoverable by Ferrum, or you must configure the executable path for your deployment. Browser packaging and sandbox settings vary by environment, so verify the setup in the same kind of container or host used in production.

2. Render a complete document

Use a template intended for image output rather than assuming a normal browser page is already self-contained. For example, a dedicated view could be app/views/reports/card.html.erb. It should include the document structure and styles it needs. If it references Rails assets, ensure the rendered HTML uses URLs the browser can actually reach. A relative path such as /assets/card.css may fail when the document is opened from a temporary file; use absolute asset URLs or inline the required styles and assets.

The following service object renders a template, saves the resulting HTML to a temporary file, and captures the browser viewport as a PNG. Adjust the template path and locals to match the application.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Philips 22 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 221V8LB
  • CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
  • SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
# app/services/html_image.rb
require "ferrum"
require "tempfile"

class HtmlImage
  def self.render_report(report)
    html = ApplicationController.renderer.render(
      template: "reports/card",
      layout: "layouts/image",
      assigns: { report: report }
    )

    Tempfile.create(["rails-image-", ".html"]) do |file|
      file.write(html)
      file.flush

      browser = Ferrum::Browser.new
      begin
        browser.goto("file://#{File.expand_path(file.path)}")
        browser.screenshot(
          path: Rails.root.join("tmp", "report.png").to_s,
          format: :png,
          full: false
        )
      ensure
        browser.quit
      end
    end
  end
end

Call HtmlImage.render_report(report) from a job or other application code. The output path in this example is tmp/report.png; change it to a unique or managed destination if multiple renders may run at once. Keep the browser lifecycle inside an ensure block so that failures do not leave a browser process behind.

3. Choose the capture bounds and format

Ferrum supports PNG, JPEG/JPG, and WebP screenshots. PNG is the documented default and is usually a good choice for text, charts, and sharp edges. JPEG or WebP may suit an image-heavy output or a consumer that specifically expects those formats. Select the format explicitly when output handling depends on it.

The example captures the browser viewport. Set viewport dimensions deliberately for a fixed-size card or social graphic; otherwise the captured layout may not match the dimensions expected by the consuming service. For a long document, use full-page capture rather than relying on a viewport screenshot. Full-page output can be much taller than a typical graphic, so consider whether the destination accepts that height or whether a smaller component capture is more appropriate.

Rank #3
Sale
Dell 24 Monitor - SE2426H - 23.8-inch FHD (1920x1080) 144Hz 1ms Display, in-Plane Switching (IPS) Technology, AMD FreeSync™, TÜV 3-Star 2X HDMI, Tilt
  • Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
  • Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
  • Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
  • In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
  • Ultra-thin bezels: Maximize your viewing experience with thin bezels.

Ferrum also supports capture by CSS selector or coordinate area, scale, background color, file output, and base64 return. Selector capture is useful when the page contains a component that should be exported without the surrounding navigation. Coordinate capture is useful for a fixed layout, but it is sensitive to viewport size and page positioning. Use scale when you need a larger raster output, and set a background explicitly when transparency or a particular page color matters.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Make the rendered result reliable

Resolve styles, fonts, and images

A screenshot is only as complete as the resources the browser can load. Check that stylesheets and image URLs resolve from the browser’s environment, not just from the Rails process. For a rendered file, relative URLs are resolved relative to that file, not automatically against the Rails application. Inline critical CSS, use absolute URLs for remote assets, or serve the document and its assets from an address available to the browser.

Fonts can load after the initial document navigation, and client-side code can change the page after the first paint. A fixed sleep may work sometimes but is not a dependable readiness rule across machines or pages. Prefer an application-specific signal: for example, render a known element only when the data and client-side layout are ready, then wait for that selector before capturing. Also test pages with slow or unavailable remote resources so that a missing font or image does not silently become an incomplete output.

Rank #4
Samsung 27" Essential S3 (S36GD) Series FHD 1800R Curved Computer Monitor
  • CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
  • SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
  • MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
  • KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
  • INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient

Choose between viewport, full page, and element capture

  • Viewport: Use it when the deliverable has known dimensions and the content is designed to fit within them.
  • Full page: Use it when the entire document is required, while checking the resulting image height and downstream limits.
  • Selector: Use it to export a specific component such as a report card or invoice region.
  • Coordinate area: Use it for a stable, fixed-position region; confirm viewport and layout dimensions so the coordinates still refer to the intended pixels.

Which Rails rendering approach should you choose?

Approach Best fit Tradeoff
Ferrum directly Rails code that needs direct browser screenshot control. Your team manages Chrome or Chromium and the integration lifecycle.
FerrumPdf A controller workflow that benefits from a Rails-oriented renderer interface. Check current Rails and gem compatibility, along with operational behavior, before adopting it.
Cuprite An application already using Capybara-driven browser workflows. Cuprite is a Capybara driver built on Ferrum; it is unnecessary overhead if the only need is direct screenshot capture.
Hosted rendering API A team that prefers not to install and manage a browser binary in its application environment. It adds an external request and service, so assess data handling, cost, and availability for your use case.

FerrumPdf documents a Rails controller renderer and a render_screenshot interface that accepts HTML or a URL and exposes screenshot controls such as format, full-page capture, selector, area, scale, and background color. Treat it as an integration option, not proof of compatibility with every Rails release. Cuprite is most relevant when Capybara is already part of the project. Its documentation includes a Docker example using a browser no-sandbox option; that is a deployment-specific configuration, not a universal security recommendation.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Run image generation outside a web request when needed

Launching a browser and waiting for page assets can make a controller response slow and resource-intensive. If image generation is expensive, unpredictable, or requested in bursts, enqueue it in a background job and let the application return a job status or a previously generated image. This is an architectural choice rather than a Ferrum guarantee: measure your own render latency and browser resource use before deciding whether synchronous generation is acceptable.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For repeated identical inputs, consider whether a cache is appropriate and define what makes a result stale: template changes, data changes, asset changes, or all three. Use unique temporary and output paths for concurrent work. Ensure jobs clean up browser processes and temporary files after both success and failure.

Best Value
Sale
Sceptre New 22-Inch Gaming Monitor, FHD 1080p, Up to 144Hz, HDMI, DisplayPort, Built-in Speakers, Machine Black (E225W-FW144 Series, 2026)
  • 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
  • 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
  • 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.

Troubleshooting Rails HTML screenshots

  • Ferrum cannot find Chrome or Chromium: Install the browser in the runtime environment and make its executable discoverable. If the executable is in a nonstandard location, configure the browser path for that environment. Confirm the setting inside the deployed container, not only on a developer workstation.
  • The image has no CSS or images: Inspect the HTML’s asset URLs from the browser’s point of view. Relative paths in a temporary file may resolve incorrectly; use reachable absolute URLs or inline the required resources.
  • The screenshot is blank or partly rendered: Check navigation success, JavaScript errors, and asset requests. Replace an arbitrary delay with a readiness condition tied to the content you need, and allow for remote-resource failures.
  • The output is clipped: Determine whether the desired result is the viewport, full document, a selector, or an area. Set the viewport intentionally and use the corresponding capture mode.
  • Text or edges look soft: Check capture scale and output dimensions, and confirm the browser has loaded the intended font before capturing.
  • Containers fail to launch the browser: Verify the installed browser and container configuration. Do not copy a no-sandbox flag from an example without reviewing its security implications for your specific deployment.
  • Requests time out or tie up web workers: Move generation to a background job when render duration or browser lifecycle makes it unsuitable for the request path; capture errors and clean up the browser in all outcomes.

Or skip the browser setup

If the page is reachable by URL and you would rather use a hosted renderer, ScreenshotNeo is a website screenshot API and MCP server. Its one-call API can return a screenshot, and its documentation also covers HTML/CSS-to-image options. For a publicly reachable page, this cURL request saves a WebP screenshot; see the ScreenshotNeo API documentation for request parameters and response details:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://your-public-site.example/report -o report.webp

ScreenshotNeo removes supported cookie and consent banners, newsletter popups, and chat widgets before capture; each of those cleanup steps can be turned off. Bot checks and CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers report the page verdict and billing status. Its MCP server offers take_screenshot, get_page_info, and capture_pdf for AI agents and MCP clients. The Free plan includes 1,000 screenshots per month with no card required; paid plans start at $5 for 3,000 shots. A hosted API adds an external service and request, so decide whether that suits your data-handling and deployment requirements.

Sign up for ScreenshotNeo’s free plan to get 1,000 screenshots a month with no card.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Frequently Asked Questions

Can I use Ferrum to return a screenshot from a Rails controller?

Yes. Ferrum can write a screenshot to a file or return image data; a controller can send that output with an image content type. For slow or bursty renders, use a background job rather than holding a web request open.

Does Ferrum render HTML without Chrome or Chromium?

No. Ferrum controls Chrome or Chromium, so the browser runtime must be available wherever the capture runs.

Is Cuprite required to take a screenshot with Ferrum?

No. Cuprite is useful for Capybara workflows; direct screenshot capture can use Ferrum without adding Capybara.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.