User Agents

Web browsers and everyday web tech, explained

HTML to Image: Playwright & Puppeteer Guide

· 4 min read · Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Converting an HTML file to an image is useful for generating thumbnails, social previews, or capturing a webpage's visual state. Both Playwright and Puppeteer can render HTML in a headless browser and screenshot it as PNG or JPEG. This guide walks you through the process step by step, covering setup, code, and common pitfalls.

What You'll Need

  • Node.js installed (version 14 or higher recommended).
  • A terminal or command prompt.
  • An HTML file you want to convert (e.g., example.html).
  • Basic familiarity with JavaScript and npm.

Step-by-Step

  1. Set up a project folder. Create a new directory and navigate into it in your terminal.
  2. Initialize a Node.js project. Run npm init -y to create a package.json file.
  3. Choose your library and install it.
    • For Playwright: run npm install playwright and then npx playwright install chromium (downloads the browser).
    • For Puppeteer: run npm install puppeteer (it downloads Chromium automatically).
  4. Create a script file. For example, screenshot.js.
  5. Write the Playwright code. Here's a minimal example:
    const { chromium } = require('playwright');
    
    (async () => {
      const browser = await chromium.launch();
      const page = await browser.newPage();
      await page.goto('file:///path/to/example.html');
      await page.screenshot({ path: 'output.png' });
      await browser.close();
    })();
  6. Write the Puppeteer code. Here's the equivalent:
    const puppeteer = require('puppeteer');
    
    (async () => {
      const browser = await puppeteer.launch();
      const page = await browser.newPage();
      await page.goto('file:///path/to/example.html');
      await page.screenshot({ path: 'output.png' });
      await browser.close();
    })();
  7. Run your script. Execute node screenshot.js in the terminal. The image will be saved in the specified path.
  8. Adjust viewport and full-page capture. By default, the screenshot captures the visible viewport. To capture the entire page, set fullPage: true in the screenshot options. To control the viewport size, use page.setViewportSize({ width: 1280, height: 720 }) before navigating.
  9. Set a delay if needed. If your page loads dynamic content, add await page.waitForTimeout(1000) (or use waitForSelector) to give scripts time to render.
  10. Choose image format and quality. For JPEG, set type: 'jpeg' and quality: 80 (0-100). PNG is lossless and the default.

Common Mistakes

  • Using a relative file path incorrectly. The file:// URL must be absolute. Use path.resolve('example.html') to construct it.
  • Forgetting to close the browser. Always call browser.close() to avoid hanging processes.
  • Not waiting for fonts or images. Screenshots can be taken before external resources load. Use page.goto(..., { waitUntil: 'networkidle0' }) or a delay.
  • Assuming Puppeteer and Playwright have identical APIs. They are similar but not the same; check the docs for your chosen library.

Tips

  • Use a consistent viewport. Set the viewport to a specific width and height to get predictable output.
  • Consider device scale factor. For high-DPI screenshots, set deviceScaleFactor: 2 in the viewport options to get crisp images.
  • Handle dynamic content gracefully. Use page.waitForSelector() to wait for a specific element to appear.
  • Use environment variables for paths. This makes your script portable.
  • Test with a simple HTML file first. Create a minimal file with a heading and a colored background to verify everything works.

Troubleshooting

  • Screenshot is blank or white. This usually means the page didn't load. Check the file path and ensure the HTML file exists. Also, try using waitUntil: 'networkidle0'.
  • Browser fails to launch. For Playwright, run npx playwright install to download browsers. For Puppeteer, if the download failed, try npm install puppeteer --force or use PUPPETEER_SKIP_DOWNLOAD and manually install Chrome.
  • Image is cut off. Set fullPage: true to capture the entire scrollable area.
  • Script hangs. Ensure you close the browser after the screenshot. Use try/finally to guarantee cleanup.
  • Fonts look different. Headless browsers may not have all system fonts. Embed web fonts or use a font that is installed on the system.

Frequently Asked Questions

Can I convert HTML to an image without a browser?

No, you need a browser engine to render HTML. Playwright and Puppeteer are the standard tools for this.

What image formats are supported?

Both libraries support PNG and JPEG. PNG is lossless and good for text; JPEG is smaller but may have artifacts.

Can I capture a specific element instead of the whole page?

Yes, use page.locator('selector').screenshot() in Playwright or page.$('selector').then(el => el.screenshot()) in Puppeteer.

Does it work with local files that have external resources?

Yes, but you need to ensure the resources are accessible. Use absolute paths or a local server (e.g., npx http-server) to avoid CORS issues.

Is there a way to speed up the process?

Use a single browser instance and reuse pages for multiple screenshots. Also, avoid waiting for network idle if not necessary.

Can I use this in a CI/CD pipeline?

Yes, both libraries work in headless mode on Linux servers, but you may need to install additional system dependencies (e.g., npx playwright install-deps).