Rafael Camargo

How to easily convert HTML to image in NodeJS or in the browser

Ever thought about turning a piece of HTML into an image? Well, it’s totally possible. And even better, you can do it either on the server or right in the browser.

NodeJS

To generate an image from HTML on the server, you'll need a library called Puppeteer.

Puppeteer is a NodeJS library that lets you control Chrome or Chromium programmatically, without actually opening a browser window (headless mode). You can use it to automate web tasks like taking screenshots, generating PDFs, and getting content from websites that rely heavily on JavaScript, which traditional http request wouldn't be able to cut it.

npm install puppeteer

Once it's installed, you'll need to:

  1. Launch a browser instance.
  2. Open a new page.
  3. Set the page's HTML content.
  4. Convert the HTML into an image (screenshot).
  5. Close the browser.
const puppeteer = require('puppeteer');

async function init(){
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  const htmlContent = `
    <html>
    <body>
      <h1>Hello world!</h1>
    </body>
    </html>
  `;
  await page.setContent(htmlContent);
  await page.screenshot({
    path: 'image.png',
    fullPage: true
  });
  await browser.close();
}

init();

If you only want to capture part of the page or need a format other than PNG, page.screenshot accepts some options that allow you customize the output:

await page.screenshot({
  path: String,                      // File path to save the image
  type: 'png' || 'jpeg' || 'webp',   // Image format (default: 'png')
  quality: Number,                   // JPEG/WebP quality (0-100)
  fullPage: Boolean,                 // Capture the entire page (default: false)
  clip: {                            // Capture a specific portion of the page
    x: Number,                       // X coordinate
    y: Number,                       // Y coordinate
    width: Number,                   // Width of the capture area
    height: Number,                  // Height of the capture area
  },
  omitBackground: Boolean,           // Remove the background (default: false)
  encoding: 'binary' || 'base64',    // Encoding format (default: 'binary')
  captureBeyondViewport: Boolean,    // Capture outside viewport (default: true)
  optimizeForSpeed: Boolean,         // Optimize for speed (default: false)
});

Note: This post uses Puppeteer version 24.2.1.

Browser

In the browser, on the other hand, you'll need some help from a library called html2canvas.

You can install it via NPM:

npm install html2canvas

Or load it from a CDN directly in your HTML file:

<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>

Based on a process much simpler than Puppeteer, html2canvas just transforms a piece of HTML into a canvas asynchronously. As soon as the process is done, you just need to convert the canvas into an image and trigger a download.

function htmlToImage(elementId) {
  html2canvas(document.getElementById(elementId))
    .then(canvas => {
      const img = canvas.toDataURL('image/png');
      let link = document.createElement('a');
      link.href = img;
      link.download = 'image.png';
      link.click();
    });
}

Converting HTML to an image in the browser

Hands-on: In this Gist, you'll find, in a single HTML file, all the necessary code to run the example above locally. But if you want a working example of HTML-to-image conversion on the server (NodeJS), you can find it in this repository.

Learn more: If you liked this post, you might also enjoy learning how to create multiple borders for an HTML element using just CSS.

Great everyday programming tips every month.

You can also stay in the loop via RSS