The Tool Desk
Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.
Control Playwright PDF margins with the four-sided margin option on page.pdf(), with CSS @page as the alternative when print layout belongs in your stylesheet. Use explicit units such as mm, cm, in, or px; choose one authoritative layer for page size; and set preferCSSPageSize when CSS must control the paper dimensions.
Set margins in page.pdf()
The API margin object has independent top, right, bottom, and left properties. Paper margins default to none, and an unlabeled number is interpreted as pixels, so physical units are safer for documents that must print consistently.
JavaScript
import { chromium } from 'playwright';
const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto('https://example.com', { waitUntil: 'networkidle' });
await page.pdf({
path: 'output.pdf',
format: 'A4',
margin: {
top: '20mm',
right: '15mm',
bottom: '20mm',
left: '15mm'
},
printBackground: true
});
await browser.close();
format selects A4 in this example. If you provide format, it takes priority over width and height. If none of those are supplied, the documented default format is Letter.
Free tools Windows power users keep installed
One-click scans. No signup required.
Python (async API)
from playwright.async_api import async_playwright
async def main():
async with async_playwright() as p:
browser = await p.chromium.launch()
page = await browser.new_page()
await page.goto("https://example.com", wait_until="networkidle")
await page.pdf(
path="output.pdf",
format="A4",
margin={
"top": "20mm",
"right": "15mm",
"bottom": "20mm",
"left": "15mm",
},
print_background=True,
)
await browser.close()
The Python option names use underscores where JavaScript uses camel case: prefer_css_page_size rather than preferCSSPageSize, for example.
#1 Best Overall
- CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
- INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
- THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
- WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
- A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents
Use CSS @page for print-owned layout
CSS can define both page size and margins, which is useful when the same print rules are used by browser printing and Playwright exports.
@page {
size: A4;
margin: 20mm 15mm 20mm 15mm;
}
@media print {
body {
margin: 0;
}
}
The four values follow the CSS order top, right, bottom, left. A single value applies to all sides; two values apply to top/bottom and right/left; three values apply to top, horizontal, and bottom margins. The body rule removes the document’s own layout margin so it does not look like an additional page margin.
Make CSS page size authoritative
When CSS declares the page size and that declaration must override format, width, or height, set preferCSSPageSize: true in JavaScript or prefer_css_page_size=True in Python.
await page.pdf({
path: 'css-sized.pdf',
preferCSSPageSize: true,
printBackground: true
});
await page.pdf(
path="css-sized.pdf",
prefer_css_page_size=True,
print_background=True,
)
The documented default is false. With the default, Playwright can scale content to fit the API-selected paper size instead of adopting the CSS size exactly. Do not leave this precedence implicit when precise dimensions matter.
Rank #2
- CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
- 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
- SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
- INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
- THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
Choose one margin authority
| Requirement | Recommended owner | Settings |
|---|---|---|
| Each export needs different margins | PDF API | Set the four-sided margin object in page.pdf(). |
| Print styling is shared across tools | CSS | Define @page and print media rules. |
| CSS must control paper dimensions | CSS with explicit precedence | Use @page { size: ... } and preferCSSPageSize: true. |
| Screen appearance should be printed | Media emulation plus either margin layer | Call emulateMedia({ media: 'screen' }) before pdf(). |
Defining a margin in both places can make ownership unclear. Keep one source authoritative, then inspect the resulting PDF at the intended paper size. If a component stylesheet contains an @page rule you did not write, it can affect the export even when your API margin looks correct.
Understand print media and page geometry
page.pdf() generates a PDF using print CSS media by default. That means @media print rules apply and screen-only rules may not. To deliberately export the screen design, switch media first:
await page.emulateMedia({ media: 'screen' });
await page.pdf({
path: 'screen-styles.pdf',
format: 'A4',
margin: { top: '12mm', right: '12mm', bottom: '12mm', left: '12mm' }
});
await page.emulate_media(media="screen")
await page.pdf(
path="screen-styles.pdf",
format="A4",
margin={"top": "12mm", "right": "12mm", "bottom": "12mm", "left": "12mm"},
)
Other PDF options can change how much content fits inside those margins. scale defaults to 1 and accepts values from 0.1 to 2; reducing it fits more content but also shrinks text. printBackground defaults to false, so set it to true when colored backgrounds are part of the intended layout.
Remove unwanted whitespace
Check for a second margin
Inspect the document’s body, root containers, headings, and print rules. A zero API margin does not remove a CSS body { margin: ... }, padding on a wrapper, or spacing created by a header component. Temporarily apply @media print { html, body { margin: 0; padding: 0; } } to isolate document spacing, then restore only the spacing you actually need.
Rank #3
- Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
- Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
- Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
- In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
- Ultra-thin bezels: Maximize your viewing experience with thin bezels.
Check page-size precedence
Unexpected whitespace can occur when a CSS @page rule interacts with an API-selected format while preferCSSPageSize remains false. If CSS is intended to own size, enable preferCSSPageSize: true, remove competing format/width/height settings, and compare the output again. If the API should own size, remove or simplify the CSS page-size declaration instead.
Check the effective media mode
A print rule may intentionally add padding, hide a panel, or change dimensions. Confirm whether the export is using print (the default) or screen media, and make the choice explicit in code.
Check scaling and headers
A scale other than 1 changes apparent whitespace because the page content is resized within the printable area. Headers and footers, if added by your export configuration, also consume space. Measure the rendered result at 100 percent before changing margins to compensate for a scaling or template issue.
Quick wins for a faster PC:
Scan for outdated or missing drivers - takes under a minuteDriver Scan →Repair Windows errors before they cause bigger problemsFix Now →Complete patterns for common jobs
Edge-to-edge content with no paper margin
await page.pdf({
path: 'edge-to-edge.pdf',
format: 'A4',
margin: { top: '0mm', right: '0mm', bottom: '0mm', left: '0mm' }
});
This removes the PDF API’s paper margin. It does not override padding, borders, or margins in your HTML and CSS, and a physical printer may still impose a non-printable hardware area.
Rank #4
- CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
- SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
- MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
- KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
- INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient
Custom paper dimensions
await page.pdf({
path: 'receipt.pdf',
width: '80mm',
height: '200mm',
margin: { top: '3mm', right: '3mm', bottom: '3mm', left: '3mm' }
});
Do not supply format with this pattern: when a format is present it takes priority over width and height.
Use a CSS print template
await page.goto('https://example.com/invoice', { waitUntil: 'networkidle' });
await page.pdf({
path: 'invoice.pdf',
preferCSSPageSize: true,
printBackground: true
});
Here the page’s @page rule owns the dimensions and margins. Keep the API free of competing paper-size settings.
Troubleshoot by symptom
| Symptom | Likely cause | Fix |
|---|---|---|
| All four margins are larger than requested | CSS body or wrapper spacing, or a competing @page rule |
Inspect print CSS, reset document margins temporarily, and choose one authority. |
| Only the top or bottom looks wrong | Asymmetric CSS value, header/footer space, or a page-break effect | Verify the four API sides and the four-value CSS order; inspect generated page breaks. |
| CSS paper size is ignored | preferCSSPageSize is false |
Set preferCSSPageSize: true (or Python’s snake-case equivalent). |
| Content is unexpectedly tiny | scale below 1 or fitting to a different format |
Use scale: 1, remove competing size settings, and verify the selected format. |
| Background colors disappear | printBackground defaults to false |
Set printBackground: true or print_background=True. |
| Screen layout is not exported | Print media is the default | Call emulateMedia({ media: 'screen' }) or Python’s emulate_media(media="screen"). |
| Different Playwright versions produce different whitespace | Page-size and @page precedence interaction |
Record the Playwright version, make precedence explicit, and test the exact HTML and CSS combination. |
Validate a margin change
- Capture a minimal page with a visible border around the main content.
- Set explicit physical units and one page-size authority.
- Generate the PDF at
scale: 1with the intended media mode. - Open the PDF in a viewer that reports physical dimensions and confirm the paper size.
- Compare each edge independently; a correct top margin does not prove the left, right, and bottom values are correct.
- Only then add complex components, backgrounds, page breaks, and production data.
Or skip the browser setup
If you need a rendered PDF or image rather than a locally managed Playwright pipeline, ScreenshotNeo exposes a single screenshot API and an MCP server for AI agents. Its PDF options include paper size, margins, landscape mode, and page ranges. 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 report the page verdict and billing status.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
For PDF output, add the documented PDF parameters to the same request. The full parameter list and examples are in the ScreenshotNeo documentation.
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)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
The service also supports full-page captures with lazy images loaded, CSS-selector element captures, custom CSS and JavaScript, clicks before capture, selector or network-idle waits, resource blocking, headers, cookies, user agents, authorization, timezone and geolocation, transparent backgrounds, resizing, chosen cache TTLs, 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 MCP tools are take_screenshot, get_page_info, and capture_pdf, so Claude, Cursor, or another MCP client can request captures directly.
Best Value
- 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
- 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
- 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.
The Free plan includes 1,000 shots per month without a card. Paid plans start at $5 for 3,000 shots; every feature is available on every plan. Create a free ScreenshotNeo account.
Frequently Asked Questions
Can I use pixels for Playwright PDF margins?
Yes. The API accepts px as well as mm, cm, and in; unlabeled numeric values are treated as pixels. Physical units are generally easier to reason about for printed documents.
Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Scan for outdated or missing drivers - takes under a minute3Clear out junk files and repair common Windows errorsDoes zero margin make a PDF printable to the edge?
It removes the PDF paper margin, but it cannot remove margins or padding in your HTML and cannot bypass a physical printer’s non-printable area.
Which setting wins when both format and width are supplied?
The format option takes priority over width and height. Remove the competing option when you need custom dimensions.
Why do two PDFs with identical margins have different pagination?
Pagination also depends on paper size, media mode, scale, fonts, content dimensions, and page-break rules. Compare those inputs before changing the margin values.
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.

