Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The most direct server-side method is node-html-to-image. It renders an HTML string in Puppeteer’s Chromium browser and can write a JPEG file or return a Buffer. Set type: 'jpeg', choose a quality value, and give your document or target element explicit dimensions so the output is predictable.

This guide covers complete-document rendering, element-only captures, direct Puppeteer control, browser-only conversion, deployment issues, and a no-browser API alternative.

Quick start: HTML string to a JPG file

Install the package in a Node.js project:

npm install node-html-to-image

Create html-to-jpg.js:

const nodeHtmlToImage = require('node-html-to-image');

(async () => {
  await nodeHtmlToImage({
    output: './image.jpg',
    type: 'jpeg',
    quality: 85,
    html: `<!doctype html>
      <html>
        <head>
          <style>
            body {
              margin: 0;
              width: 1200px;
              height: 630px;
              font-family: Arial, sans-serif;
              display: grid;
              place-items: center;
              background: white;
            }
          </style>
        </head>
        <body><h1>Hello from HTML</h1></body>
      </html>`
  });
})();

Run it with node html-to-jpg.js. The resulting image.jpg is a JPEG. The package defaults to PNG, so omitting type: 'jpeg' does not produce the requested format. The quality value controls JPEG compression; higher values generally preserve more detail while producing larger files.

Why dimensions matter

The rendered size comes from your CSS when using node-html-to-image. Set a width and height on body or on a containing element rather than relying on content that can reflow. For social cards, for example, 1200px by 630px is a deliberate canvas; for an invoice, use the dimensions appropriate to the page you are generating.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
Philips 24 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 241V8LB
  • CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
  • WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
  • A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents

Return a Buffer instead of writing a file

Omit output and the function returns image data in memory. This is useful when an HTTP route needs to stream the image, upload it to storage, or attach it to a message.

const nodeHtmlToImage = require('node-html-to-image');

(async () => {
  const imageBuffer = await nodeHtmlToImage({
    type: 'jpeg',
    quality: 85,
    html: `<html><body style="margin:0">
      <div style="width:800px;height:450px;padding:40px">
        <h1>Render me</h1>
      </div>
    </body></html>`
  });

  // Example: write it yourself, upload it, or send it in a response.
  require('fs').writeFileSync('./from-buffer.jpg', imageBuffer);
})();

Keep the Buffer binary. Do not convert it to a UTF-8 string before writing or uploading.

Capture one element from an HTML document

For cards, receipts, badges, and other components, pass a CSS selector. The selector tells the package to capture that element rather than the whole body.

const nodeHtmlToImage = require('node-html-to-image');

(async () => {
  await nodeHtmlToImage({
    output: './card.jpg',
    type: 'jpeg',
    quality: 90,
    selector: '#card',
    html: `<!doctype html>
      <html>
        <head>
          <style>
            body { margin: 0; background: #eee; }
            #card {
              width: 800px;
              height: 450px;
              box-sizing: border-box;
              padding: 48px;
              background: #172554;
              color: white;
            }
          </style>
        </head>
        <body>
          <section id="card"><h1>Product card</h1></section>
        </body>
      </html>`
  });
})();

Make the selector match exactly one visible element and give that element an explicit size. If it matches nothing, the capture cannot produce the intended result; if it matches several nodes, use a more specific selector.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Wait for fonts, images, and other assets

Screenshotting immediately after HTML is parsed can capture an unfinished layout. Images may still be loading, web fonts may not have applied, and scripts may still be changing the DOM. Use the package’s documented waitUntil setting where appropriate, and make sure every asset URL is reachable from the rendering process.

Rank #2
Philips 22 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 221V8LB
  • CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
  • SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors

Practical asset checklist

  • Use absolute, reachable URLs for remote images and stylesheets, or embed assets as data URLs.
  • Ensure the server running Chromium can resolve DNS and make outbound HTTPS requests.
  • Wait for the page’s intended readiness state before capture.
  • Keep a fixed layout while assets load so late font changes do not alter the image dimensions.
  • Use a pre-screenshot hook when you need to configure the Puppeteer page before rendering.

There is no universal wait time that guarantees every application is ready. A readiness condition tied to your page is more reliable than an arbitrary delay.

Use Puppeteer directly for full browser control

node-html-to-image is convenient, but direct Puppeteer is better when you need explicit viewport settings, request interception, browser lifecycle management, or custom page setup.

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  try {
    const page = await browser.newPage();
    await page.setViewport({
      width: 1200,
      height: 630,
      deviceScaleFactor: 1
    });

    await page.setContent(`<!doctype html>
      <html>
        <body style="margin:0">
          <h1>Hello</h1>
        </body>
      </html>`, { waitUntil: 'load' });

    await page.screenshot({
      path: './image.jpg',
      type: 'jpeg',
      quality: 85,
      fullPage: true
    });
  } finally {
    await browser.close();
  }
})();

Install Puppeteer separately with npm install puppeteer. The try/finally block is important: it closes Chromium even when navigation or screenshotting fails.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

When direct Puppeteer is the better choice

  • Viewport fidelity: set width, height, and device scale explicitly.
  • Navigation: use page.goto() for a URL or page.setContent() for an HTML string.
  • Element screenshots: locate an element and use its screenshot method when you need DOM-level control.
  • Network control: intercept requests, block unwanted resources, or provide authentication before loading.
  • Lifecycle control: reuse a browser process for a batch, while creating isolated pages per job.

Convert an existing browser DOM with html-to-image

If the HTML is already rendered in a browser, a client-side library avoids starting a server-side Chromium process. html-to-image exposes toJpeg, which returns a JPEG data URL and accepts a quality value from 0 to 1.

import * as htmlToImage from 'html-to-image';

const node = document.getElementById('card');
const dataUrl = await htmlToImage.toJpeg(node, {
  quality: 0.92,
  backgroundColor: '#ffffff'
});

const link = document.createElement('a');
link.download = 'card.jpg';
link.href = dataUrl;
link.click();

This approach is appropriate when the user already has the DOM in a browser tab. It is not a replacement for rendering an arbitrary HTML string on a server: it needs a real DOM node and the browser’s current state.

Rank #3
Sale
Dell 24 Monitor - SE2426H - 23.8-inch FHD (1920x1080) 144Hz 1ms Display, in-Plane Switching (IPS) Technology, AMD FreeSync™, TÜV 3-Star 2X HDMI, Tilt
  • Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
  • Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
  • Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
  • In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
  • Ultra-thin bezels: Maximize your viewing experience with thin bezels.

Choose the right approach

Approach Input Runtime Output Best fit
node-html-to-image HTML string Node.js with Puppeteer File or Buffer Fast setup for server-side templates and cards
Direct Puppeteer HTML string or URL Node.js with Chromium File or other browser-controlled result Viewport, network, fonts, and lifecycle control
html-to-image Existing DOM element Browser JPEG data URL Client-side downloads without server Chromium

All three can produce a JPEG, but they solve different input and deployment problems. A server rendering pipeline must account for a compatible Chromium executable; containers and serverless platforms may require custom Puppeteer-compatible binary configuration.

Build a reliable HTML-to-JPG pipeline

Make layout deterministic

Declare the capture width, height, margins, background, and box sizing in CSS. Avoid viewport-dependent units when the output must be identical across jobs. For full-page captures, decide whether the document should grow with content or be constrained to a fixed canvas.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Handle remote resources deliberately

Cross-origin images, protected URLs, blocked requests, and unavailable fonts can produce blank areas or different wrapping. Embed critical assets, provide credentials through your page setup when required, and test the same network conditions used in production.

Choose quality based on use

JPEG is lossy and works best for photographic or gradient-heavy artwork. Text-heavy graphics can show ringing or blurry edges; compare a quality around 85 with a higher value for your particular design. If you need transparency or pixel-perfect flat text, JPEG may be the wrong format even though it is widely supported.

Control concurrency

Each new browser process consumes memory and startup time. For batches, reuse a browser and create separate pages, but cap concurrent pages to the resources available on the host. Close pages and browsers on both success and failure.

Rank #4
Samsung 27" Essential S3 (S36GD) Series FHD 1800R Curved Computer Monitor
  • CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
  • SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
  • MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
  • KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
  • INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshooting common failures

The output is PNG, not JPG

Set type: 'jpeg' in node-html-to-image or in page.screenshot. A filename ending in .jpg does not change the encoded format.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The image is blank or cropped

Check that the HTML has a visible body, that the selector exists, and that dimensions are nonzero. For Puppeteer, set the viewport before rendering. For a selector capture, inspect whether padding, overflow, or a collapsed parent hides the target.

Images or fonts are missing

Verify URLs from the server, wait for the intended readiness state, and check that remote resources do not require browser credentials. Embed critical images or fonts when reproducibility matters.

Chromium fails to launch

Confirm that Puppeteer’s browser executable is present and compatible with the deployment image. Minimal containers often lack required system libraries; serverless deployments may need a separately packaged Puppeteer-compatible binary and an explicit executable path.

The process hangs

Ensure every browser is closed in a finally block, set a navigation or job timeout in your surrounding application, and investigate requests that never resolve. Do not leave orphaned Chromium processes after a failed job.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Sale
Sceptre New 22-Inch Gaming Monitor, FHD 1080p, Up to 144Hz, HDMI, DisplayPort, Built-in Speakers, Machine Black (E225W-FW144 Series, 2026)
  • 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
  • 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
  • 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.

Text changes between runs

Font availability, late-loading styles, viewport differences, and nondeterministic application data are common causes. Pin the viewport, load the same fonts, wait for them before capture, and make the HTML data deterministic.

Or skip the browser setup

ScreenshotNeo accepts one GET request and returns a PNG, JPEG, WebP, or PDF. It handles the browser infrastructure for you and exposes controls for full-page capture with lazy images, CSS-selector element capture, dark mode, 12 device presets or any viewport, retina scale, custom CSS and JavaScript, clicks, selector or network-idle waits, blocked ads and trackers, custom headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, caching, signed links, asynchronous webhooks, bulk capture of up to 100 URLs per call, usage reporting, and an OpenAPI specification.

Use the API from the command line:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Node.js:

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

Python:

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)

See the ScreenshotNeo documentation for parameters and response handling. Cookie and consent banners, newsletter popups, and chat widgets are removed before the shot; bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and response headers identify the page verdict and billing status. Its 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 per month with no card. Paid plans start at $5 for 3,000 screenshots; every feature is available on every plan, and yearly billing gives two months free. Create a free ScreenshotNeo account.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Security and operational notes

  • Treat HTML and URLs as untrusted input when they come from users. Apply your own validation and isolation rules.
  • Do not expose API keys, cookies, authorization headers, or private HTML in client-side code.
  • Limit resource sizes and capture dimensions to prevent memory exhaustion.
  • Log the input identifier, selected dimensions, format, quality, and failure reason so an unsuccessful conversion can be reproduced.
  • Return the correct MIME type, image/jpeg, when serving a JPEG over HTTP.

Frequently Asked Questions

Is JPG different from JPEG in Node.js?

No. JPG and JPEG refer to the same image format. Use type: 'jpeg'; the file extension can be .jpg or .jpeg.

Can I convert a remote web page instead of an HTML string?

Yes. Use Puppeteer’s page.goto() and then page.screenshot(), or use ScreenshotNeo’s URL-based API when you do not want to operate Chromium yourself.

Why does my JPEG have a white background?

JPEG has no transparency channel. Set an explicit background color for predictable output; use PNG instead when transparent pixels are required.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.