htmlcsstoimage-api 0.1.4 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. checksums.yaml +4 -4
  2. data/.github/workflows/ruby.yml +2 -0
  3. data/Gemfile.lock +3 -1
  4. data/README.md +299 -10
  5. data/htmlcsstoimage.gemspec +4 -2
  6. data/lib/htmlcsstoimage/client.rb +36 -0
  7. data/lib/htmlcsstoimage/images.rb +193 -0
  8. data/lib/htmlcsstoimage/recordings.rb +108 -0
  9. data/lib/htmlcsstoimage/request_override_resource_type.rb +33 -0
  10. data/lib/htmlcsstoimage/signed_urls.rb +130 -0
  11. data/lib/htmlcsstoimage/templates.rb +100 -0
  12. data/lib/htmlcsstoimage/version.rb +2 -1
  13. data/lib/htmlcsstoimage.rb +9 -151
  14. metadata +26 -29
  15. data/cassettes/HTMLCSSToImage/_create_image/accepts_additional_params.yml +0 -66
  16. data/cassettes/HTMLCSSToImage/_create_image/creates_an_image.yml +0 -64
  17. data/cassettes/HTMLCSSToImage/_create_template/creates_a_new_template.yml +0 -62
  18. data/cassettes/HTMLCSSToImage/_delete_image/deletes_an_image.yml +0 -60
  19. data/cassettes/HTMLCSSToImage/_templates/retrieves_templates.yml +0 -110
  20. data/cassettes/HTMLCSSToImage/_url_to_image/accepts_additional_params.yml +0 -64
  21. data/cassettes/HTMLCSSToImage/_url_to_image/creates_an_image_from_a_url.yml +0 -64
  22. data/docs/HTMLCSSToImage/ApiResponse.html +0 -124
  23. data/docs/HTMLCSSToImage.html +0 -1340
  24. data/docs/_config.yml +0 -1
  25. data/docs/_index.html +0 -122
  26. data/docs/class_list.html +0 -51
  27. data/docs/css/common.css +0 -1
  28. data/docs/css/full_list.css +0 -58
  29. data/docs/css/style.css +0 -496
  30. data/docs/file.README.html +0 -187
  31. data/docs/file_list.html +0 -56
  32. data/docs/frames.html +0 -17
  33. data/docs/index.html +0 -187
  34. data/docs/js/app.js +0 -314
  35. data/docs/js/full_list.js +0 -216
  36. data/docs/js/jquery.js +0 -4
  37. data/docs/method_list.html +0 -107
  38. data/docs/top-level-namespace.html +0 -110
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: c33bcd3c7a212ce188b7016c5910a5053f801005a2eb93d367b2cc2722a98aee
4
- data.tar.gz: de1d090df2591e9c37b2a60b9331b83cb700c106e971782d2bce16345086e6cc
3
+ metadata.gz: fe88de5675da52a0325a6b46c0d223487bd6ff47d86df11c6bb26706ec1058ab
4
+ data.tar.gz: '069102c0a4c9bb0434567df163d2e9daf246ab1c410e384ec54418564fb9c557'
5
5
  SHA512:
6
- metadata.gz: eaebdc8ab7326430a86bbca299376e94cf890ba4f7e4bceaf2b7aa7e4ef18d974ce3223defba69015dcccfaf78bc1ed2aa101069d626f36130d53b55f5633f83
7
- data.tar.gz: 490e852085597ab9c65bf6c9a812853f3585a5c4c9ec0a26a0a816dba86d64e3db436249ff6bcf77d360c770828728685ca2d0a3392b8f6c3a8dade3ec092d1d
6
+ metadata.gz: f39ad806edc68e1f47ab9e2edc3b04d02dca1a6dfa94d3f9ee88abb08fb9eae23fa914038c95bd0fa6b5f82f884700bcced11eeca24847eabbcdf7c6c8c70537
7
+ data.tar.gz: c4d476e92f6ef02bac29152e8452d755cdc099ace8d4e34412abe60adac67e759d315f3cae24c0cbe770213a5d828129807cb3c0a9515ca548ea9ed8522a27c6
@@ -15,6 +15,8 @@ jobs:
15
15
  - uses: actions/checkout@v4
16
16
  - name: Set up Ruby
17
17
  uses: ruby/setup-ruby@v1
18
+ with:
19
+ ruby-version: '3.3'
18
20
  - name: Install dependencies
19
21
  run: bundle install
20
22
  - name: Run tests
data/Gemfile.lock CHANGED
@@ -1,7 +1,7 @@
1
1
  PATH
2
2
  remote: .
3
3
  specs:
4
- htmlcsstoimage-api (0.1.3)
4
+ htmlcsstoimage-api (1.0.0)
5
5
  addressable (> 2.5.0)
6
6
  httparty (> 0.10)
7
7
 
@@ -56,6 +56,7 @@ GEM
56
56
  addressable (>= 2.8.0)
57
57
  crack (>= 0.3.2)
58
58
  hashdiff (>= 0.4.0, < 2.0.0)
59
+ yard (0.9.45)
59
60
 
60
61
  PLATFORMS
61
62
  ruby
@@ -69,6 +70,7 @@ DEPENDENCIES
69
70
  rspec (~> 3.0)
70
71
  vcr
71
72
  webmock
73
+ yard (~> 0.9)
72
74
 
73
75
  BUNDLED WITH
74
76
  2.5.23
data/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  Ruby client for the [HTML/CSS to Image API](https://htmlcsstoimage.com).
6
6
 
7
- Generate png, jpg or webp images with Ruby. Renders exactly like Google Chrome.
7
+ Generate PNG, JPG, WebP, or PDF files with Ruby. Renders exactly like Google Chrome.
8
8
 
9
9
  ## Installation
10
10
 
@@ -42,12 +42,14 @@ client = HTMLCSSToImage.new
42
42
  ```
43
43
 
44
44
  ### Create an image
45
+
45
46
  Generate an image from HTML/CSS. Returns a URL to the image.
46
47
 
47
48
  ```ruby
48
49
  image = client.create_image("<div>Hello, world</div>",
49
50
  css: "div { background-color: red; font-family: Roboto; }",
50
- google_fonts: "Roboto")
51
+ google_fonts: "Roboto",
52
+ format: "webp")
51
53
 
52
54
  image
53
55
  => #<HTMLCSSToImage::ApiResponse url="https://hcti.io/v1/image/254b444c-dd82-4cc1-94ef-aa4b3a6870a6", id="254b444c-dd82-4cc1-94ef-aa4b3a6870a6">
@@ -56,20 +58,265 @@ image.url
56
58
  ```
57
59
 
58
60
  ### Delete an image
61
+
59
62
  Delete an existing image. Removes the image from HCTI servers and clears the CDN.
60
63
 
61
64
  ```ruby
62
65
  client.delete_image("254b444c-dd82-4cc1-94ef-aa4b3a6870a6")
63
66
  ```
64
67
 
68
+ Delete several images in one request:
69
+
70
+ ```ruby
71
+ client.delete_image_batch([
72
+ "254b444c-dd82-4cc1-94ef-aa4b3a6870a6",
73
+ "60ab90f0-c019-4d0d-a234-cc39e1f2226e"
74
+ ])
75
+ ```
76
+
65
77
  ### URL to image
78
+
66
79
  Generate a screenshot of any public URL.
67
80
 
68
81
  ```ruby
69
82
  image = client.url_to_image("https://github.com", viewport_width: 800, viewport_height: 1200)
70
83
  ```
71
84
 
85
+ ### Create a PDF
86
+
87
+ Select PDF output with `format: "pdf"`; use `pdf_options` to configure its layout:
88
+
89
+ ```ruby
90
+ pdf = client.create_image(
91
+ "<h1>Quarterly report</h1>",
92
+ format: "pdf",
93
+ pdf_options: {
94
+ print_background: true,
95
+ margins: ["20px", "20px", "20px", "20px"]
96
+ }
97
+ )
98
+ ```
99
+
100
+ ### Create a batch of images
101
+
102
+ Create several HTML/CSS or URL images in one API request. Each variation inherits
103
+ values from `default_options` and can override them.
104
+
105
+ ```ruby
106
+ images = client.create_image_batch(
107
+ [
108
+ { html: "<h1>First</h1>", format: "jpg" },
109
+ { html: "<h1>Second</h1>", transparent_background: true }
110
+ ],
111
+ { viewport_width: 1200, format: "webp" }
112
+ )
113
+ ```
114
+
115
+ ## Recordings
116
+
117
+ Record HTML/CSS or a public webpage as MP4, WebM, or GIF. Use
118
+ `create_html_css_recording` for HTML/CSS and `create_url_recording` for a webpage:
119
+
120
+ ```ruby
121
+ recording = client.create_url_recording(
122
+ "https://example.com",
123
+ duration_ms: 10000,
124
+ viewport_width: 1280,
125
+ viewport_height: 720,
126
+ actions: [{ type: "simple_scroll" }],
127
+ output: { format: "mp4" }
128
+ )
129
+
130
+ recording.id
131
+ recording.status_url
132
+ recording.recording_url
133
+
134
+ animation = client.create_html_css_recording(
135
+ "<h1>Hello</h1>",
136
+ css: "@keyframes fade { from { opacity: 0; } to { opacity: 1; } } h1 { animation: fade 2s; font-family: Roboto; }",
137
+ google_fonts: "Roboto",
138
+ duration_ms: 3000,
139
+ duration_mode: "fixed",
140
+ output: { format: "gif", scale: 0.5 }
141
+ )
142
+ ```
143
+
144
+ Both methods accept browser, timeline, and output options as hashes, following
145
+ the image methods. Options pass through to the API without local validation.
146
+ Omitted settings use API defaults. Recordings do not include audio.
147
+
148
+ Triggers and actions use a `type` discriminator. For example, wait until an
149
+ element is visible, click a button, and hold the result:
150
+
151
+ ```ruby
152
+ demo = client.create_url_recording(
153
+ "https://example.com/demo",
154
+ duration_ms: 5000,
155
+ duration_mode: "fixed",
156
+ trigger: { type: "element_visible", selector: "#demo", timeout_ms: 2000 },
157
+ actions: [
158
+ { type: "click", selector: "#start", if_not_found: [{ type: "error" }] },
159
+ { type: "stall", duration_ms: 1000 }
160
+ ]
161
+ )
162
+ ```
163
+
164
+ Nested branches run on the API. For JavaScript actions, omitting `if_error` or
165
+ setting it to `nil` fails on a script error; `if_error: []` ignores errors.
166
+ Empty arrays, explicit `nil`, `false`, and zero values are preserved in JSON.
167
+
168
+ A `scroll` action moves through ordered `steps`. Each step's `duration_ms` is
169
+ required and must be at least 1:
170
+
171
+ ```ruby
172
+ client.create_url_recording(
173
+ "https://example.com",
174
+ duration_ms: 6000,
175
+ actions: [
176
+ { type: "scroll", steps: [
177
+ { to: { type: "selector", selector: "#pricing" }, duration_ms: 1200, easing: "ease_in_out_cubic" },
178
+ { to: { type: "position", position: "bottom" }, duration_ms: 1500 }
179
+ ] }
180
+ ]
181
+ )
182
+ ```
183
+
184
+ Embed or request `recording_url` directly; the request waits until the
185
+ recording is ready, so checking status is optional. To inspect progress, fetch
186
+ the current status once with:
187
+
188
+ ```ruby
189
+ status = client.fetch_recording_status(recording.id)
190
+ puts status.status
191
+ puts status.attempt_count
192
+ ```
193
+
194
+ HTTP 200 and 202 both return status information. The states `ready`, `failed`,
195
+ and `cancelled` are terminal. A successful status fetch can report a failed
196
+ recording, and `status.error` can describe an earlier, retryable attempt.
197
+ `status.status` is the raw API string. Treat values not listed here, which
198
+ newer API versions may add, as unknown; the client passes them through as-is.
199
+ API errors and transport failures follow the existing image-method behavior.
200
+
201
+ Delete recordings individually or in a batch:
202
+
203
+ ```ruby
204
+ client.delete_recording("recording-id")
205
+ client.delete_recording_batch(["first-id", "second-id"])
206
+ ```
207
+
208
+ Deletion returns `true` when accepted, or the API response on failure. Empty
209
+ batch lists succeed without an API request, matching `delete_image_batch`.
210
+
211
+ See the [recording guide](https://docs.htmlcsstoimage.com/getting-started/recordings/),
212
+ [actions reference](https://docs.htmlcsstoimage.com/parameters/actions/), and
213
+ [trigger reference](https://docs.htmlcsstoimage.com/parameters/trigger/) for
214
+ options and examples.
215
+
216
+ ## Signed URLs
217
+
218
+ Signed URLs let another application, browser, or service render an image on
219
+ demand without exposing your API key. Generating a signed URL does not make an
220
+ API request; the image is created when the resulting URL is requested.
221
+
222
+ Both signed URL methods return an `HTMLCSSToImage::ApiResponse`. Use `.url` to
223
+ retrieve the URL:
224
+
225
+ ```ruby
226
+ signed_image = client.generate_create_and_render_url("https://example.com")
227
+ signed_image.url
228
+ # => "https://hcti.io/v1/image/create-and-render/user-id/..."
229
+ ```
230
+
231
+ Generate signed URLs in trusted server-side code. The API key is used to create
232
+ the HMAC signature and should never be exposed to a browser or end user. Query
233
+ parameters are covered by that signature, so modifying them after generation
234
+ invalidates the URL. Remember that the URL and its query values remain visible
235
+ to anyone who receives it.
236
+
237
+ [Learn more about create-and-render and signed URLs](https://docs.htmlcsstoimage.com/getting-started/create-and-render/).
238
+
239
+ ### Sign a URL screenshot
240
+
241
+ Use `generate_create_and_render_url` when you want HCTI to capture a public
242
+ webpage each time the signed URL is requested. Pass the target URL first,
243
+ followed by the same screenshot options accepted by `url_to_image`.
244
+
245
+ ```ruby
246
+ signed_image = client.generate_create_and_render_url(
247
+ "https://example.com/dashboard",
248
+ css: ".navigation { display: none; }",
249
+ headers: { "X-Preview-Mode" => "enabled" },
250
+ additional_header_origins: ["https://api.example.com"],
251
+ include_headers_on_subrequests: true,
252
+ identify_as_hcti: true,
253
+ format: "webp",
254
+ viewport_width: 1200,
255
+ viewport_height: 630,
256
+ transparent_background: false
257
+ )
258
+
259
+ signed_image.url
260
+ # => "https://hcti.io/v1/image/create-and-render/user-id/..."
261
+ ```
262
+
263
+ `pdf_options` is not supported by the create-and-render endpoint and
264
+ `dedupe_duration_s` only applies to standard POST requests, so both are omitted
265
+ when generating this URL. Other boolean options set to `false` are omitted,
266
+ except `transparent_background`, where both `true` and `false` are meaningful.
267
+ Custom headers are encoded in the URL and must not contain long-lived secrets.
268
+
269
+ ### Sign a templated image
270
+
271
+ Use `generate_templated_image_url` to substitute values into a saved template
272
+ when the signed URL is requested. Pass `template_version` to pin the URL to a
273
+ specific version; omit it to use the latest template version.
274
+
275
+ ```ruby
276
+ signed_image = client.generate_templated_image_url(
277
+ "t-56c64be5-5861-4148-acec-aaaca452027f",
278
+ {
279
+ title: "Hello, world!",
280
+ customer: {
281
+ name: "Ada",
282
+ plan: "Pro"
283
+ }
284
+ },
285
+ template_version: 1596829374001,
286
+ format: "webp"
287
+ )
288
+
289
+ signed_image.url
290
+ # => "https://hcti.io/v1/image/t-56c64be5-.../signed-token?template_version=...&customer=...&title=..."
291
+ ```
292
+
293
+ Hashes and arrays in `template_values` are serialized as JSON. Values set to
294
+ `nil` are omitted from the signed query string.
295
+
296
+ #### Changed in 0.2.0: template URL signatures
297
+
298
+ Ruby client 0.1.x URL-decoded the query string before generating its HMAC.
299
+ Version 0.2.0 instead signs the encoded query string exactly as it appears in
300
+ the generated URL, as required by the current API.
301
+
302
+ This means regenerating a template URL with the same inputs produces a
303
+ different token after upgrading from 0.1.x. Previously generated URLs are not
304
+ modified and continue to work.
305
+
306
+ `create_image_from_template` remains available as a compatibility proxy:
307
+
308
+ ```ruby
309
+ signed_image = client.create_image_from_template(
310
+ "t-56c64be5-5861-4148-acec-aaaca452027f",
311
+ { title: "Hello, world!" }
312
+ )
313
+ ```
314
+
315
+ Its legacy third argument was previously ignored. It remains unsupported except
316
+ for `template_version`; other keys in that argument are ignored.
317
+
72
318
  ## Templates
319
+
73
320
  A template allows you to define HTML that includes variables to be substituted at the time of image creation. [Learn more about templates](https://docs.htmlcsstoimage.com/getting-started/templates/).
74
321
 
75
322
  ```ruby
@@ -77,22 +324,45 @@ template = client.create_template("<div>{{title}}</div>")
77
324
  # => #<HTMLCSSToImage::ApiResponse template_id="t-56c64be5-5861-4148-acec-aaaca452027f", template_version=1596829374001>
78
325
 
79
326
  # Get templates
80
- all_templates = client.templates
81
-
82
- # Create a signed URL for a templated image
83
- image = client.create_image_from_template(template.template_id, { title: "Hello, world!" })
84
- # => #<HTMLCSSToImage::ApiResponse url="https://hcti.io/v1/image/t-56c64be5-5861-4148-acec-aaaca452027f/3aaa814dd998b302cc62b3550ddb35e8b9117c5ecea286da904eced0a3f44d9e?title=Hello%2C%20world%21">
85
-
86
- image.url
87
- # => "https://hcti.io/v1/image/t-56c64be5-5861-4148-acec-aaaca452027f/3aaa814dd998b302cc62b3550ddb35e8b9117c5ecea286da904eced0a3f44d9e?title=Hello%2C%20world%21"
327
+ all_templates = client.list_templates(count: 25)
328
+
329
+ # Get versions of one template
330
+ versions = client.list_template_versions(template.template_id, count: 25)
331
+
332
+ # Create a new version
333
+ version = client.create_template_version(
334
+ template.template_id,
335
+ "<div class='updated'>{{title}}</div>"
336
+ )
337
+
338
+ # Create a templated image with an API request
339
+ created_image = client.create_templated_image(
340
+ template.template_id,
341
+ { title: "Hello, world!" },
342
+ template_version: version.template_version,
343
+ format: "webp"
344
+ )
88
345
  ```
89
346
 
347
+ For signed, on-demand template images, see “Sign a templated image” in the
348
+ Signed URLs section above. `templates` remains available as a compatibility
349
+ alias for `list_templates`.
350
+
90
351
  ### Additional methods
352
+
91
353
  See the [ruby-client docs for all of the available methods](https://htmlcsstoimage.github.io/ruby-client/HTMLCSSToImage.html).
92
354
 
93
355
  ## Available parameters
356
+
94
357
  For detailed information on all the available parameters, visit the docs: https://docs.htmlcsstoimage.com/getting-started/using-the-api/
95
358
 
359
+ The client passes supported API parameters through as JSON. Recent additions
360
+ include `dedupe_duration_s`, `storage_destination_id`,
361
+ `transparent_background`, `format`, `proxy_id`, `jumbo_max_width`, `jumbo_max_height`,
362
+ and, for URL screenshots, `headers`, `additional_header_origins`,
363
+ `include_headers_on_subrequests`, `identify_as_hcti`, and
364
+ `block_consent_banners`.
365
+
96
366
  ## Development
97
367
 
98
368
  After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
@@ -102,6 +372,7 @@ To install this gem onto your local machine, run `bundle exec rake install`. To
102
372
  To generate the Yard docs, run `yard doc -o docs` and commit the changes.
103
373
 
104
374
  ## Support
375
+
105
376
  For help with the API, you can also contact `support@htmlcsstoimage.com`.
106
377
 
107
378
  ## Contributing
@@ -115,3 +386,21 @@ The gem is available as open source under the terms of the [MIT License](https:/
115
386
  ## Code of Conduct
116
387
 
117
388
  Everyone interacting in the project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/htmlcsstoimage/ruby-client/blob/main/CODE_OF_CONDUCT.md).
389
+
390
+ ## Templated image batches
391
+
392
+ Create images from one or more templates with shared defaults and ordered variations:
393
+
394
+ ```ruby
395
+ result = client.create_templated_image_batch(
396
+ [
397
+ { template_values: { title: "First" } },
398
+ { template_id: "t-other", template_values: { title: "Second" } }
399
+ ],
400
+ { template_id: "t-card", template_version: 3, format: "webp" }
401
+ )
402
+ ```
403
+
404
+ Omitted fields inherit defaults. Supplying a template ID resets the inherited version; omit its version to use latest. Template value objects merge recursively on the API; arrays, scalars, and explicit null values replace defaults. Results preserve input order and identical images reuse existing assets. Each merged values object must be nonempty and satisfy its template's required variables.
405
+
406
+ See the [API reference](https://docs.htmlcsstoimage.com/getting-started/using-the-api/#batch-templated-image-creation) for plan limits and examples.
@@ -10,14 +10,15 @@ Gem::Specification.new do |spec|
10
10
  spec.email = ["support@htmlcsstoimage.com"]
11
11
 
12
12
  spec.summary = %q{Ruby client for the HTML/CSS to Image API.}
13
- spec.description = %q{Ruby client for the HTML/CSS to Image API. Generate a png, jpg or webp images with Ruby. Renders exactly like Google Chrome. }
13
+ spec.description = %q{Ruby client for the HTML/CSS to Image API. Generate PNG, JPG, WebP, or PDF images and MP4, WebM, or GIF recordings with Ruby. Renders exactly like Google Chrome. }
14
14
  spec.homepage = "https://docs.htmlcsstoimage.com/example-code/ruby"
15
15
  spec.license = "MIT"
16
+ spec.required_ruby_version = ">= 2.7.0"
16
17
 
17
18
  # Specify which files should be added to the gem when it is released.
18
19
  # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
19
20
  spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
20
- `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features|doc)/}) }
21
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features|doc|docs|cassettes)/}) }
21
22
  end
22
23
  spec.bindir = "exe"
23
24
  spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
@@ -32,4 +33,5 @@ Gem::Specification.new do |spec|
32
33
  spec.add_development_dependency "pry-byebug"
33
34
  spec.add_development_dependency "vcr"
34
35
  spec.add_development_dependency "webmock"
36
+ spec.add_development_dependency "yard", "~> 0.9"
35
37
  end
@@ -0,0 +1,36 @@
1
+ # Client for creating images, recordings, and managing templates with HTML/CSS to Image.
2
+ class HTMLCSSToImage
3
+ include HTTParty
4
+
5
+ base_uri "https://hcti.io"
6
+ headers "Content-Type" => "application/json"
7
+ format :json
8
+
9
+ # A structured API response with attribute-style access to JSON fields.
10
+ class ApiResponse < OpenStruct
11
+ end
12
+
13
+ parser(
14
+ proc do |body, format|
15
+ case format
16
+ when :json
17
+ JSON.parse(body, object_class: ApiResponse)
18
+ else
19
+ body
20
+ end
21
+ end
22
+ )
23
+
24
+ # Creates an instance of HTMLCSSToImage with API credentials.
25
+ # If credentials are not provided, the client uses the `HCTI_USER_ID`
26
+ # and `HCTI_API_KEY` environment variables.
27
+ #
28
+ # @see https://htmlcsstoimage.com/dashboard
29
+ #
30
+ # @param user_id [String] the user ID for the account
31
+ # @param api_key [String] the API key for the account
32
+ # @return [HTMLCSSToImage] an instance of the API client
33
+ def initialize(user_id: ENV["HCTI_USER_ID"], api_key: ENV["HCTI_API_KEY"])
34
+ @auth = { username: user_id, password: api_key }
35
+ end
36
+ end
@@ -0,0 +1,193 @@
1
+ class HTMLCSSToImage
2
+ # Converts HTML/CSS to an image with the API.
3
+ #
4
+ # @see https://docs.htmlcsstoimage.com/getting-started/using-the-api
5
+ #
6
+ # @param html [String] HTML to render, as a snippet or an entire webpage
7
+ # @param params [Hash] image creation options
8
+ # @option params [String] :format 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.
9
+ # @option params [String] :css The CSS for your image.
10
+ # @option params [Numeric] :device_scale The pixel ratio for the screenshot. Minimum: `0.1`, Maximum: `3`.
11
+ # @option params [String] :google_fonts Google Fonts to load. Separate multiple fonts with `|`.
12
+ # @option params [Integer] :max_wait_ms The maximum time to wait before taking the screenshot. Minimum: `500`, Maximum: `10000`.
13
+ # @option params [Integer] :ms_delay Extra time in milliseconds to wait before taking the screenshot. Maximum: `10000`.
14
+ # @option params [Boolean] :render_when_ready Wait until `ScreenshotReady()` is called from JavaScript before taking the screenshot.
15
+ # @option params [String] :selector A CSS selector for the element to capture.
16
+ # @option params [Integer] :viewport_height The Chrome viewport height. Both viewport dimensions must be set if using either.
17
+ # @option params [Integer] :viewport_width The Chrome viewport width. Both viewport dimensions must be set if using either.
18
+ # @option params [Hash] :pdf_options Options for generating a PDF, including page size, margins, scale, and background printing.
19
+ # @option params [Boolean] :disable_twemoji For HTML/CSS, true disables default Twemoji replacement. For URLs, only explicit false injects Twemoji; omitted or true leaves the page unchanged.
20
+ # @option params [Boolean] :max_render_once Ensure the image is only rendered and saved once.
21
+ # @option params [Integer] :dedupe_duration_s Reuse an identical image created within this many seconds. Only supported for single-image POST requests.
22
+ # @option params [String] :color_scheme Render using the `light` or `dark` browser color scheme.
23
+ # @option params [String] :timezone The browser timezone as an IANA timezone identifier, such as `America/New_York`.
24
+ # @option params [Boolean] :viewport_mobile Whether to honor the page's mobile viewport behavior.
25
+ # @option params [Boolean] :viewport_landscape Whether to render the viewport in landscape mode.
26
+ # @option params [Boolean] :viewport_touch Whether the viewport supports touch events.
27
+ # @option params [String] :media_type Render using `print` or `screen` media.
28
+ # @option params [String] :proxy_id The ID of an organization proxy to use for the render.
29
+ # @option params [Array<Hash>] :request_overrides Browser request block rules, such as `{ action: "block", resource_types: [RequestOverrideResourceType::Script] }`. Requires a paid plan.
30
+ # @option params [String] :storage_destination_id The ID of an organization storage destination for the rendered image.
31
+ # @option params [Integer] :jumbo_max_height Maximum output height in jumbo mode. Requires `jumbo_max_width`.
32
+ # @option params [Integer] :jumbo_max_width Maximum output width in jumbo mode. Requires `jumbo_max_height`.
33
+ # @option params [Boolean] :transparent_background Whether to render the image with a transparent background.
34
+ # @return [HTMLCSSToImage::ApiResponse] image details, including `.url`
35
+ def create_image(html, params = {})
36
+ body = { html: html }.merge(params).to_json
37
+ options = { basic_auth: @auth, body: body, query: { includeId: true } }
38
+
39
+ self.class.post("/v1/image", options)
40
+ end
41
+
42
+ # Generates a screenshot of a public URL.
43
+ #
44
+ # @see https://docs.htmlcsstoimage.com/getting-started/url-to-image/
45
+ #
46
+ # @param url [String] the fully qualified URL to capture
47
+ # @param params [Hash] image creation options
48
+ # @option params [String] :format 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.
49
+ # @option params [String] :css CSS to inject into the webpage.
50
+ # @option params [Numeric] :device_scale The pixel ratio for the screenshot. Minimum: `0.1`, Maximum: `3`.
51
+ # @option params [Boolean] :full_screen Take a screenshot of the entire scrollable page.
52
+ # @option params [Integer] :max_wait_ms The maximum time to wait before taking the screenshot. Minimum: `500`, Maximum: `10000`.
53
+ # @option params [Integer] :ms_delay Extra time in milliseconds to wait before taking the screenshot. Maximum: `10000`.
54
+ # @option params [Boolean] :render_when_ready Wait until `ScreenshotReady()` is called from JavaScript before taking the screenshot.
55
+ # @option params [String] :selector A CSS selector for the element to capture.
56
+ # @option params [Integer] :viewport_height The Chrome viewport height. Both viewport dimensions must be set if using either.
57
+ # @option params [Integer] :viewport_width The Chrome viewport width. Both viewport dimensions must be set if using either.
58
+ # @option params [Hash] :pdf_options Options for generating a PDF, including page size, margins, scale, and background printing.
59
+ # @option params [Boolean] :disable_twemoji For HTML/CSS, true disables default Twemoji replacement. For URLs, only explicit false injects Twemoji; omitted or true leaves the page unchanged.
60
+ # @option params [Boolean] :max_render_once Ensure the image is only rendered and saved once.
61
+ # @option params [Integer] :dedupe_duration_s Reuse an identical image created within this many seconds. Only supported for single-image POST requests.
62
+ # @option params [String] :color_scheme Render using the `light` or `dark` browser color scheme.
63
+ # @option params [String] :timezone The browser timezone as an IANA timezone identifier, such as `America/New_York`.
64
+ # @option params [Boolean] :block_consent_banners Attempt to block cookie and consent banners.
65
+ # @option params [Hash{String => String}] :headers Custom HTTP headers to send to allowed origins.
66
+ # @option params [Array<String>] :additional_header_origins Additional exact origins allowed to receive custom headers.
67
+ # @option params [Boolean] :include_headers_on_subrequests Send custom headers on subrequests to allowed origins.
68
+ # @option params [Boolean] :identify_as_hcti Add `X-HCTI-SCREENSHOT: 1` to the top-level page request.
69
+ # @option params [Boolean] :viewport_mobile Whether to honor the page's mobile viewport behavior.
70
+ # @option params [Boolean] :viewport_landscape Whether to render the viewport in landscape mode.
71
+ # @option params [Boolean] :viewport_touch Whether the viewport supports touch events.
72
+ # @option params [String] :media_type Render using `print` or `screen` media.
73
+ # @option params [String] :proxy_id The ID of an organization proxy to use for the render.
74
+ # @option params [Array<Hash>] :request_overrides Browser request block rules, such as `{ action: "block", resource_types: [RequestOverrideResourceType::Script] }`. Requires a paid plan.
75
+ # @option params [String] :storage_destination_id The ID of an organization storage destination for the rendered image.
76
+ # @option params [Integer] :jumbo_max_height Maximum output height in jumbo mode. Requires `jumbo_max_width`.
77
+ # @option params [Integer] :jumbo_max_width Maximum output width in jumbo mode. Requires `jumbo_max_height`.
78
+ # @option params [Boolean] :transparent_background Whether to render the image with a transparent background.
79
+ # @return [HTMLCSSToImage::ApiResponse] image details, including `.url`
80
+ def url_to_image(url, params = {})
81
+ body = { url: url }.merge(params).to_json
82
+ options = { basic_auth: @auth, body: body, query: { includeId: true } }
83
+
84
+ self.class.post("/v1/image", options)
85
+ end
86
+
87
+ # Creates an image from a saved template with an API request.
88
+ #
89
+ # @see https://docs.htmlcsstoimage.com/getting-started/templates/
90
+ #
91
+ # @param template_id [String] the saved template ID
92
+ # @param template_values [Hash] values to substitute into the template
93
+ # @param template_version [Integer, nil] a specific template version, or the latest when omitted
94
+ # @param format [String, nil] the format used in the initially returned URL: `png`, `jpg`, `webp`, or `pdf`; does not change the stored image definition
95
+ # @param keyword_values [Hash] template values passed as Ruby keyword arguments
96
+ # @return [HTMLCSSToImage::ApiResponse] image details, including `.url`
97
+ def create_templated_image(
98
+ template_id,
99
+ template_values = {},
100
+ template_version: nil,
101
+ format: nil,
102
+ **keyword_values
103
+ )
104
+ template_values = template_values.merge(keyword_values)
105
+ body = {
106
+ template_id: template_id,
107
+ template_values: template_values
108
+ }
109
+ body[:template_version] = template_version unless template_version.nil?
110
+ body[:format] = format unless format.nil?
111
+
112
+ self.class.post(
113
+ "/v1/image",
114
+ basic_auth: @auth,
115
+ body: body.to_json,
116
+ query: { includeId: true }
117
+ )
118
+ end
119
+
120
+ # Creates several HTML/CSS or URL images in one API request.
121
+ #
122
+ # For template batches, use #create_templated_image_batch.
123
+ #
124
+ # @see https://docs.htmlcsstoimage.com/getting-started/using-the-api
125
+ #
126
+ # @param variations [Array<Hash>] per-image values
127
+ # @param default_options [Hash, nil] shared values inherited by each variation; `format` may be `png`, `jpg`, `webp`, or `pdf` and only changes initially returned URL extensions
128
+ # @return [HTMLCSSToImage::ApiResponse] batch response with images available at `.images`
129
+ def create_image_batch(variations, default_options = nil)
130
+ return ApiResponse.new(images: []) if variations.empty?
131
+
132
+ body = { variations: variations }
133
+ body[:default_options] = default_options unless default_options.nil?
134
+
135
+ self.class.post(
136
+ "/v1/image/batch",
137
+ basic_auth: @auth,
138
+ body: body.to_json
139
+ )
140
+ end
141
+
142
+ # Creates images from one or more templates in a single request.
143
+ # Objects in template_values merge recursively; arrays, scalars and null replace defaults.
144
+ # Supplying template_id resets the inherited version; omit a version to use latest.
145
+ # @param variations [Array<Hash>] per-image template options; results preserve this order
146
+ # @param default_options [Hash, nil] shared template_id, template_version, template_values and format
147
+ # @return [HTMLCSSToImage::ApiResponse] batch response with results at `.images`
148
+ def create_templated_image_batch(variations, default_options = nil)
149
+ return ApiResponse.new(images: []) if variations.empty?
150
+
151
+ body = { variations: variations }
152
+ body[:default_options] = default_options unless default_options.nil?
153
+ self.class.post(
154
+ "/v1/image/batch/templated",
155
+ basic_auth: @auth,
156
+ body: body.to_json
157
+ )
158
+ end
159
+
160
+ # Deletes an image.
161
+ #
162
+ # @see https://docs.htmlcsstoimage.com/getting-started/using-the-api
163
+ #
164
+ # @param image_id [String] the ID of the image to delete
165
+ # @return [Boolean, HTMLCSSToImage::ApiResponse] true on success, or the API response on failure
166
+ def delete_image(image_id)
167
+ response = self.class.delete("/v1/image/#{image_id}", basic_auth: @auth)
168
+
169
+ return true if response.success?
170
+
171
+ response
172
+ end
173
+
174
+ # Deletes multiple images in one request.
175
+ #
176
+ # @see https://docs.htmlcsstoimage.com/getting-started/using-the-api
177
+ #
178
+ # @param image_ids [Array<String>] IDs of the images to delete
179
+ # @return [Boolean, HTMLCSSToImage::ApiResponse] true on success, or the API response on failure
180
+ def delete_image_batch(image_ids)
181
+ return true if image_ids.empty?
182
+
183
+ response = self.class.delete(
184
+ "/v1/image/batch",
185
+ basic_auth: @auth,
186
+ body: { ids: image_ids }.to_json
187
+ )
188
+
189
+ return true if response.success?
190
+
191
+ response
192
+ end
193
+ end