Class: HTMLCSSToImage

Inherits:
Object
  • Object
show all
Includes:
HTTParty
Defined in:
lib/htmlcsstoimage/client.rb,
lib/htmlcsstoimage/images.rb,
lib/htmlcsstoimage/version.rb,
lib/htmlcsstoimage/templates.rb,
lib/htmlcsstoimage/signed_urls.rb

Overview

Client for creating images and managing templates with HTML/CSS to Image.

Defined Under Namespace

Classes: ApiResponse

Constant Summary collapse

VERSION =

Current version of the Ruby client gem.

"0.3.0"

Instance Method Summary collapse

Constructor Details

#initialize(user_id: ENV["HCTI_USER_ID"], api_key: ENV["HCTI_API_KEY"]) ⇒ HTMLCSSToImage

Creates an instance of HTMLCSSToImage with API credentials. If credentials are not provided, the client uses the HCTI_USER_ID and HCTI_API_KEY environment variables.

Parameters:

  • user_id (String) (defaults to: ENV["HCTI_USER_ID"])

    the user ID for the account

  • api_key (String) (defaults to: ENV["HCTI_API_KEY"])

    the API key for the account

See Also:



33
34
35
# File 'lib/htmlcsstoimage/client.rb', line 33

def initialize(user_id: ENV["HCTI_USER_ID"], api_key: ENV["HCTI_API_KEY"])
  @auth = { username: user_id, password: api_key }
end

Instance Method Details

#create_image(html, params = {}) ⇒ HTMLCSSToImage::ApiResponse

Converts HTML/CSS to an image with the API.

Parameters:

  • html (String)

    HTML to render, as a snippet or an entire webpage

  • params (Hash) (defaults to: {})

    image creation options

Options Hash (params):

  • :format (String)

    The format used in the initially returned URL: png, jpg, webp, or pdf. This does not change the stored image definition or prevent rendering another supported format later.

  • :css (String)

    The CSS for your image.

  • :device_scale (Numeric)

    The pixel ratio for the screenshot. Minimum: 0.1, Maximum: 3.

  • :google_fonts (String)

    Google Fonts to load. Separate multiple fonts with |.

  • :max_wait_ms (Integer)

    The maximum time to wait before taking the screenshot. Minimum: 500, Maximum: 10000.

  • :ms_delay (Integer)

    Extra time in milliseconds to wait before taking the screenshot. Maximum: 10000.

  • :render_when_ready (Boolean)

    Wait until ScreenshotReady() is called from JavaScript before taking the screenshot.

  • :selector (String)

    A CSS selector for the element to capture.

  • :viewport_height (Integer)

    The Chrome viewport height. Both viewport dimensions must be set if using either.

  • :viewport_width (Integer)

    The Chrome viewport width. Both viewport dimensions must be set if using either.

  • :pdf_options (Hash)

    Options for generating a PDF, including page size, margins, scale, and background printing.

  • :disable_twemoji (Boolean)

    Disable the Twemoji fallback and use native emoji fonts.

  • :max_render_once (Boolean)

    Ensure the image is only rendered and saved once.

  • :dedupe_duration_s (Integer)

    Reuse an identical image created within this many seconds. Only supported for single-image POST requests.

  • :color_scheme (String)

    Render using the light or dark browser color scheme.

  • :timezone (String)

    The browser timezone as an IANA timezone identifier, such as America/New_York.

  • :viewport_mobile (Boolean)

    Whether to honor the page's mobile viewport behavior.

  • :viewport_landscape (Boolean)

    Whether to render the viewport in landscape mode.

  • :viewport_touch (Boolean)

    Whether the viewport supports touch events.

  • :media_type (String)

    Render using print or screen media.

  • :proxy_id (String)

    The ID of an organization proxy to use for the render.

  • :storage_destination_id (String)

    The ID of an organization storage destination for the rendered image.

  • :jumbo_max_height (Integer)

    Maximum output height in jumbo mode. Requires jumbo_max_width.

  • :jumbo_max_width (Integer)

    Maximum output width in jumbo mode. Requires jumbo_max_height.

  • :transparent_background (Boolean)

    Whether to render the image with a transparent background.

Returns:

See Also:



34
35
36
37
38
39
# File 'lib/htmlcsstoimage/images.rb', line 34

def create_image(html, params = {})
  body = { html: html }.merge(params).to_json
  options = { basic_auth: @auth, body: body, query: { includeId: true } }

  self.class.post("/v1/image", options)
end

#create_image_batch(variations, default_options = nil) ⇒ HTMLCSSToImage::ApiResponse

Creates several HTML/CSS or URL images in one API request.

Templates are not supported in batch requests.

Parameters:

  • variations (Array<Hash>)

    per-image values

  • default_options (Hash, nil) (defaults to: nil)

    shared values inherited by each variation; format may be png, jpg, webp, or pdf and only changes initially returned URL extensions

Returns:

See Also:



127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/htmlcsstoimage/images.rb', line 127

def create_image_batch(variations, default_options = nil)
  return ApiResponse.new(images: []) if variations.empty?

  body = { variations: variations }
  body[:default_options] = default_options unless default_options.nil?

  self.class.post(
    "/v1/image/batch",
    basic_auth: @auth,
    body: body.to_json
  )
end

#create_image_from_template(template_id, template_values = {}, params = {}, template_version: nil, format: nil, **keyword_values) ⇒ HTMLCSSToImage::ApiResponse

Deprecated.

Compatibility proxy for #generate_templated_image_url.

The third positional hash was accepted by previous versions but was not used. Its template_version value is now honored when present.

Parameters:

  • template_id (String)

    the saved template ID

  • template_values (Hash) (defaults to: {})

    values to substitute into the template

  • params (Hash) (defaults to: {})

    legacy options; only template_version is used

  • template_version (Integer, nil) (defaults to: nil)

    a specific template version

  • format (String, nil) (defaults to: nil)

    output format appended to the signed URL path: png, jpg, webp, or pdf

  • keyword_values (Hash)

    template values passed as Ruby keyword arguments

Returns:



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/htmlcsstoimage/signed_urls.rb', line 55

def create_image_from_template(
  template_id,
  template_values = {},
  params = {},
  template_version: nil,
  format: nil,
  **keyword_values
)
  params ||= {}
  template_values = template_values.merge(keyword_values)
  legacy_version =
    if params.is_a?(Hash)
      params[:template_version] || params["template_version"]
    end

  options = { template_version: template_version || legacy_version }
  options[:format] = format unless format.nil?

  generate_templated_image_url(template_id, template_values, **options)
end

#create_template(html, params = {}) ⇒ HTMLCSSToImage::ApiResponse

Creates an image template.

Parameters:

  • html (String)

    HTML for the template

  • params (Hash) (defaults to: {})

    template and rendering options

Options Hash (params):

  • :name (String)

    A short name to identify the template. Maximum length: 64.

  • :description (String)

    A description of the template. Maximum length: 1024.

  • :css (String)

    The CSS for the template.

  • :device_scale (Numeric)

    The pixel ratio for the screenshot. Minimum: 0.1, Maximum: 3.

  • :google_fonts (String)

    Google Fonts to load. Separate multiple fonts with |.

  • :max_wait_ms (Integer)

    The maximum time to wait before taking the screenshot. Minimum: 500, Maximum: 10000.

  • :ms_delay (Integer)

    Extra time in milliseconds to wait before taking the screenshot. Maximum: 10000.

  • :render_when_ready (Boolean)

    Wait until ScreenshotReady() is called from JavaScript before taking the screenshot.

  • :max_render_once (Boolean)

    Ensure images created from the template are only rendered and saved once.

  • :selector (String)

    A CSS selector for the element to capture.

  • :viewport_height (Integer)

    The Chrome viewport height. Both viewport dimensions must be set if using either.

  • :viewport_width (Integer)

    The Chrome viewport width. Both viewport dimensions must be set if using either.

  • :disable_twemoji (Boolean)

    Disable the Twemoji fallback and use native emoji fonts.

  • :color_scheme (String)

    Render using the light or dark browser color scheme.

  • :timezone (String)

    The browser timezone as an IANA timezone identifier, such as America/New_York.

  • :viewport_mobile (Boolean)

    Whether to honor the page's mobile viewport behavior.

  • :viewport_landscape (Boolean)

    Whether to render the viewport in landscape mode.

  • :viewport_touch (Boolean)

    Whether the viewport supports touch events.

  • :media_type (String)

    Render using print or screen media.

  • :jumbo_max_height (Integer)

    Maximum output height in jumbo mode. Requires jumbo_max_width.

  • :jumbo_max_width (Integer)

    Maximum output width in jumbo mode. Requires jumbo_max_height.

  • :proxy_id (String)

    The ID of an organization proxy to use for the render.

  • :storage_destination_id (String)

    The ID of an organization storage destination inherited by images created from the template.

  • :transparent_background (Boolean)

    Whether images created from the template should use a transparent background.

Returns:

See Also:



74
75
76
# File 'lib/htmlcsstoimage/templates.rb', line 74

def create_template(html, params = {})
  create_template_at_path("/v1/template", html, params)
end

#create_template_version(template_id, html, params = {}) ⇒ HTMLCSSToImage::ApiResponse

Creates a new version of a saved template.

Accepts the same options as #create_template.

Parameters:

  • template_id (String)

    the saved template ID

  • html (String)

    HTML for the new template version

  • params (Hash) (defaults to: {})

    template and rendering options

Returns:

See Also:



88
89
90
# File 'lib/htmlcsstoimage/templates.rb', line 88

def create_template_version(template_id, html, params = {})
  create_template_at_path("/v1/template/#{template_id}", html, params)
end

#create_templated_image(template_id, template_values = {}, template_version: nil, format: nil, **keyword_values) ⇒ HTMLCSSToImage::ApiResponse

Creates an image from a saved template with an API request.

Parameters:

  • template_id (String)

    the saved template ID

  • template_values (Hash) (defaults to: {})

    values to substitute into the template

  • template_version (Integer, nil) (defaults to: nil)

    a specific template version, or the latest when omitted

  • format (String, nil) (defaults to: nil)

    the format used in the initially returned URL: png, jpg, webp, or pdf; does not change the stored image definition

  • keyword_values (Hash)

    template values passed as Ruby keyword arguments

Returns:

See Also:



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/htmlcsstoimage/images.rb', line 95

def create_templated_image(
  template_id,
  template_values = {},
  template_version: nil,
  format: nil,
  **keyword_values
)
  template_values = template_values.merge(keyword_values)
  body = {
    template_id: template_id,
    template_values: template_values
  }
  body[:template_version] = template_version unless template_version.nil?
  body[:format] = format unless format.nil?

  self.class.post(
    "/v1/image",
    basic_auth: @auth,
    body: body.to_json,
    query: { includeId: true }
  )
end

#delete_image(image_id) ⇒ Boolean, HTMLCSSToImage::ApiResponse

Deletes an image.

Parameters:

  • image_id (String)

    the ID of the image to delete

Returns:

See Also:



146
147
148
149
150
151
152
# File 'lib/htmlcsstoimage/images.rb', line 146

def delete_image(image_id)
  response = self.class.delete("/v1/image/#{image_id}", basic_auth: @auth)

  return true if response.success?

  response
end

#delete_image_batch(image_ids) ⇒ Boolean, HTMLCSSToImage::ApiResponse

Deletes multiple images in one request.

Parameters:

  • image_ids (Array<String>)

    IDs of the images to delete

Returns:

See Also:



160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'lib/htmlcsstoimage/images.rb', line 160

def delete_image_batch(image_ids)
  return true if image_ids.empty?

  response = self.class.delete(
    "/v1/image/batch",
    basic_auth: @auth,
    body: { ids: image_ids }.to_json
  )

  return true if response.success?

  response
end

#generate_create_and_render_url(url, params = {}) ⇒ HTMLCSSToImage::ApiResponse

Generates a signed create-and-render URL for a URL screenshot.

This method makes no network requests. PDF options are omitted because the create-and-render endpoint does not support them. dedupe_duration_s is omitted because deduplication applies only to standard POST requests. False boolean values are omitted except for transparent_background, where both values are meaningful.

Parameters:

  • url (String)

    the fully qualified URL to capture

  • params (Hash) (defaults to: {})

    URL screenshot options; format may be png, jpg, webp, or pdf and is appended to the signed URL path instead of the query string

Returns:

See Also:



89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# File 'lib/htmlcsstoimage/signed_urls.rb', line 89

def generate_create_and_render_url(url, params = {})
  pairs = [["url", url.to_s]]
  format = params[:format] || params["format"]

  params
    .reject do |key, _value|
      %w[url format pdf_options dedupe_duration_s].include?(key.to_s)
    end
    .sort_by { |key, _value| key.to_s }
    .each do |key, value|
      next if value.nil?
      next if value == false && key.to_s != "transparent_background"

      case key.to_s
      when "headers"
        value.each { |name, header_value| pairs << ["headers", "#{name}:#{header_value}"] }
      when "additional_header_origins"
        value.each { |origin| pairs << ["additional_header_origins", origin.to_s] }
      else
        pairs << [key.to_s, signed_value(value)]
      end
    end

  query = Addressable::URI.form_encode(pairs)
  token = generate_hmac_token(query)
  format_path = format.nil? ? "" : "/#{format}"

  ApiResponse.new(
    url: "https://hcti.io/v1/image/create-and-render/#{@auth[:username]}/#{token}#{format_path}?#{query}"
  )
end

#generate_templated_image_url(template_id, template_values = {}, template_version: nil, format: nil, **keyword_values) ⇒ HTMLCSSToImage::ApiResponse

Generates a signed URL for rendering an image from a saved template.

This method makes no network requests. Hashes and arrays in template_values are encoded as JSON before the query string is signed.

Parameters:

  • template_id (String)

    the saved template ID

  • template_values (Hash) (defaults to: {})

    values to substitute into the template

  • template_version (Integer, nil) (defaults to: nil)

    a specific template version, or the latest when omitted

  • format (String, nil) (defaults to: nil)

    output format appended to the signed URL path: png, jpg, webp, or pdf

  • keyword_values (Hash)

    template values passed as Ruby keyword arguments

Returns:

See Also:



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/htmlcsstoimage/signed_urls.rb', line 15

def generate_templated_image_url(
  template_id,
  template_values = {},
  template_version: nil,
  format: nil,
  **keyword_values
)
  template_values = template_values.merge(keyword_values)
  pairs = []
  pairs << ["template_version", template_version.to_s] unless template_version.nil?

  template_values.sort_by { |key, _value| key.to_s }.each do |key, value|
    next if value.nil?

    pairs << [key.to_s, signed_value(value)]
  end

  query = Addressable::URI.form_encode(pairs)
  token = generate_hmac_token(query)
  separator = query.empty? ? "" : "?"
  format_path = format.nil? ? "" : "/#{format}"

  ApiResponse.new(
    url: "https://hcti.io/v1/image/#{template_id}/#{token}#{format_path}#{separator}#{query}"
  )
end

#list_template_versions(template_id, params = {}) ⇒ HTMLCSSToImage::ApiResponse

Retrieves versions of a saved template.

Parameters:

  • template_id (String)

    the saved template ID

  • params (Hash) (defaults to: {})

    pagination options

Options Hash (params):

  • :count (Integer)

    number of versions to return, up to 100

  • :max_version (Integer)

    pagination cursor returned by the previous request

Returns:

See Also:



35
36
37
38
39
40
41
# File 'lib/htmlcsstoimage/templates.rb', line 35

def list_template_versions(template_id, params = {})
  self.class.get(
    "/v1/template/#{template_id}",
    basic_auth: @auth,
    query: params
  )
end

#list_templates(params = {}) ⇒ HTMLCSSToImage::ApiResponse

Retrieves saved templates.

Parameters:

  • params (Hash) (defaults to: {})

    pagination options

Options Hash (params):

  • :count (Integer)

    number of templates to return, up to 100

  • :max_version (Integer)

    pagination cursor returned by the previous request

Returns:

See Also:



10
11
12
13
14
15
16
# File 'lib/htmlcsstoimage/templates.rb', line 10

def list_templates(params = {})
  self.class.get(
    "/v1/template",
    basic_auth: @auth,
    query: params
  )
end

#templates(params = {}) ⇒ HTMLCSSToImage::ApiResponse

Compatibility proxy for #list_templates.

Parameters:

  • params (Hash) (defaults to: {})

    pagination options

Returns:



22
23
24
# File 'lib/htmlcsstoimage/templates.rb', line 22

def templates(params = {})
  list_templates(params)
end

#url_to_image(url, params = {}) ⇒ HTMLCSSToImage::ApiResponse

Generates a screenshot of a public URL.

Parameters:

  • url (String)

    the fully qualified URL to capture

  • params (Hash) (defaults to: {})

    image creation options

Options Hash (params):

  • :format (String)

    The format used in the initially returned URL: png, jpg, webp, or pdf. This does not change the stored image definition or prevent rendering another supported format later.

  • :css (String)

    CSS to inject into the webpage.

  • :device_scale (Numeric)

    The pixel ratio for the screenshot. Minimum: 0.1, Maximum: 3.

  • :full_screen (Boolean)

    Take a screenshot of the entire scrollable page.

  • :max_wait_ms (Integer)

    The maximum time to wait before taking the screenshot. Minimum: 500, Maximum: 10000.

  • :ms_delay (Integer)

    Extra time in milliseconds to wait before taking the screenshot. Maximum: 10000.

  • :render_when_ready (Boolean)

    Wait until ScreenshotReady() is called from JavaScript before taking the screenshot.

  • :selector (String)

    A CSS selector for the element to capture.

  • :viewport_height (Integer)

    The Chrome viewport height. Both viewport dimensions must be set if using either.

  • :viewport_width (Integer)

    The Chrome viewport width. Both viewport dimensions must be set if using either.

  • :pdf_options (Hash)

    Options for generating a PDF, including page size, margins, scale, and background printing.

  • :disable_twemoji (Boolean)

    Disable the Twemoji fallback and use native emoji fonts.

  • :max_render_once (Boolean)

    Ensure the image is only rendered and saved once.

  • :dedupe_duration_s (Integer)

    Reuse an identical image created within this many seconds. Only supported for single-image POST requests.

  • :color_scheme (String)

    Render using the light or dark browser color scheme.

  • :timezone (String)

    The browser timezone as an IANA timezone identifier, such as America/New_York.

  • :block_consent_banners (Boolean)

    Attempt to block cookie and consent banners.

  • :headers (Hash{String => String})

    Custom HTTP headers to send to allowed origins.

  • :additional_header_origins (Array<String>)

    Additional exact origins allowed to receive custom headers.

  • :include_headers_on_subrequests (Boolean)

    Send custom headers on subrequests to allowed origins.

  • :identify_as_hcti (Boolean)

    Add X-HCTI-SCREENSHOT: 1 to the top-level page request.

  • :viewport_mobile (Boolean)

    Whether to honor the page's mobile viewport behavior.

  • :viewport_landscape (Boolean)

    Whether to render the viewport in landscape mode.

  • :viewport_touch (Boolean)

    Whether the viewport supports touch events.

  • :media_type (String)

    Render using print or screen media.

  • :proxy_id (String)

    The ID of an organization proxy to use for the render.

  • :storage_destination_id (String)

    The ID of an organization storage destination for the rendered image.

  • :jumbo_max_height (Integer)

    Maximum output height in jumbo mode. Requires jumbo_max_width.

  • :jumbo_max_width (Integer)

    Maximum output width in jumbo mode. Requires jumbo_max_height.

  • :transparent_background (Boolean)

    Whether to render the image with a transparent background.

Returns:

See Also:



78
79
80
81
82
83
# File 'lib/htmlcsstoimage/images.rb', line 78

def url_to_image(url, params = {})
  body = { url: url }.merge(params).to_json
  options = { basic_auth: @auth, body: body, query: { includeId: true } }

  self.class.post("/v1/image", options)
end