JavaScript Usage Examples

Learn how to use the HTML to Image API with JavaScript, both in Node.js and in the browser.

Node.js Examples

Basic Setup

First, install the required packages:

npm install node-fetch
# or if using TypeScript
npm install node-fetch @types/node-fetch

HTML to Image Example

Here’s a simple example using Node.js:

import fetch from 'node-fetch';
import fs from 'fs/promises';

async function htmlToImage(html, css = '') {
  try {
    const response = await fetch('https://app.html2img.com/api/html', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-API-Key': process.env.HTML2IMG_API_KEY
      },
      body: JSON.stringify({
        html,
        css,
        width: 800,
        height: 600
      })
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.message || 'Failed to generate image');
    }

    const imageBuffer = await response.buffer();
    await fs.writeFile('output.png', imageBuffer);
    
    console.log('Image saved as output.png');
  } catch (error) {
    console.error('Error:', error.message);
  }
}

// Example usage
const html = `
  <div style="padding: 20px; background: #f0f0f0;">
    <h1>Hello from Node.js!</h1>
    <p>Generated at ${new Date().toLocaleString()}</p>
  </div>
`;

const css = `
  h1 { color: #2563eb; }
  p { color: #4b5563; }
`;

htmlToImage(html, css);

Screenshot Example

Taking a screenshot of a webpage:

import fetch from 'node-fetch';
import fs from 'fs/promises';

async function takeScreenshot(url) {
  try {
    const response = await fetch('https://app.html2img.com/api/screenshot', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-API-Key': process.env.HTML2IMG_API_KEY
      },
      body: JSON.stringify({
        url,
        width: 1200,
        height: 800,
        dpi: 2,
        fullpage: true
      })
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.message || 'Failed to take screenshot');
    }

    const imageBuffer = await response.buffer();
    await fs.writeFile('screenshot.png', imageBuffer);
    
    console.log('Screenshot saved as screenshot.png');
  } catch (error) {
    console.error('Error:', error.message);
  }
}

takeScreenshot('https://example.com');

Express.js Example

Here’s how to use it with Express.js:

import express from 'express';
import fetch from 'node-fetch';

const app = express();

app.get('/generate-image', async (req, res) => {
  try {
    const response = await fetch('https://app.html2img.com/api/html', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-API-Key': process.env.HTML2IMG_API_KEY
      },
      body: JSON.stringify({
        html: `
          <div style="padding: 20px; background: #f0f0f0;">
            <h1>Hello from Express!</h1>
            <p>Generated at ${new Date().toLocaleString()}</p>
          </div>
        `,
        width: 800,
        height: 600
      })
    });

    if (!response.ok) {
      throw new Error('Failed to generate image');
    }

    const imageBuffer = await response.buffer();
    
    res.set('Content-Type', 'image/png');
    res.send(imageBuffer);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

app.get('/screenshot', async (req, res) => {
  try {
    const { url = 'https://example.com' } = req.query;
    
    const response = await fetch('https://app.html2img.com/api/screenshot', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-API-Key': process.env.HTML2IMG_API_KEY
      },
      body: JSON.stringify({
        url,
        width: 1200,
        height: 800,
        dpi: 2,
        fullpage: true
      })
    });

    if (!response.ok) {
      throw new Error('Failed to take screenshot');
    }

    const imageBuffer = await response.buffer();
    
    res.set('Content-Type', 'image/png');
    res.send(imageBuffer);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

Browser Examples

Using Fetch API

Here’s how to use the API directly in the browser:

async function generateImage() {
  try {
    const response = await fetch('https://app.html2img.com/api/html', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-API-Key': 'your-api-key' // Be careful with API key exposure!
      },
      body: JSON.stringify({
        html: `
          <div style="padding: 20px; background: #f0f0f0;">
            <h1>Hello from the Browser!</h1>
            <p>Generated at ${new Date().toLocaleString()}</p>
          </div>
        `,
        width: 800,
        height: 600
      })
    });

    if (!response.ok) {
      throw new Error('Failed to generate image');
    }

    const blob = await response.blob();
    const imageUrl = URL.createObjectURL(blob);
    
    // Display the image
    const img = document.createElement('img');
    img.src = imageUrl;
    document.body.appendChild(img);
  } catch (error) {
    console.error('Error:', error.message);
  }
}

React Component Example

Here’s a React component that uses the API:

import { useState } from 'react';

function ImageGenerator() {
  const [imageUrl, setImageUrl] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const generateImage = async () => {
    setLoading(true);
    setError(null);
    
    try {
      const response = await fetch('https://app.html2img.com/api/html', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-API-Key': process.env.REACT_APP_HTML2IMG_API_KEY
        },
        body: JSON.stringify({
          html: `
            <div style="padding: 20px; background: #f0f0f0;">
              <h1>Hello from React!</h1>
              <p>Generated at ${new Date().toLocaleString()}</p>
            </div>
          `,
          width: 800,
          height: 600
        })
      });

      if (!response.ok) {
        throw new Error('Failed to generate image');
      }

      const blob = await response.blob();
      const url = URL.createObjectURL(blob);
      setImageUrl(url);
    } catch (error) {
      setError(error.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div>
      <button 
        onClick={generateImage}
        disabled={loading}
      >
        {loading ? 'Generating...' : 'Generate Image'}
      </button>
      
      {error && (
        <div style={{ color: 'red' }}>
          Error: {error}
        </div>
      )}
      
      {imageUrl && (
        <div>
          <img 
            src={imageUrl} 
            alt="Generated content"
            style={{ maxWidth: '100%' }}
          />
        </div>
      )}
    </div>
  );
}

export default ImageGenerator;

Vue Component Example

Here’s a Vue 3 component that uses the API:

<template>
  <div>
    <button 
      @click="generateImage"
      :disabled="loading"
    >
      {{ loading ? 'Generating...' : 'Generate Image' }}
    </button>
    
    <div v-if="error" class="error">
      Error: {{ error }}
    </div>
    
    <div v-if="imageUrl">
      <img 
        :src="imageUrl" 
        alt="Generated content"
        style="max-width: 100%"
      />
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';

const imageUrl = ref(null);
const loading = ref(false);
const error = ref(null);

const generateImage = async () => {
  loading.value = true;
  error.value = null;
  
  try {
    const response = await fetch('https://app.html2img.com/api/html', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-API-Key': import.meta.env.VITE_HTML2IMG_API_KEY
      },
      body: JSON.stringify({
        html: `
          <div style="padding: 20px; background: #f0f0f0;">
            <h1>Hello from Vue!</h1>
            <p>Generated at ${new Date().toLocaleString()}</p>
          </div>
        `,
        width: 800,
        height: 600
      })
    });

    if (!response.ok) {
      throw new Error('Failed to generate image');
    }

    const blob = await response.blob();
    imageUrl.value = URL.createObjectURL(blob);
  } catch (err) {
    error.value = err.message;
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.error {
  color: red;
  margin: 1rem 0;
}
</style>

When using the API in the browser, make sure to handle your API key securely. Never expose it directly in client-side code. Instead, proxy your requests through a backend server.

For production applications, consider implementing rate limiting, error handling, and loading states to provide a better user experience.