Set the browser’s media type to screen before creating the PDF. Headless Chrome’s PDF APIs use the print CSS media type by default, so print-only rules can hide elements, change layout, or remove backgrounds. In Puppeteer, call await page.emulateMediaType('screen'). In Playwright, call await page.emulateMedia({ media: 'screen' }). Then create the PDF and explicitly configure its page geometry, backgrounds, and color behavior.
Why a headless PDF differs from the browser
A live page normally renders under the screen media type. CSS can provide a separate print design with rules such as @media print, different widths, hidden navigation, altered typography, or simplified colors. Both Puppeteer’s and Playwright’s PDF methods generate output using the print media type unless you override it.
That means changing only options such as format, margin, or printBackground cannot make the browser select screen rules. Media emulation must happen before the PDF call. Screen emulation controls which CSS media queries apply; it does not promise identical pagination to a live viewport.
Puppeteer: generate a PDF with screen CSS
Minimal working example
import puppeteer from 'puppeteer';
const browser = await puppeteer.launch({ headless: true });
const page = await browser.newPage();
await page.goto('https://example.com', { waitUntil: 'networkidle0' });
await page.emulateMediaType('screen');
await page.pdf({
path: 'page.pdf',
format: 'A4',
printBackground: true
});
await browser.close();
The important ordering is goto, readiness checks, emulateMediaType('screen'), and then pdf. Calling the PDF method first produces print-media output; changing the media type afterward cannot alter an already-written file.
#1 Best Overall
- BEST FOR SMALL BUSINESSES – Engineered for extraordinary productivity, the Brother DCP-L2640DW Monochrome (Black & White) 3-in-1 combines laser printer, scanner, copier in one compact footprint and delivers high-quality black & white prints
- FAST PRINTER WITH EFFICIENT SCANNING – Produces documents quickly with print speeds up to 36 ppm(2) and scan speeds up to 23.6/7.9 ipm(3) (black/color). A 50-page auto document feeder(4) allows for convenient, time saving multi-page scanning and copying
- FLEXIBLE CONNECTION OPTIONS – Easily navigate the changing demands of your business with secure multi-device connectivity via built-in dual-band wireless (2.4GHz / 5GHz) and Ethernet. Or connect locally to a single computer via USB interface
- BROTHER MOBILE CONNECT APP – Print, scan, and manage your wireless printer anytime, from almost anywhere from your mobile device. Order Brother Genuine Supplies, track toner usage, and complete more work on-the-go(5)
- CHOOSE BROTHER GENUINE TONER – When it’s time to replace your toner, be sure to choose Brother Genuine TN830 or TN830XL replacement toner. And with Refresh EZ Print Subscription Service, you’ll never worry about running out of toner again and you’ll enjoy savings of up to 50%(6) on Brother Genuine Toner. Get started with Refresh today with a Free Trial(1)
Use explicit dimensions and margins
Screen CSS often depends on a viewport width, while a PDF uses a physical sheet. Set a viewport that represents the desktop or mobile design you intend to capture, then select paper geometry independently:
await page.setViewport({
width: 1440,
height: 1000,
deviceScaleFactor: 1
});
await page.emulateMediaType('screen');
await page.pdf({
path: 'screen-layout.pdf',
width: '1440px',
height: '2000px',
margin: { top: '24px', right: '24px', bottom: '24px', left: '24px' },
printBackground: true,
preferCSSPageSize: false
});
For a paged document, use a paper format such as A4 or Letter and inspect page breaks. A tall custom height may be useful for a single-page visual export, but it is not a substitute for pagination testing.
Playwright: the equivalent sequence
Minimal working example
import { chromium } from 'playwright';
const browser = await chromium.launch();
const page = await browser.newPage({
viewport: { width: 1440, height: 1000 }
});
await page.goto('https://example.com', { waitUntil: 'networkidle' });
await page.emulateMedia({ media: 'screen' });
await page.pdf({
path: 'page.pdf',
format: 'A4',
printBackground: true
});
await browser.close();
Playwright uses page.emulateMedia({ media: 'screen' }); Puppeteer uses page.emulateMediaType('screen'). Do not substitute one API call for the other.
When to use a persistent context
If the page requires an authenticated session, launch a persistent context or create a context with stored state, then perform the same media-emulation step immediately before PDF generation. Keep credentials out of source code and avoid writing session cookies into logs.
Preserve screen colors and backgrounds
PDF generation applies print-oriented color adjustment by default. A dark panel, gradient, or brand color can therefore look lighter or otherwise different even after selecting screen media. Add this rule to the page stylesheet when exact screen colors are required:
Rank #2
- BEST FOR HOMES & HOME OFFICES – Engineered for consistent, premium print quality, the Brother HL-L2405W Monochrome (Black & White) Laser Printer delivers sharp, crisp prints at an affordable price. Prints one-sided documents at speeds up to 30ppm(2)
- COMPACT, CONNECTED PRINTER – Flexible connection options make this an ideal printer for home use and at-home offices. Securely connect to multiple devices with built-in dual-band wireless (2.4GHz/5GHz) or locally to a single computer via USB interface
- BROTHER MOBILE CONNECT APP – Manage your printer remotely and print from your mobile device anytime, from almost anywhere. Order Brother Genuine Supplies, track toner usage, and complete more work on-the-go(3)
- VERSATILE PAPER HANDLING – Enjoy seamless, reliable everyday printing with the 250-sheet paper tray(4) and a manual feed slot that enables printing on envelopes and specialty pape
- BROTHER IS AT YOUR SIDE – Backed by Brother with a 1-year limited warranty and free online, call, or live chat support for the life of your printer
html {
-webkit-print-color-adjust: exact;
print-color-adjust: exact;
}
Also set printBackground: true in Puppeteer or Playwright. The CSS property asks the renderer not to alter colors for printing; the PDF option permits background painting. You generally need both.
Color fidelity still depends on the assets and browser version. Web fonts that have not loaded, images decoded late, transparency, and color profiles can all affect the result. Treat “screen media” as a CSS-selection fix, not a universal pixel-identity guarantee.
Make the page ready before capture
Wait for navigation and application state
networkidle or networkidle0 is useful for pages that finish loading network requests, but it is not proof that a single-page application has rendered its final state. Wait for a selector that proves the content exists:
Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Fix the driver behind crashes, sound loss and screen glitches3Clear out junk files and repair common Windows errorsawait page.goto(url, { waitUntil: 'domcontentloaded' });
await page.waitForSelector('[data-report-ready]', { timeout: 30000 });
await page.evaluate(() => document.fonts.ready);
await page.emulateMediaType('screen');
await page.pdf({ path: 'report.pdf', printBackground: true });
For Playwright, replace the media call with await page.emulateMedia({ media: 'screen' }). If images are injected lazily, scroll through the document or wait for a page-specific completion signal before creating the PDF.
Control animations and transient UI
Animations can capture halfway through a transition. Disable them with a temporary stylesheet when deterministic output matters:
Rank #3
- FAST PRINT SPEEDS: Print up to 19 pages per minute.
- COMPACT DESIGN: Space-saving, compact design fits anywhere in your home, school or small office.
- WIRELESS CONNECTIVITY: Print from almost anywhere in your workspace using your compatible mobile device.
- PAPER CAPACITY: Up to 150 sheets.
- SUSTAINABILITY: Uses less than 2 watts in Energy Saver mode.
await page.addStyleTag({ content: `
*, *::before, *::after {
animation: none !important;
transition: none !important;
caret-color: transparent !important;
}
` });
Do this only if removing motion is acceptable for the document. Alternatively, wait for a known animation to finish.
Screen media does not remove pagination problems
A screen layout is usually continuous; a PDF is paged. Large cards, sticky headers, tables, and CSS transforms can cross page boundaries. After selecting screen media:
Free tools Windows power users keep installed
One-click scans. No signup required.
- Choose paper size, orientation, and margins explicitly.
- Inspect headings, tables, images, and repeated headers at page boundaries.
- Use CSS break rules such as
break-inside: avoidfor units that should stay together, while accepting that very tall elements still must split. - Check responsive breakpoints against the chosen viewport width.
- Verify overflow from fixed or absolutely positioned elements.
For a print-oriented report, a dedicated paged layout can be more reliable than forcing a screen design onto paper. Use screen emulation when preserving the on-screen appearance is the requirement, then validate the resulting pages rather than assuming the browser view and PDF have identical geometry.
Choosing Puppeteer or Playwright
| Question | Puppeteer | Playwright |
|---|---|---|
| Screen-media API | page.emulateMediaType('screen') |
page.emulateMedia({ media: 'screen' }) |
| PDF call | page.pdf(options) |
page.pdf(options) |
| What changes | The CSS media type used while rendering; print paper geometry still requires PDF options. | |
| Best choice | Use the library already supported by your project and its installed browser version; the media principle is the same. | |
Compare your existing dependency, browser version policy, authentication helpers, and validation tooling rather than expecting one library to guarantee closer visual parity. Neither documented API publishes a universal pixel-difference percentage for screen-versus-PDF output.
Common failures and fixes
“My PDF still uses the print layout”
Check that the media call runs on the same page immediately before pdf(), and that no later code changes it back to print. Confirm that your CSS actually contains the expected screen rules; ordinary styles outside media queries apply in both modes.
“Backgrounds or colors are missing”
Set printBackground: true and add -webkit-print-color-adjust: exact; print-color-adjust: exact;. Ensure the background is not being removed by an explicit @media print rule or by a transparent overlay.
Rank #4
- BEST FOR HOME OFFICES & SMALL TEAMS – Engineered for consistent, premium print quality, the Brother HL-L2460DW Monochrome (Black & White) Laser Printer produces documents that are clear, crisp, and easy to review and share, all at an affordable price
- COMPACT, CONNECTED, EXCEPTIONALLY EFFICIENT– Connect with built-in dual-band wireless (2.4GHz/5GHz), Ethernet, or to a single computer via USB interface. Prints at speeds up to 36ppm(2), plus automatic duplex printing saves time and reduces paper waste
- BROTHER MOBILE CONNECT APP – Manage your wireless printer remotely and print from your mobile device anytime, from almost anywhere. Order Brother Genuine Supplies, track toner usage, and complete more work on-the-go(3)
- VERSATILE PAPER HANDLING – Tackle high-volume black & white printing with the 250-sheet capacity paper tray.(4) The manual feed slot enables printing on envelopes and specialty paper
- BROTHER IS AT YOUR SIDE – Backed by Brother with a 1-year limited warranty and free online, call, or live chat support for the life of your printer
“Fonts are wrong or text wraps differently”
Wait for document.fonts.ready, verify that font requests succeed, and use a consistent viewport and browser build. A fallback font changes glyph widths and therefore line breaks and page count.
“The page is blank or incomplete”
Wait for an application-specific ready selector, not only navigation. Increase the selector timeout when appropriate, inspect console and request failures, and confirm that the target route is accessible to the headless session.
“The PDF has clipped or overlapping content”
Look for fixed heights, transforms, sticky elements, and viewport-dependent breakpoints. Test with the intended paper size and margins, remove accidental horizontal overflow, and review each page at the boundaries of large components.
“Network idle never occurs”
Analytics, WebSockets, and long polls can keep a page active indefinitely. Use domcontentloaded plus a meaningful selector, or set a bounded wait strategy instead of waiting forever for network quiescence.
Or skip the browser setup
ScreenshotNeo provides a website screenshot API and MCP server when you need a rendered page or PDF without maintaining a browser worker. Its PDF endpoint accepts screen-oriented capture options, and its cleanup steps remove cookie or consent banners, newsletter popups, and chat widgets before the shot. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and each response identifies the page verdict and billing status.
For a direct PDF request, start with the documented API options at https://screenshotneo.com/docs/. A one-call image example is:
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
The same request in Python:
import requests
r = requests.get(
"https://api.screenshotneo.com/v1/shot",
params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
timeout=90,
)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)
And in 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}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const buffer = Buffer.from(await res.arrayBuffer());
await import('node:fs/promises').then(fs => fs.writeFile('shot.webp', buffer));
ScreenshotNeo also offers an MCP server with take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. It includes 1,000 screenshots per month free with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.
Best Value
- FROM AMERICA'S MOST TRUSTED PRINTER BRAND – Perfect for small teams printing professional-quality black & white documents and reports. Perfect for 1-3 people
- WORLD'S SMALLEST LASER IN ITS CLASS – Precision laser printing that fits anywhere
- FAST PRINT SPEEDS – Up to 21 black-and-white pages per minute single-sided
- WIRELESS WITH SELF-RESET – Helps you stay connected
- PRINT FROM ANY DEVICE – Wireless printing from any mobile device, PC or tablet. Works with Microsoft, Mac, AirPrint, Android, Chromebook and more
Operational and cost considerations
Reliability
Pin compatible browser versions in CI, use bounded navigation and selector timeouts, and save failed HTML, console output, and screenshots for diagnosis. Deterministic fonts, disabled animations, and a fixed viewport reduce run-to-run differences. Recheck representative documents after browser upgrades.
Recommended Free Tools
Performance
Reuse a browser process when generating multiple PDFs, but isolate pages or contexts when cookies and authentication must not leak. Avoid unnecessarily large viewports and wait only for the readiness condition your application can actually satisfy. Loading every image at full resolution increases memory and render time.
Cost
Self-hosted Puppeteer or Playwright costs compute time, browser maintenance, and engineering effort. A hosted endpoint trades that operational work for request pricing and service limits. ScreenshotNeo’s free allowance is 1,000 screenshots per month without a card; its paid tiers begin at $5 for 3,000, with yearly billing providing two months free. Failed loads and other non-clean outcomes described above are not billed.
Validation checklist
- Open the page at the target viewport and record the intended screen appearance.
- Wait for content, fonts, and lazy images to be ready.
- Set screen media with the API appropriate to your library.
- Enable backgrounds and exact color adjustment when required.
- Set paper size, orientation, margins, and any CSS page-size policy.
- Generate the PDF and inspect every page boundary.
- Repeat with representative responsive breakpoints and authenticated states.
- Pin or document browser versions so future changes are explainable.
Frequently Asked Questions
Does screen-media emulation make a PDF identical to a browser screenshot?
No. It selects screen CSS rules, while paper size, pagination, font loading, device scale, and browser rendering still affect the PDF.
Can I call emulateMedia after page.pdf()?
No. The media type must be set before PDF generation; a later call cannot change the file already produced.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Do I need both printBackground and print-color-adjust?
Use both when backgrounds and exact colors matter: the PDF option enables background painting, while the CSS property prevents print-oriented color adjustment.
Which library should a new project choose?
Choose the stack that matches your existing browser dependencies and validation needs. Puppeteer and Playwright expose different media-emulation calls but the same ordering requirement.
Quick Recap
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.




