Skip to content

HtmlRasterizerClient

Overview

The HtmlRasterizerClient is a Ruby client developed to convert HTML content into PDF documents or PNG/JPEG images. It offloads the rendering process to an internal Node.js service (utilizing the Puppeteer library), ensuring that the main Rails application is not blocked by heavy rendering tasks.

This tool is essential for generating: - PDFs: Invoices, deal summaries, and contracts. - Images: Previews for digital invites and social media assets.

Key Concepts

Service Queues

To prevent resource contention between critical business flows and general background tasks, the client provides two distinct pre-configured instances:

  1. HtmlRasterizerClient.billing_docs

    • Usage: STRICTLY for billing-related documents (e.g., invoices, receipts).
    • Purpose: Ensures that generating a hard copy of an invoice is never delayed by a large batch of less critical tasks.
  2. HtmlRasterizerClient.generic

    • Usage: For all other purposes (e.g., invite previews, report generation).
    • Purpose: General pool for non-billing rasterization jobs.

Usage Guide

1. Prepare the HTML Content

The rasterizer expects a full HTML string. It is best practice to use render_to_string with a dedicated layout that includes all necessary styles but excludes interactive UI elements (like navigation bars).

# Example: Rendering a view to a string
html_content = ApplicationController.ad_hoc_instance(document: @document).render_to_string(
  template: 'rasterization/custom_template',
  layout: 'bs4_iplan_theme/layouts/rasterize' # Use a layout optimized for print/static rendering
)

2. Call the Rasterizer

Select the appropriate queue (generic or billing_docs) and call the rasterize! method.

Syntax

HtmlRasterizerClient.generic.rasterize!(html_content, format: :symbol, **options)

Parameters

  • html_content (String): The raw HTML string to convert.
  • format (Symbol): Output format. Supported values: :pdf, :png, :jpeg.
  • options (Hash): Additional configuration for the rasterization process.

3. Examples

Generating a PDF

To generate a PDF, specify format: :pdf. You can control margins, orientation, and format via output_options.

begin
  pdf_binary = HtmlRasterizerClient.generic.rasterize!(
    html_content,
    format: :pdf,
    output_options: {
      # Margin settings (can be a string "1cm" or object)
      margin: { top: '2cm', right: '1cm', bottom: '2cm', left: '1cm' },
      # Page orientation: :portrait (default) or :landscape
      orientation: :portrait,
      # Page format: 'A4' (default), 'Letter', etc.
      format: 'A4'
    }
  )

  # Save or send the PDF binary
  File.binwrite("output.pdf", pdf_binary)
rescue Faraday::Error => e
  # Handle service failures (timeout, network issues)
  Rails.logger.error("PDF Generation failed: #{e.message}")
end

Generating an Image (PNG)

To generate an image, specify format: :png.

image_binary = HtmlRasterizerClient.generic.rasterize!(
  html_content,
  format: :png,
  output_options: {
    full_page: true,       # Capture the entire scrollable content
    omit_background: false # Set true for transparent background
  }
)

Configuration & Options

The output_options hash is passed directly to the rendering service (transforming keys to camelCase). Common options include:

PDF Options

Option Type Default Description
format String 'A4' Paper format (e.g., 'A4', 'Letter').
landscape Boolean false Set to true for landscape orientation.
margin Hash/String '0.5cm' Page margins.
printBackground Boolean true Whether to print background graphics.

Image Options

Option Type Default Description
full_page Boolean false If true, takes a screenshot of the full scrollable page.
quality Integer - Quality (0-100) for JPEG images.

Error Handling

The rasterize! method raises a Faraday::Error if the request to the rasterization service fails (e.g., service down, timeout, 500 error).

  • Always wrap calls in a begin-rescue block to ensure your application can handle rendering failures gracefully.
  • Log errors with ample context (document IDs, parameters) to aid debugging.

Troubleshooting

  • Missing Styles/Images: Ensure your HTML uses absolute URLs or that the originUrl is correctly resolved by the service. The client attempts to set a default originUrl based on the app configuration.
  • Timeouts: Large or complex HTML documents may take longer to render. Simplify your HTML or check the service timeout settings if you encounter frequent timeouts.