ScreenshotNeo

BlogAI agents

How to Use an AI Agent to Screenshot a Webpage with a Print Stylesheet

Use Playwright to apply print CSS before capturing a webpage as an image, or generate a paginated PDF when you need print output.

By the ScreenshotNeo team4 October 20268 min read

To screenshot a webpage with its print stylesheet, have an AI agent open the page in a browser automation runtime, wait for the content you need, switch the page to print media, and capture it with Playwright’s page.screenshot(). Use fullPage: true for content below the viewport. If you need a paginated document rather than one tall image, use page.pdf().

The key distinction is that page.screenshot() captures the browser’s rendered page as an image, while page.pdf() creates a paginated PDF. Playwright uses print CSS media by default for PDFs; screenshots need an explicit media emulation step to activate print rules.

1. Understand what print media changes

A page can define print-specific styles with @media print or load a stylesheet using media="print". Those rules may hide navigation and controls, change typography or colors, and rearrange the reading column. Applying print media asks the browser to render those rules before the screenshot is taken.

Print styles can also affect a linked print stylesheet and page rules. For printed page dimensions, orientation, or margins, CSS can use @page, though support for some paged-media details varies by browser. A screenshot is still a raster image: it does not add paper-sized pages or pagination. Inspect the result for clipping, missing content, and unexpected layout changes.

2. Capture a print-styled screenshot with Playwright

The following Node.js example uses Playwright’s documented Page API. Set TARGET_URL to the page to capture. It waits for the page’s load event, then gives the browser a short rendering interval before switching to print media. For production pages, replace the generic wait with a page-specific readiness condition when possible.

import { chromium } from 'playwright';

const url = process.env.TARGET_URL;
if (!url) throw new Error('Set TARGET_URL to the page URL');

const browser = await chromium.launch({ headless: true });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });

try {
  await page.goto(url, { waitUntil: 'load', timeout: 60_000 });
  // Prefer a page-specific condition, such as a main article selector,
  // when the site renders important content after the load event.
  await page.locator('body').waitFor({ state: 'visible' });
  await page.waitForTimeout(500);

  await page.emulateMedia({ media: 'print' });
  await page.screenshot({ path: 'page-print.png', fullPage: true });
} finally {
  await browser.close();
}

Run it with Playwright installed in a Node.js project and a target URL set in the environment:

npm install playwright
npx playwright install chromium
TARGET_URL="https://example.com/article" node capture-print.mjs

This example captures a full-page PNG. Use a URL you are authorized to access. A fixed delay is only a practical fallback; it does not prove that every image, client-rendered widget, or delayed request has finished.

Wait for the content that matters

When the page has a reliable content selector, wait for that selector instead of relying on a generic delay:

await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 60_000 });
await page.locator('main article').waitFor({ state: 'visible', timeout: 20_000 });
await page.emulateMedia({ media: 'print' });
await page.screenshot({ path: 'article-print.png', fullPage: true });

Choose a selector that represents the content you need, not an element that appears before the page has populated it. If the site loads images lazily as the page scrolls, inspect whether the full-page capture includes them; a full-page screenshot does not guarantee every site-specific lazy-loading behavior has completed.

Capture the viewport or one element

Use the default screenshot extent for the current viewport. To capture a particular element, locate it and take the screenshot from that locator:

await page.emulateMedia({ media: 'print' });
await page.locator('main article').screenshot({ path: 'article-print.png' });

Use an element capture when you need a chart, article, or other specific region. Check for content that overflows the element or is hidden by the print stylesheet. Use fullPage: true when the complete scrollable document should appear in one image; very long pages can produce very tall, unwieldy files.

3. Choose screenshot or PDF

Need Playwright operation What to expect
Visual image of the rendered print layout page.screenshot() Raster image of the viewport, selected element, or full page; emulate print media first.
Paginated print document page.pdf() PDF output with print CSS media applied by default; inspect page breaks and paper layout.
PDF using screen styles Emulate screen media, then call page.pdf() Uses screen media styling for the PDF generation request.

To create a PDF with print styling, Playwright’s PDF operation already uses print CSS media by default:

await page.goto(url, { waitUntil: 'load' });
await page.pdf({ path: 'page-print.pdf', format: 'A4', printBackground: true });

To create a PDF with screen styles instead, emulate screen media before generating it:

await page.emulateMedia({ media: 'screen' });
await page.pdf({ path: 'page-screen-styles.pdf', format: 'A4', printBackground: true });

For a screenshot, explicitly choose the media mode you want. Restore screen media after a print screenshot if later steps in the same workflow expect the screen layout:

await page.emulateMedia({ media: 'print' });
await page.screenshot({ path: 'page-print.png', fullPage: true });
await page.emulateMedia({ media: 'screen' });

4. Set page print styles when you control the website

If you own the page, put print-specific rules in its stylesheet or link a dedicated print stylesheet. Keep the reading area legible, remove nonessential controls, and check that important links and images remain useful in the output. CSS specificity and the cascade still apply, so a print rule may need enough specificity to override the site’s existing styles.

@media print {
  nav,
  .cookie-banner,
  .share-controls {
    display: none !important;
  }

  main {
    max-width: 42rem;
    margin: 0 auto;
  }

  article {
    color: #111;
    background: #fff;
  }
}

@page {
  size: A4 portrait;
  margin: 18mm;
}

The example selectors are illustrative: replace them with selectors from your site. Hiding elements and changing colors are design choices, not guarantees of the screenshot API. If paper dimensions, orientation, or margins matter, verify the PDF in the browser you use for generation because paged-media support can vary.

5. Give an AI agent a reliable capture task

An AI agent can use a browser tool or call a script like the one above. Make the task explicit so it selects the right rendering mode and output:

  1. Open the supplied URL in the browser runtime.
  2. Wait for a named content selector or another page-specific readiness condition.
  3. Emulate print media before taking an image screenshot.
  4. Choose viewport, element, or full-page extent and the desired image path and format.
  5. Inspect the saved image for missing content, overflow, unwanted navigation, ads, and print-layout changes.
  6. If the requirement is page breaks or paper-sized pages, produce and inspect a PDF instead.
  7. If the workflow continues in the same page, set its media state explicitly for the next operation.

For an agent instruction, specify the target URL, the content selector or readiness signal, whether the output should be an image or PDF, whether to capture the viewport or full page, and where to save the result. This avoids leaving the agent to guess whether “screenshot” means a single viewport, a long image, or a paginated document.

6. Format, scale, and capture extent

  • Extent: capture the viewport for a screen-sized view, a locator for one region, or the full page for below-the-fold content.
  • Format: Playwright screenshot tooling supports PNG, JPEG, and WebP. Use PNG when preserving crisp text and interface edges matters; use JPEG or WebP when a smaller image is more useful and their compression is acceptable.
  • Scale: choose CSS-pixel scale for dimensions aligned with the CSS layout, or device-pixel scale for higher-resolution output. Higher-resolution output increases image dimensions and file size.
  • Media: use print to activate print rules or screen to render the on-screen layout.
  • PDF: use PDF output when page size, margins, orientation, and pagination matter. A tall screenshot does not represent page breaks.

7. Troubleshooting

Symptom Likely cause Fix
Screenshot looks like the normal website Print media was not emulated before the screenshot, or the site has no print-specific rules. Call page.emulateMedia({ media: 'print' }) before capture. Check the site’s stylesheet for @media print or a print-linked stylesheet.
Print CSS works in PDF but not in screenshot PDF generation applies print media by default; screenshot capture does not automatically switch media. Emulate print media explicitly before calling page.screenshot().
Article content is missing The page may render content after the load event, or the readiness selector may be too early or incorrect. Wait for a page-specific content selector and verify that it contains the expected content before capture.
Images are blank or incomplete Images may be lazy-loaded, delayed, or affected by print-specific styles. Inspect the page after scrolling or wait for the relevant images to load; check their computed visibility under print media.
Full-page image is too tall The page has a long scrollable document. Capture a target element or viewport, or create a PDF if the output needs pages.
Content is clipped or rearranged unexpectedly Print rules change widths, visibility, positioning, or page layout. Inspect the captured output, adjust site-owned print CSS, or capture the intended element. Use PDF when pagination is the requirement.
PDF has unexpected margins or page breaks Page CSS, browser behavior, or paged-media support differs from expectations. Check the page’s @page rules and PDF options, then inspect the generated PDF in the target browser workflow.

8. Performance, reliability, and cost

Capture time depends on navigation, page rendering, and the readiness condition. Waiting for the right content is more reliable than adding a long arbitrary delay, but a site-specific selector can itself fail if the site changes. Keep a timeout, handle navigation and selector failures, and save or report errors so an agent does not silently treat a failed capture as success.

Full-page images can consume more memory and disk space than viewport or element captures, especially at high resolution. Use the smallest extent and scale that meet the downstream need. PDFs are usually the better fit when the page must be reviewed or printed as individual pages. Browser automation has no fixed per-capture cost stated here; account for the compute and storage of the runtime you choose.

Or skip the browser setup

ScreenshotNeo provides a website screenshot API and MCP server for developers. A GET request with a URL returns a PNG, JPEG, WebP, or PDF. For the request and available options, see the ScreenshotNeo API documentation.

curl -G "https://api.screenshotneo.com/v1/shot" \
  -d access_key=YOUR_API_KEY \
  --data-urlencode url=https://example.com/article \
  -o shot.webp
import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://example.com/article"},
    timeout=90,
)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({
  access_key: 'YOUR_API_KEY',
  url: 'https://example.com/article',
});
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot request failed: ${res.status}`);
await Bun.write('shot.webp', res);

ScreenshotNeo removes cookie banners, newsletter popups, and chat widgets before the shot; bot checks, blank pages, and failed loads are never billed. Its MCP server lets AI agents take screenshots. The free plan includes 1,000 screenshots a month with no card, and paid plans start at $5 for 3,000. The API offers capture options including full-page capture, CSS selectors, output format, and PDF settings; see the docs for parameter names and configuration.

Sign up for ScreenshotNeo’s free plan and get 1,000 screenshots a month with no card.

FAQ

Does a print stylesheet make a screenshot paginated?

No. A screenshot is an image of the rendered page. Use PDF generation when you need separate pages and print pagination.

Can I capture the screen layout as a PDF?

Yes. Set screen media before calling Playwright’s PDF operation.

Can the agent take a screenshot without changing the website’s CSS?

Yes. Media emulation changes the browser’s rendering mode; it does not require editing the site. The page must already provide print rules for the layout to change.

What should I inspect after capture?

Check that the expected content and images appear, the print layout has not clipped important material, and the chosen extent matches the intended output.