ScreenshotNeo

BlogHow-to

How to Export Multiple Divs as Images with html-to-image

Export every matching div as a PNG, JPEG, SVG, Blob, or canvas with html-to-image, with reliable downloads, fonts, CORS, and performance fixes.

By the ScreenshotNeo team30 September 20268 min read

How to Export Multiple Divs as Images with html-to-image

Use one html-to-image conversion per element. Select the divs, map them to toPng (or another output function), then save each returned result. The library does not export a NodeList in one call.

import { toPng } from 'html-to-image';

const cards = [...document.querySelectorAll('.export-card')];

const files = await Promise.all(
  cards.map(async (card, index) => ({
    name: `card-${index + 1}.png`,
    dataUrl: await toPng(card, { cacheBust: true })
  }))
);

for (const { name, dataUrl } of files) {
  const link = document.createElement('a');
  link.download = name;
  link.href = dataUrl;
  link.click();
}

This pattern follows the library’s documented Promise-based, one-node API and download approach. See the official GitHub README and npm documentation.

1. Install and prepare the cards

npm install html-to-image
<section class="cards">
  <article class="export-card" data-id="alpha">
    <h2>Alpha</h2>
    <p>This card becomes alpha.png.</p>
  </article>
  <article class="export-card" data-id="beta">
    <h2>Beta</h2>
    <p>This card becomes beta.png.</p>
  </article>
</section>
<button id="export" type="button">Export cards</button>
import { toPng } from 'html-to-image';

const exportButton = document.querySelector('#export');

exportButton.addEventListener('click', async () => {
  const cards = [...document.querySelectorAll('.export-card')];

  for (const [index, card] of cards.entries()) {
    const id = card.dataset.id || String(index + 1);
    const dataUrl = await toPng(card, { cacheBust: true });

    const link = document.createElement('a');
    link.download = `${id}.png`;
    link.href = dataUrl;
    link.click();
  }
});

Use a stable identifier from data-id when possible. Index-based names remain deterministic if the order is fixed.

html-to-image processes each selected DOM node as a separate conversion.
html-to-image processes each selected DOM node as a separate conversion.

2. Wait for fonts and images

Capture only after the visual state is ready. Otherwise a card can contain fallback fonts, unloaded images, or incomplete lazy content.

async function waitForAssets(root = document) {
  if (document.fonts?.ready) {
    await document.fonts.ready;
  }

  const images = [...root.querySelectorAll('img')];
  await Promise.all(images.map((image) => {
    if (image.complete) return Promise.resolve();
    return new Promise((resolve) => {
      image.addEventListener('load', resolve, { once: true });
      image.addEventListener('error', resolve, { once: true });
    });
  }));
}

await waitForAssets();
const cards = [...document.querySelectorAll('.export-card')];

For images served from another origin, the response must permit CORS. A canvas containing disallowed cross-origin content can become tainted and fail when the library tries to render it.

3. Export PNG, JPEG, SVG, Blob, canvas, or pixels

Function Result Use it when
toPng(node, options) PNG data URL You need lossless output or transparency.
toJpeg(node, { quality }) JPEG data URL You want smaller photographic files; the documented example uses quality: 0.95.
toSvg(node, options) SVG data URL You need scalable or editable vector output.
toBlob(node) PNG Blob You are sending files to an API or using object URLs.
toCanvas(node) HTMLCanvasElement You need further canvas processing.
toPixelData(node) Raw RGBA bytes You need image analysis or custom encoding.
import { toJpeg, toSvg, toBlob } from 'html-to-image';

const card = document.querySelector('.export-card');
const jpegUrl = await toJpeg(card, { quality: 0.95, backgroundColor: '#ffffff' });
const svgUrl = await toSvg(card);
const blob = await toBlob(card);

function downloadUrl(url, filename) {
  const link = document.createElement('a');
  link.download = filename;
  link.href = url;
  link.click();
}

downloadUrl(jpegUrl, 'card.jpg');
downloadUrl(svgUrl, 'card.svg');

if (blob) {
  const objectUrl = URL.createObjectURL(blob);
  downloadUrl(objectUrl, 'card.png');
  URL.revokeObjectURL(objectUrl);
}

4. Important options

  • filter excludes a node and its descendants. Hide buttons, selection handles, or private controls from the export.
  • backgroundColor supplies a CSS background, useful for JPEG because JPEG has no transparency.
  • width and height change the rendered node dimensions.
  • canvasWidth and canvasHeight scale the output canvas without changing the source layout.
  • cacheBust: true adds a cache-busting query to image URLs.
  • type and includeStyleProperties tune serialization and copied styles.
import { toPng } from 'html-to-image';

const dataUrl = await toPng(card, {
  cacheBust: true,
  backgroundColor: '#fff',
  width: 1200,
  height: 630,
  canvasWidth: 2400,
  canvasHeight: 1260,
  filter: (node) => !node.classList?.contains('no-export')
});

5. Reuse embedded fonts across cards

When many cards use the same web fonts, compute the font CSS once and pass it to each conversion. This avoids repeating font discovery and embedding work.

import { getFontEmbedCSS, toPng } from 'html-to-image';

const cards = [...document.querySelectorAll('.export-card')];
await document.fonts.ready;
const fontEmbedCSS = await getFontEmbedCSS(cards[0]);

for (const [index, card] of cards.entries()) {
  const dataUrl = await toPng(card, { fontEmbedCSS, cacheBust: true });
  const link = document.createElement('a');
  link.download = `card-${index + 1}.png`;
  link.href = dataUrl;
  link.click();
}

6. Choose safe concurrency

Promise.all is concise and can be fast for a few small cards. Dozens of large cards create multiple cloned DOM trees, SVG strings, canvases, and data URLs at once. Use a sequential loop or a small concurrency limit to reduce peak memory.

async function mapWithConcurrency(items, limit, worker) {
  const results = new Array(items.length);
  let next = 0;

  async function run() {
    while (true) {
      const index = next++;
      if (index >= items.length) return;
      results[index] = await worker(items[index], index);
    }
  }

  await Promise.all(
    Array.from({ length: Math.min(limit, items.length) }, run)
  );
  return results;
}

const cards = [...document.querySelectorAll('.export-card')];
const files = await mapWithConcurrency(cards, 2, async (card, index) => ({
  name: `card-${index + 1}.png`,
  dataUrl: await toPng(card, { cacheBust: true })
}));

Start with a limit of 1 or 2 for large cards, then adjust based on memory and user-perceived speed. This is an engineering recommendation derived from the library’s documented large-DOM and data-URI limitations.

7. Download many files reliably

Browsers can restrict a burst of automatic downloads. A short delay, or packaging files into a ZIP in your application, gives users a more predictable experience.

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

for (const { name, dataUrl } of files) {
  const link = document.createElement('a');
  link.download = name;
  link.href = dataUrl;
  link.click();
  await sleep(150);
}

For Blob output, call URL.revokeObjectURL after the browser has received the click. Keep filenames free of slashes and other platform-specific characters.

8. How html-to-image works and where it breaks

The library recursively clones the DOM, copies computed styles, embeds fonts and image URLs, serializes the clone, wraps it in an SVG foreignObject, and optionally draws that SVG on an off-screen canvas for PNG, JPEG, or pixel output.

  • Cross-origin assets: images or SVG resources without suitable CORS headers can taint the canvas.
  • Browser support: the normal path depends on Promise and SVG foreignObject. Internet Explorer lacks the required foreignObject support. Safari’s stricter security model can block rasterization; the documented workaround is rendering the SVG on a server.
  • Large DOM trees: huge cards can exceed browser data-URI or canvas limits. Reduce the capture size, split the card, or export sequentially.
  • Unsupported visual effects: browser rendering and CSS serialization do not guarantee that every feature, external resource, or pseudo-element will reproduce exactly.

9. Troubleshooting

Symptom Likely cause Fix
Blank or missing images Image not loaded or blocked by CORS. Wait for image load events and serve the image with CORS headers. Test the image URL directly.
Web font replaced by a fallback Capture ran before fonts were ready. Await document.fonts.ready; reuse fontEmbedCSS for repeated exports.
SecurityError or tainted canvas Cross-origin content was drawn without permission. Use same-origin assets or configure CORS. Do not expect client-side code to bypass another origin’s policy.
Safari fails while Chromium works Safari security restrictions around SVG foreignObject rasterization. Use SVG output or render the SVG on a server, as the project documentation recommends.
Export is clipped The node’s measured dimensions do not include the intended content. Set explicit width/height, ensure overflow content is present, and capture the correct wrapper.
Output is blurry Canvas dimensions match CSS dimensions. Increase canvasWidth and canvasHeight proportionally, or export SVG.
Browser becomes unresponsive Too many large conversions started together. Use sequential processing or a small concurrency limit and release Blob URLs.
Only the first file downloads Browser download protection blocked a burst. Add a short delay, ask the user to click each file, or create one ZIP.
Private controls appear in the image All descendants are included by default. Add a class and exclude it with filter.

10. Performance, reliability, and cost considerations

  • Measure before scaling: conversion time grows with DOM size, style complexity, embedded fonts, and image dimensions.
  • Control memory: avoid retaining many large data URLs; save or upload each result, then discard references.
  • Use the right format: PNG preserves detail and transparency, JPEG reduces photographic file size, SVG stays scalable, and Blob integrates with file APIs.
  • Make state deterministic: freeze animations, open the intended tab, apply theme classes, and wait for asynchronous content before capture.
  • Handle failures per card: wrap each conversion in try/catch so one problematic asset does not hide successful exports.
const results = [];

for (const [index, card] of cards.entries()) {
  try {
    results.push({
      ok: true,
      name: `card-${index + 1}.png`,
      dataUrl: await toPng(card, { cacheBust: true })
    });
  } catch (error) {
    results.push({
      ok: false,
      name: `card-${index + 1}.png`,
      error
    });
  }
}

11. Or skip the browser setup

If you need a screenshot of a live URL rather than a client-side DOM export, ScreenshotNeo provides a single GET request that returns PNG, JPEG, WebP, or PDF. Its capture can target an element by CSS selector and can load lazy images, apply custom CSS or JavaScript, set a viewport or device preset, and wait for a selector, delay, or network idle.

A capture service can remove common overlays before taking a page screenshot.
A capture service can remove common overlays before taking a page screenshot.

See the ScreenshotNeo API docs for parameters and response details.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

Cookie banners, newsletter popups, and chat widgets are removed before the shot. Bot checks, blank pages, failed loads, timeouts, and cache hits are never billed, and response headers identify the page verdict and billing status. An MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.

12. FAQ

Can I pass a NodeList directly to toPng?

No. Convert it to an array and call the function once for each node.

Should I use PNG or JPEG?

Choose PNG for transparency and sharp text. Choose JPEG when photographic content and smaller files matter.

Can I export only one child inside each card?

Yes. Select those child nodes instead of the card wrappers, or pass the desired child to the conversion function.

Does cacheBust fix CORS?

No. It changes URL caching behavior. The remote response still needs appropriate CORS permission.

When should I use server-side screenshots?

Use a server-side browser or screenshot API when you need a remote page, Safari-safe rasterization, centralized credentials, or reliable processing outside a user’s browser.