October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk7 min

Generate Social Media Preview Images from HTML with Playwright

A repeatable Playwright workflow for rendering a dedicated HTML social card, saving its image, publishing it, and pointing Open Graph metadata to it.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Playwright to render a dedicated HTML social card at a fixed viewport, save the card as an image, publish it at a stable public URL, and reference that URL in your page’s Open Graph metadata. Playwright creates the image; the metadata tells crawlers which image and page information to use.

Build a dedicated social-card page

A share card is a compact composition, not a screenshot of your whole article. Give it a fixed canvas and a dedicated element to capture. That keeps navigation, unrelated page content, and variable page length out of the image.

As an Amazon Associate I earn from qualifying purchases.

The example below uses a 1200 × 627 CSS-pixel card. LinkedIn’s official sharing help page gives 1200 × 627 pixels as a minimum for its sharing module; that is a LinkedIn-specific requirement, not a universal size for every platform. Check the current requirements of each destination where the image will appear.

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.

Save this as social-card.html. Its text and styling are deliberately self-contained, so the result does not depend on a remote font or image finishing its load.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Social card</title>
  <style>
    * { box-sizing: border-box; }
    html, body { margin: 0; width: 1200px; height: 627px; }
    body {
      font-family: Arial, Helvetica, sans-serif;
      background: #10223b;
      color: #fff;
    }
    [data-social-card] {
      width: 1200px;
      height: 627px;
      padding: 72px;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      background: linear-gradient(135deg, #10223b, #245d77);
    }
    .eyebrow { font-size: 22px; letter-spacing: .12em; text-transform: uppercase; }
    h1 { max-width: 1000px; margin: 32px 0; font-size: 64px; line-height: 1.08; }
    .site { font-size: 24px; color: #c8e9f2; }
  </style>
</head>
<body>
  <main data-social-card>
    <div>
      <div class="eyebrow">A practical guide</div>
      <h1>Generate social preview images with Playwright</h1>
    </div>
    <div class="site">example.com</div>
  </main>
</body>
</html>

Install Playwright and capture the card

In a Node.js project, install Playwright and its Chromium browser. The browser installation is a separate step from installing the package.

npm install playwright
npx playwright install chromium

Save the following script as capture-card.js beside social-card.html. It opens that local file, waits for the card to appear, captures only the card element, and writes a PNG to public/social/example.png.

const { chromium } = require('playwright');
const { resolve } = require('node:path');
const { pathToFileURL } = require('node:url');
const { mkdir } = require('node:fs/promises');

(async () => {
  const browser = await chromium.launch();
  try {
    const page = await browser.newPage({
      viewport: { width: 1200, height: 627 },
      deviceScaleFactor: 1,
    });
    const htmlPath = resolve(__dirname, 'social-card.html');
    await page.goto(pathToFileURL(htmlPath).href, { waitUntil: 'load' });
    const card = page.locator('[data-social-card]');
    await card.waitFor({ state: 'visible' });
    await page.evaluate(() => document.fonts.ready);

    const output = resolve(__dirname, 'public/social/example.png');
    await mkdir(resolve(__dirname, 'public/social'), { recursive: true });
    await card.screenshot({
      path: output,
      type: 'png',
      animations: 'disabled',
      scale: 'css',
    });
    console.log(`Saved ${output}`);
  } finally {
    await browser.close();
  }
})().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});

Run it with node capture-card.js. For an app route rather than a local file, replace the page.goto(...) call with your card URL, for example http://localhost:3000/social-card/example. Start the app first, and keep the fixed viewport and element selector so the capture remains focused on the card.

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

The example uses Playwright’s locator screenshot method and options documented in its screenshot API. Check the API documentation for the version installed in your project if you change options.

Choose the right capture target and output

Choice Use it when Practical effect
Element screenshot The card is a distinct DOM element, as in the example. Captures the element rather than the surrounding page.
Viewport screenshot The card itself fills the page viewport and its bounds are controlled. Captures the visible viewport; the viewport dimensions define the composition.
Clip rectangle The composition is already positioned precisely and you need an exact rectangle. Captures a specified region of the page.
Full-page screenshot You need a tall page image, not a compact share card. Captures the full page and is usually the wrong artifact for a social preview.

Playwright’s page.screenshot() returns image bytes; supplying path saves the image directly. Screenshot controls include capture type, clipping, full-page mode, scale, masking, style overrides, and animation handling. For a fixed card, an element capture is usually easiest to reason about.

Pixel scale

scale: 'css' produces one screenshot pixel per CSS pixel. scale: 'device' uses device-pixel resolution, which can increase image dimensions and file size. Keep the chosen scale consistent with the dimensions you declare in metadata.

Image format and quality

PNG is Playwright’s default and is useful when you need lossless output or transparency. JPEG and WebP are also available. The quality option applies to JPEG and WebP, not PNG. Choose a format the destination supports and weigh compression against image detail; platform format support should be checked for the specific destination rather than assumed.

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

Make captures repeatable

A fixed viewport is only one part of a stable result. A page can still change while it loads: fonts, external images, application data, animations, and rotating content can alter layout or pixels. The screenshot call does not prove that those dependencies are ready.

  • Wait for the actual card element and any application data it needs, not just the initial document response.
  • Wait for fonts that affect line wrapping. The example waits for document.fonts.ready; if a font is remote, make sure it has loaded successfully before capture.
  • If the card contains images, wait for those images to finish loading and verify that they are not broken before taking the screenshot.
  • Use deterministic card content. Avoid random values, clocks, rotating banners, or content that changes between runs unless the variation is intentional.
  • Disable animations with animations: 'disabled' or use a screenshot stylesheet to suppress motion and hide elements that should not appear in the image.
  • Choose a readiness condition that fits your page. networkidle can be useful for some routes, but analytics, polling, or persistent requests can prevent the network from becoming idle; waiting for a card-specific condition is often more targeted.

Playwright provides controls for animations and screenshot styling, but no single wait condition guarantees every external font, image, or asynchronous data source is ready. Add explicit checks for dependencies your card actually uses.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Publish the image and add Open Graph metadata

Deploy the generated image at a stable, publicly reachable URL, then set that URL in the shared page’s document head. A local path such as public/social/example.png is a file on your server; the metadata needs the public URL that resolves to that file after deployment.

<meta property="og:title" content="Example page title" />
<meta property="og:type" content="website" />
<meta property="og:url" content="https://example.com/example" />
<meta property="og:image" content="https://example.com/social/example.png" />
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="627" />
<meta property="og:image:alt" content="A short description of the preview image" />

The Open Graph Protocol identifies og:title, og:type, og:image, and og:url as the four required properties for a page. Its protocol specification describes og:image:width, og:image:height, og:image:type, og:image:secure_url, and og:image:alt as structured image properties. The alternative text should describe the image, not serve as its caption; include it when you specify an image.

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

Use the page’s canonical shared URL for og:url, and ensure the image URL is reachable by the crawler that needs it. The dimensions above describe the example image and match LinkedIn’s stated minimum shape; they do not establish a universal requirement. If a property has multiple values, Open Graph prefers the first tag in document order when there is a conflict. Put the intended og:image first, followed by that image’s structured properties.

Troubleshoot common capture and preview problems

Symptom Likely cause Fix
Locator screenshot times out The selector is wrong, the card never renders, or the app route was not started. Confirm the selector exists in the rendered DOM, start the local server if using a route, and wait for the page state that actually reveals the card.
Text wraps differently between runs A font is missing or not loaded, viewport dimensions differ, or content changes. Wait for fonts and required data, use the same viewport and scale, and make card content deterministic.
Images are blank in the output The capture ran before image loading completed, or an image URL failed. Wait for the card’s images to load and check their load status and URLs before capture.
Image dimensions differ from expectation Device scale was used, or the captured element does not have the expected CSS size. Check the element’s rendered bounds and use scale: 'css' when one output pixel per CSS pixel is intended.
Share preview shows the wrong or no image The metadata points to the wrong URL, the image is not publicly reachable, or the crawler has not picked up the updated page. Inspect the deployed page’s head and image URL. Crawler refresh and cache behavior differ by platform; consult that platform’s current tools and documentation.
Output includes a transition or transient overlay Animation or dynamic UI was still active at capture time. Disable animations, apply a screenshot stylesheet, or remove the transient UI from the dedicated card route.

Or skip the browser setup

If your card is already available as a URL, ScreenshotNeo can return a screenshot from one GET request. It also supports HTML/CSS-to-image capture. See the ScreenshotNeo API documentation for request options.

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

ScreenshotNeo accepts cookie or consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each of those steps can be turned off. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and responses indicate the page verdict and billing status in headers. An MCP server provides take_screenshot, get_page_info, and capture_pdf tools for AI agents and MCP clients. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000 screenshots. Sign up for ScreenshotNeo’s free plan.

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.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

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

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.