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

To convert HTML to a JPG in Node.js, render the markup in a real browser and capture the rendered page as a JPEG. With Playwright, the essential call is page.screenshot({ path: 'output.jpg', type: 'jpeg', quality: 80, fullPage: true }). Use fullPage: true for the complete scrollable document, or leave it out for only the current viewport.

This approach captures what users see: CSS, fonts, images, JavaScript, and layout after rendering. It does not turn the HTML source into an image by itself.

What you need before converting HTML to JPG

  • A supported Node.js release and a project with a package.json.
  • A browser automation library such as Playwright or Puppeteer.
  • The HTML you want to render, either as a URL or as a string assigned to a page.
  • A deliberate choice between a viewport image and a full-page image.

Install Playwright in a new project:

mkdir html-to-jpg
cd html-to-jpg
npm init -y
npm install playwright
npx playwright install chromium

The browser installation command downloads Chromium for Playwright. In a managed build environment, install the browser during the image-build step rather than on every request.

Convert a URL to JPG with Playwright

This complete script opens a URL, sets a deterministic viewport, waits for the page to load, writes a JPEG, and closes the browser even when an error occurs.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
const { chromium } = require('playwright');

(async () => {
  const browser = await chromium.launch({ headless: true });
  try {
    const page = await browser.newPage({
      viewport: { width: 1440, height: 900 },
      deviceScaleFactor: 1
    });

    await page.goto('https://example.com', {
      waitUntil: 'networkidle',
      timeout: 60_000
    });

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

Run it with node convert-url.js. The resulting file is a lossy JPEG. Raise quality when text or fine UI details need more fidelity; lower it when file size matters. The exact visual result depends on the installed Playwright and browser versions, operating system, fonts, and page content, so verify dimensions and appearance in your own environment.

Viewport capture versus full-page capture

Setting Result Use it when
Omit fullPage or set it to false Only the visible viewport is captured. You need a fixed-size thumbnail, social preview, or hero image.
fullPage: true The browser captures the complete scrollable document. You need an entire article, invoice, or report in one tall image.

A full-page JPG can become extremely tall. Downstream systems that expect a fixed width and height may need a viewport capture or a later resize step.

Convert an HTML string to JPG

Use page.setContent() when the HTML is generated by your application rather than hosted at a URL.

const { chromium } = require('playwright');

const html = `<!doctype html>
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
      body { font-family: Arial, sans-serif; margin: 40px; }
      .card { padding: 24px; background: #f3f4f6; border-radius: 12px; }
    </style>
  </head>
  <body>
    <div class="card"><h1>Monthly report</h1><p>Rendered in Node.js.</p></div>
  </body>
</html>`;

(async () => {
  const browser = await chromium.launch();
  try {
    const page = await browser.newPage({ viewport: { width: 1200, height: 800 } });
    await page.setContent(html, { waitUntil: 'networkidle' });
    await page.screenshot({
      path: 'report.jpg',
      type: 'jpeg',
      quality: 90,
      fullPage: true
    });
  } finally {
    await browser.close();
  }
})();

Relative images, stylesheets, and fonts in a string need resolvable URLs. Prefer absolute HTTPS URLs, embed small assets as data URLs, or serve the HTML from a local HTTP server. If a page uses client-side rendering, wait for the application to finish instead of assuming that navigation completion means the screen is ready.

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

Wait for fonts, images, and application rendering

There is no universal wait condition that works for every site. Network idle can be unsuitable for applications that keep analytics or WebSocket connections open. Combine a targeted condition with a bounded timeout:

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
await page.goto('https://example.com/dashboard', { waitUntil: 'domcontentloaded' });
await page.waitForSelector('[data-ready="true"]', { timeout: 30_000 });
await page.evaluate(() => document.fonts.ready);
await page.waitForTimeout(300); // only if the page has a known late animation

For images that affect layout, wait for them explicitly:

await page.waitForFunction(() => Array.from(document.images)
  .every(img => img.complete));

Disable or freeze animations when repeatable pixels matter. You can inject CSS with page.addStyleTag() or a stylesheet in the document. Keep the viewport, browser version, fonts, device scale factor, color scheme, and headless mode consistent across runs because browser rendering can vary across hosts.

Capture a particular element

When the JPG should contain a card, chart, or invoice rather than the page, locate the element and use its locator screenshot:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const card = page.locator('.invoice-card');
await card.screenshot({
  path: 'invoice-card.jpg',
  type: 'jpeg',
  quality: 85
});

The element must be visible and have a rendered size. If it is below the fold, scroll it into view first. A selector that matches multiple elements should be narrowed to one specific element.

Keep the image in memory instead of writing a file

Playwright returns image data from page.screenshot() even when no path is supplied:

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
const jpegBuffer = await page.screenshot({ type: 'jpeg', quality: 80, fullPage: true });
// Upload jpegBuffer to object storage or return it from an HTTP endpoint.

This avoids temporary files for APIs and queues. Set the response content type to image/jpeg when returning the buffer to a client.

Using Puppeteer instead

Puppeteer exposes the same browser-rendering model. Its screenshot API can write a file and can also return image bytes (a Uint8Array) or a base64 representation, which is useful when the next step is an upload or database write.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
npm install puppeteer
const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch({ headless: true });
  try {
    const page = await browser.newPage();
    await page.setViewport({ width: 1440, height: 900, deviceScaleFactor: 1 });
    await page.goto('https://example.com', {
      waitUntil: 'networkidle0',
      timeout: 60_000
    });
    const jpegBytes = await page.screenshot({
      type: 'jpeg',
      quality: 80,
      fullPage: true
    });
    require('fs').writeFileSync('output.jpg', jpegBytes);
  } finally {
    await browser.close();
  }
})();

Choose the library that fits your existing project and the controls you need. Both perform a browser capture; neither is a text-only HTML converter.

JPEG options and trade-offs

Quality

Playwright’s quality option applies to JPEG output. It does not apply to PNG. Higher values preserve more detail and generally produce larger files; the useful setting depends on the page and your delivery constraints, so inspect representative output.

Transparency

JPEG does not support an alpha channel. Playwright’s omitBackground option is not applicable to JPEG. If transparent pixels are required, capture a format that supports transparency, such as PNG, and convert only if transparency is no longer needed.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

Scale and dimensions

Viewport dimensions and device scale factor influence the pixel dimensions. Set them explicitly, then check the actual output with your image pipeline. Do not assume CSS pixels and final image pixels are identical when using a scale factor above one.

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

Custom page state

Set cookies, headers, authentication, timezone, or other state before navigation when the page requires a logged-in or locale-specific view. Never place credentials in a URL or commit them to source control.

Common failures and fixes

Symptom Likely cause Fix
Executable doesn't exist The browser binary was not installed. Run npx playwright install chromium, or install browsers during your container build.
Blank or partially rendered JPG Capture happened before JavaScript, fonts, or images finished. Wait for a page-specific selector, document.fonts.ready, and required images; avoid an arbitrary long sleep as the only condition.
Navigation timeout The site is slow, blocked, or never becomes idle. Use a realistic timeout, switch from networkidle to domcontentloaded, and wait for a specific readiness signal.
Missing styles or images Relative URLs cannot resolve from setContent(), or requests are blocked. Use absolute URLs, a local server, or embedded assets; inspect network and console errors.
Unexpected page size Full-page capture includes all scrollable content, or layout changes after load. Choose viewport capture deliberately and freeze late layout changes before taking the screenshot.
Different pixels between machines Different fonts, browser builds, OS rendering, scale, or color settings. Pin the browser and fonts, set viewport and scale explicitly, and capture in the same container image.
JPEG looks soft or has artifacts Quality is too low or text is being compressed as a photographic image. Increase JPEG quality, or use PNG when lossless text and transparency are more important than file size.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Performance, reliability, and cost considerations

Launching a browser for every request is simple but expensive in latency and memory. For a service, reuse a browser process, create isolated pages or contexts per job, cap concurrency, and close pages in a finally block. Reusing a page without clearing cookies and storage can leak one customer’s state into another capture.

Measure your own pages for navigation time, screenshot time, output dimensions, and memory use. The available API documentation does not establish a universal performance number or output-size limit. Large full-page captures and pages with many images require more memory than small viewport shots.

For reliable jobs, record the target URL, browser version, viewport, wait condition, and failure reason. Retry transient navigation failures with a limit, but do not blindly retry authentication errors or deterministic invalid URLs. Keep screenshots and logs separate from secrets such as cookies and authorization headers.

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.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Or skip the browser setup

ScreenshotNeo is a hosted website screenshot API and MCP server. It accepts a URL and returns PNG, JPEG, WebP, or PDF. Before capture it accepts cookie or consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be disabled. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status.

One GET request is enough:

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

See the complete option list and response details in the ScreenshotNeo documentation. The service supports full-page capture, CSS-element capture, dark mode, device presets and custom viewports, retina scale, PDF paper and page options, custom CSS and JavaScript, pre-capture clicks, hidden selectors, waits for selectors or network idle, ad and tracker blocking, custom headers, cookies, user agents and authorization, timezone and geolocation, transparent backgrounds, resizing, configurable caching, signed image links, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, a usage API, and an OpenAPI specification. Its parameter names are compatible with those used by other screenshot APIs, which can simplify migration.

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)

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}`);

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 per month without a card; paid plans start at $5 for 3,000 screenshots, and every feature is available on every plan. Create a free ScreenshotNeo account.

Frequently Asked Questions

Can Node.js convert HTML to JPG without launching a browser?

Not for a faithful rendering of modern HTML and CSS. A browser engine is needed to execute JavaScript, load fonts and images, and compute layout before pixels can be captured.

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

Should I use JPEG or PNG for text-heavy documents?

Use JPEG when lossy compression is acceptable. Use PNG when you need lossless text edges or transparency; JPEG cannot preserve an alpha channel.

Why is my full-page image so tall?

Full-page mode includes the entire scrollable document. Use a viewport capture for fixed dimensions, or split and resize the result in a separate image-processing step.

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.