Skip to content
HTML/CSS to ImageDocs

JavaScript - HTML to Image Example

Generate PNG, JPG, WebP, and PDF output with JavaScript, using HTML/CSS or reusable templates rendered in Google Chrome.

Generating images with JavaScript

  1. Send your HTML/CSS to the API.
  2. The API renders it in Google Chrome.
  3. Read the generated image URL from the JSON response.

See Creating an image for request parameters. A response includes the image's url and id.

Example image generated from HTML with JavaScript

Authentication with JavaScript

Use HTTP Basic authentication with your API ID as the username and API key as the password. Find both in the dashboard. Keep credentials in server-side configuration or environment variables.

JavaScript example code

The example sends a POST request to https://hcti.io/v1/image. Image creation requires images:create. See authentication and API keys for scoped credentials and access errors.

Looking for the official npm client? See the Official npm client section on the TypeScript example page.

This example uses Node.js’s built-in fetch. Run it as an ES module on Node.js 18 or newer.

const API_ID = process.env.HCTI_API_ID;
const API_KEY = process.env.HCTI_API_KEY;
if (!API_ID || !API_KEY) throw new Error('Set HCTI_API_ID and HCTI_API_KEY');
// Define your HTML/CSS
const data = {
html: "<div class='box'>JavaScript ✅</div>",
css: ".box { border: 4px solid #03B875; padding: 20px; font-family: 'Roboto'; }",
google_fonts: "Roboto"
}
// Create an image by sending a POST to the API.
// Retrieve your api_id and api_key from the Dashboard. https://htmlcsstoimage.com/dashboard
const response = await fetch('https://hcti.io/v1/image', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Basic ' + Buffer.from(`${API_ID}:${API_KEY}`).toString('base64'),
},
body: JSON.stringify(data),
});
if (!response.ok) throw new Error(`API request failed: ${response.status}`);
console.log(await response.json());
// {"url": "https://hcti.io/v1/image/1113184e-419f-49f1-b231-2069942a186f"}

To see all of the available parameters, see: Creating an image.

If your code supports async/await, we recommend using the following.

This example uses the axios package. Install with npm install axios.

const axios = require('axios');
async function createImage() {
const payload = { html: "<div>Test</div>",
css: "div { background-color: blue; }" };
let headers = { auth: {
username: 'user-id',
password: 'api-key'
},
headers: {
'Content-Type': 'application/json'
}
}
try {
const response = await axios.post('https://hcti.io/v1/image', JSON.stringify(payload), headers);
console.log(response.data.url);
} catch (error) {
console.error(error);
}
}
createImage();

If you prefer not to install an HTTP library for making the request. This example shows you how to use the API without any dependencies.

const https = require('https')
const data = JSON.stringify({
html: "<div class='box'>JavaScript ✅</div>",
css: ".box { border: 4px solid #03B875; padding: 20px; font-family: 'Roboto'; }",
google_fonts: "Roboto"
})
// Retrieve your api_id and api_key from the Dashboard. https://htmlcsstoimage.com/dashboard
const apiId = "your-api-id"
const apiKey = "your-api-key"
const options = {
hostname: 'hcti.io',
port: 443,
path: '/v1/image',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Basic ' + Buffer.from(apiId + ':' + apiKey).toString('base64')
}
}
const req = https.request(options, (res) => {
console.log(`statusCode: ${res.statusCode}`)
let body = '';
res.setEncoding('utf8');
res.on('data', (chunk) => { body += chunk; });
res.on('end', () => {
if (res.statusCode < 200 || res.statusCode >= 300) {
console.error(`API request failed: ${res.statusCode}`, body);
return;
}
try { console.log(JSON.parse(body).url); }
catch (error) { console.error('Invalid JSON response', error); }
})
})
req.on('error', (error) => {
console.error(error)
})
req.write(data)
req.end()

Use the Fetch API to call your own backend. The backend validates the request and calls HCTI with server-side credentials using the example above. This keeps your API key out of browser code, including internal applications.

const json = {
html: "<div class='test'>Hello, world!</div>",
css: ".test { background-color: green; }"
};
const options = {
method: 'POST',
body: JSON.stringify(json),
headers: {
'Content-Type': 'application/json'
}
}
// Implement this route in your backend and return the HCTI JSON response.
fetch('/api/create-image', options)
.then(res => {
if (res.ok) {
return res.json();
} else {
return Promise.reject(res.status);
}
})
.then(data => {
// Image URL is available here
console.log(data.url)
})
.catch(err => console.error(err));

Need help?

Talk to a human. Email support@htmlcsstoimage.com and we’ll help you get started.