browser-printing
Skill2 starsChanged 4 months agoMITView on GitHub
Best practices for printing web pages, sections, or components from the browser: choosing a print strategy, writing print CSS, pagination control, page numbers, headless PDF generation, and diagnosing print-specific failures. Use this skill whenever the user mentions printing, print styles, @media print, window.print(), "save as PDF", print preview problems, page breaks, invoices/reports/labels/tickets that will be printed, or PDF generation via Playwright/Puppeteer — even if they only say something like "make this printable," "the printout looks wrong," or "add a print button." Print bugs rarely announce themselves as print bugs; if paper or PDF output is involved at all, consult this skill.
In this repository3 other files it gives its agents.
- SKILL.mdSkill
- skill-templateSkill
- typesettingSkill
The file
Show its rules and text
We split this skill into the rules it gives an agent
14 rules. About 0 are common, 10 are distinctive, and 4 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈10
Distinctive · estimate
This author's own choices. Worth a look.
4
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 30
If the audience spans both, design for the shared safe area (210mm width, 279mm height).
- Distinctive: line 35
Ask only what changes the implementation, batch the questions in one message, and cap at 2–3.
- Distinctive: line 51
Output constraints: must text remain selectable/searchable in the PDF?
- Distinctive: line 58
Do not ask about paper size, margins, or orientation unless inference fails — propose defaults instead.
- Distinctive: line 126
Prefer borders and text color over backgrounds where possible — cheaper in ink and immune to the "backgrounds off" dialog setting.
- Very specific: line 129
Dark themes: never print a dark UI as-is.
- Very specific: line 151
Never hand a user a counter(pages) solution for in-browser printing.
- Very specific: line 164
If the user asks for page numbers on a plain window.print() flow, explain the constraint and steer to option 1 or 2 rather than …
- Distinctive: line 204
Commercial Printing: If the document is for a commercial press (requires true CMYK, spot colors, or true black text), browser-based …
- Distinctive: line 208
When a user explicitly needs a CMYK PDF, the solution is a two-step process:
- Distinctive: line 209
Use Playwright/Puppeteer to generate an RGB PDF.
- Very specific: line 270
Ink/toner: default to white backgrounds, dark text, borders over fills.
- Distinctive: line 326
Check: total page count sane, no clipped right/bottom edges, no blank pages, headings not orphaned at page bottoms, table headers …
- Distinctive: line 328
If the page has dynamic data, test the extremes: empty state, one row, and a dataset long enough to cross at least three pages.
≈ “Common” is an estimate: at least 1 in 5 of the 213,895 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Browser Printing
Print is a paginated, physical-unit medium; the browser is a continuous, pixel-unit one. Nearly every print bug comes from applying screen-layout instincts to a paged context. Work in this order: clarify intent → choose a strategy → apply print CSS fundamentals → check the failure-mode list → iterate under media emulation → verify with a real paginated render.
1. Clarifying questions — and the discipline of asking them
Infer before you ask. Most answers are already in context:
- User locale or audience → paper size (US/Canada → Letter, nearly everywhere else → A4). If the audience spans both, design for the shared safe area (210mm width, 279mm height).
- Framework in the codebase → viable strategies (React → portal/print-route; server app → dedicated print view).
- Artifact type → fidelity bar (invoice/label/legal form → exact placement; article/report → clean and readable).
- Existing infra (Playwright/Puppeteer in CI) → headless generation is cheap to adopt.
Ask only what changes the implementation, batch the questions in one message, and cap at 2–3. For anything else, state the default you are assuming so the user can veto it: "I'll target A4 and Letter with 15mm margins, backgrounds on — say the word if you need something else."
The questions that most often change the implementation:
- What exactly prints? The whole page, one section/component, or a document that doesn't exist on screen yet (invoice, report)? This decides the strategy (§2).
- Who triggers it, and where does it run? A button calling
window.print(), the user pressing Ctrl+P on any page, or server-side/CI generation with no browser UI? - Fidelity bar: pixel-exact placement (forms, labels, anything overlaying preprinted stock) or "clean and readable"? Exact placement pushes toward headless generation or a purpose-built print route.
- Multi-page needs: repeating table headers, page numbers, "Page X of Y", running headers, a cover page? Page numbers in particular constrain the approach (§4).
- Output constraints: must text remain selectable/searchable in the PDF? Are there brand-color backgrounds that must survive? Any sensitive on-screen data that must NOT appear in the printout?
- Color Fidelity / CMYK: Will this be printed on an office printer, or sent to a commercial press? (Office printers handle RGB fine; commercial presses require CMYK, which browsers cannot output natively — this requires post-processing, see §6).
Do not ask about paper size, margins, or orientation unless inference fails — propose defaults instead.
2. Choose a strategy before writing CSS
Decision guide:
- Whole page needs cleanup for Ctrl+P →
@media printoverrides on the live page. Fine for content sites. Hide chrome (nav, footers, ads, chat widgets, cookie banners), linearize the layout, done. - One component from a complex app → do NOT fight the app's layout with hide-everything
CSS. Clone the component's markup into a dedicated, minimally-styled print container
(or a React portal / hidden print root) that becomes the only visible element in print
media. The popular
body * { visibility: hidden }trick breaks whenever an ancestor hastransform,position, oroverflow— treat it as a last resort for trivial pages. - Recurring document (invoice, report, ticket) → dedicated print route
(
/invoices/123/print): its own template, its own CSS, no app shell. Most maintainable option; usually the right answer, and it doubles as the input for headless generation. - Deterministic output, server-side, CI, or exact fidelity → headless Chromium
(
page.pdf()in Playwright/Puppeteer) rendering the print route. See §5. - Print an iframe's content → call
iframe.contentWindow.print(). Same-origin only; a cross-origin iframe cannot be restyled or printed as part of the parent — offer a print action inside the frame's own document or reproduce the data outside it.
Escalate rather than patch: if a hide-and-reveal approach needs its third exception, move to a clone or a print route.
3. Print CSS fundamentals
Page setup. Declare intent even though users can override it in the dialog:
@page { size: A4 portrait; margin: 15mm; }Physical units only for print-specific dimensions: mm, cm, in, pt.
Viewport units are meaningless on paper — height: 100vh is a blank-page generator,
and min-height: 100vh on a wrapper adds a trailing blank page.
Pagination control:
h2, h3 { break-after: avoid; } /* no orphaned headings */
figure, table tr, .card { break-inside: avoid; }
.chapter { break-before: page; }
p { orphans: 3; widows: 3; }Emit the legacy page-break-* aliases alongside break-* when older WebKit matters.
Break-avoidance is only reliable in block and table layout: flex and grid containers
paginate unpredictably across engines. For multi-page content, linearize to block flow
in print media (display: block on the flex/grid parents) or accept mid-item breaks.
Repeating table headers: thead { display: table-header-group; } repeats the header
on every page — but position: sticky on that same header silently disables it in some
engines. Strip sticky in print media.
Backgrounds and color: browsers strip backgrounds by default. Where they carry meaning (status chips, brand bars, zebra stripes):
.badge { print-color-adjust: exact; -webkit-print-color-adjust: exact; }Prefer borders and text color over backgrounds where possible — cheaper in ink and immune to the "backgrounds off" dialog setting.
Dark themes: never print a dark UI as-is. In print media, force a light scheme:
reset background to white and text to near-black at the root, and re-check contrast
of anything that relied on the dark backdrop.
Links: on paper, a link is just underlined text. Expand external URLs:
@media print {
a[href^="http"]::after { content: " (" attr(href) ")"; font-size: 0.85em; }
a[href^="#"]::after, nav a::after { content: ""; }
}Hide interactive chrome: buttons, inputs (or swap inputs for their values), video players (swap for a poster frame), and anything labeled "click," "tap," or "scroll."
4. Page numbers and running headers — know the real options
@page margin boxes (@top-center, counter(page), counter(pages)) are part of CSS
Paged Media but not implemented in browsers. CSS that uses them silently does nothing.
Never hand a user a counter(pages) solution for in-browser printing. The actual options:
- Headless generation (§5):
headerTemplate/footerTemplatewith the special classespageNumber,totalPages,date,title,url. Gotcha: templates render in an isolated context with font-size 0 in practice — set an explicitfont-sizeand inline styles, and reserve room for them via themarginoption. - Paged.js (polyfill): implements Paged Media in the browser, enabling margin boxes, page counters, and running headers for in-browser printing. Adds a chunking pre-render step; best for document-heavy products that need book-like output without server infra.
- Per-page footers via table hack: wrap content in a single table and put the running
footer in
tfoot(display: table-footer-group). Repeats per page but cannot show "Page X of Y". Fragile; use when 1–2 are unavailable.
If the user asks for page numbers on a plain window.print() flow, explain the constraint
and steer to option 1 or 2 rather than approximating.
5. Headless PDF generation (Playwright / Puppeteer)
Chromium-only (page.pdf() throws on Firefox/WebKit drivers). Baseline recipe:
await page.goto(url, { waitUntil: 'networkidle' });
await page.emulateMedia({ media: 'print' });
await page.evaluate(() => document.fonts.ready); // web fonts loaded
const pdf = await page.pdf({
format: 'A4',
printBackground: true,
preferCSSPageSize: true, // let @page { size } win over `format`
margin: { top: '15mm', bottom: '18mm', left: '15mm', right: '15mm' },
displayHeaderFooter: true,
footerTemplate: `<div style="font-size:9px; width:100%; text-align:center;">
Page <span class="pageNumber"></span> of <span class="totalPages"></span>
</div>`,
headerTemplate: `<div></div>`,
});Also: wait for any client-rendered charts/data to settle (an explicit "ready" flag on
document.body.dataset beats sleep-based waits); ensure lazy content is forced eager for
the print route; and note that the resulting PDF is untagged — if the document must
meet accessibility requirements (PDF/UA, Section 508), plan a tagging step or generate
via a tool that produces tagged output.
6. Color spaces: RGBA to CMYK conversion
Browsers are RGB environments. They composite pages in RGB, and their PDF export (window.print(), page.pdf()) generates RGB PDFs. Even if you specify colors using CSS color(device-cmyk ...) or HSL/RGBA, the browser's PDF engine will convert and export them in RGB.
Guidance & Suggestions:
- Office/Home Printing: RGB is perfectly fine. The printer driver will handle the RGB-to-CMYK conversion reasonably well.
- Commercial Printing: If the document is for a commercial press (requires true CMYK, spot colors, or true black text), browser-based printing cannot do this natively.
- Gamut warning: RGB has a wider color gamut than CMYK. Bright, neon RGB colors (like
rgba(0, 255, 0, 1)) will look muddy when printed. For print stylesheets, redefine your CSS color variables to CMYK-safe RGB values that won't shift drastically on paper.
Solutioning for CMYK Output: When a user explicitly needs a CMYK PDF, the solution is a two-step process:
- Use Playwright/Puppeteer to generate an RGB PDF.
- Post-process the PDF using a tool like Ghostscript to convert the color space to CMYK.
Example Ghostscript post-processing command to suggest:
gs -dSAFER -dBATCH -dNOPAUSE -dNOCACHE -sDEVICE=pdfwrite \
-sColorConversionStrategy=CMYK -dProcessColorModel=/DeviceCMYK \
-sOutputFile=output-cmyk.pdf input-rgb.pdfNote for true black: Standard RGB black (#000000) often converts to "Rich Black" (a mix of cyan, magenta, yellow, and black ink) during automated CMYK conversion, which can cause blurry text on commercial presses. If crisp text is critical, you must use a specific ICC color profile during the Ghostscript conversion to map RGB black directly to C0 M0 Y0 K100.
7. Failure modes checklist
Scan this list against the page before declaring done — none of these produce an error:
- Virtualized lists print a fraction of the data. react-window, TanStack Virtual,
AG Grid etc. render only visible rows. For print, render the full dataset into the
print container/route, or provide a non-virtualized print view. Same family: infinite
scroll, lazy-loaded routes/tabs, collapsed accordions — expand them in
beforeprintand restore inafterprint. overflow: hiddenon an ancestor clips print content into nothing. Audit the ancestor chain of the print root.loading="lazy"images print as blank boxes. Switch to eager in print context, or force-load inbeforeprintand wait.- Web fonts not ready → fallback-font output. Await
document.fonts.ready. position: fixedrepeats on every page in some engines, vanishes in others. Convert to static/absolute in print media.- Transforms, filters, and clip-paths break pagination and break-avoidance; strip them in print media.
- Canvas charts print blurry or blank. Canvas rasterizes at screen DPI. Prefer SVG
renderers for chart libraries that offer them; otherwise redraw the canvas at 2–3×
scale in
beforeprintor export to a high-resolution image for the print view. - Shadow DOM ignores document print CSS. Print styles must live inside the shadow root (or the component must expose parts/custom properties for print theming).
- Phantom trailing blank page — usually a
100vhmin-height, a trailing margin, or a sub-pixel overflow. Addhtml, body { height: auto }in print media and hunt the last element's box. - Sensitive data leaks into the PDF. Visually-hidden-but-in-DOM content (white text,
opacity: 0, off-screen positioning) survives in the PDF text layer. Redact withdisplay: noneor by omitting the data from the print markup entirely. - JS lifecycle:
beforeprint/afterprintfire for both Ctrl+P andwindow.print();matchMedia('print')covers engines with partial event support. Any DOM mutation for printing must be undone inafterprint— users keep using the page afterward.
8. Optimization
- Image resolution: screens are ~96 DPI, print is ~300 DPI. A 600px-wide image
spanning 160mm prints soft. Serve higher-resolution sources for print
(
image-set(),<picture>with a print-oriented source, or dedicated assets), but downsample anything larger than ~300 DPI at its printed size — beyond that is pure file-size waste in generated PDFs. - PDF size: the big levers are image resolution/compression and fonts. Subset embedded fonts; avoid embedding multiple full weights when two are used.
- Very long documents (hundreds of pages): pagination cost is superlinear with DOM
complexity. Flatten wrappers in the print view, avoid per-row
break-inside: avoidon huge tables (headers viatable-header-grouphandle continuity), and for headless generation consider chunking into sections and merging PDFs. - Ink/toner: default to white backgrounds, dark text, borders over fills. Reserve
print-color-adjust: exactfor elements where color carries meaning.
9. Debugging tooling — the two tiers of print preview
Browsers expose two preview tiers. Know which tier answers which question, and use the scriptable equivalents rather than asking the user to click through DevTools.
Tier 1 — media emulation: fast, scriptable, NOT paginated.
The DevTools toggle ("Emulate CSS media type: print" in Chrome/Edge's Rendering panel;
the page-icon toggle in Firefox's Rules panel) wraps the CDP command
Emulation.setEmulatedMedia — the same thing Playwright's
page.emulateMedia({ media: 'print' }) and Puppeteer's page.emulateMediaType('print')
call. With emulation active, an agent can iterate without rendering anything:
await page.emulateMedia({ media: 'print' });
// Assert resolved print styles directly:
const navDisplay = await page.$eval('nav', el => getComputedStyle(el).display); // 'none'
// JS media branches behave as they will at print time:
await page.evaluate(() => matchMedia('print').matches); // true
// Screenshot the restyled (unpaginated) layout for quick visual diffs:
await page.screenshot({ path: 'print-emulated.png', fullPage: true });Independently of emulation, audit what print CSS exists at all by walking CSSOM —
document.styleSheets → rules that are CSSMediaRules matching print — useful for
diagnosing "my print styles do nothing" (wrong media query, stylesheet media attribute,
or rules overridden at higher specificity).
Tier 2 — the paginated render: faithful, slower.
The browser's print-preview dialog is the true paginated preview but is not scriptable.
Its API equivalent is CDP Page.printToPDF — i.e. page.pdf() (§5), or with zero
dependencies: chrome --headless --print-to-pdf=out.pdf <url>. Same rendering path as
the dialog, so it is the only programmatic view of breaks, clipping, phantom pages, and
page count.
Workflow: iterate under Tier 1 (computed-style assertions, emulated screenshots),
confirm under Tier 2. Never conclude from Tier 1 alone — emulation can pass while the
paginated output has broken break-inside, clipped edges, or a trailing blank page,
because emulation restyles but never paginates. Engine caveats: page.pdf() is
Chromium-only; Firefox's print simulation exists only in the DevTools UI, with no
driver-level equivalent.
10. Verification — non-negotiable
DevTools "Emulate CSS media type: print" applies print styles but does not paginate; it cannot reveal break bugs, clipping, or phantom pages. Verify by producing a real paginated render:
- Print-to-PDF at both Letter and A4, at 100% scale (not "Fit to page" — fit-scaling masks overflow that will clip on a physical printer).
- Check: total page count sane, no clipped right/bottom edges, no blank pages, headings not orphaned at page bottoms, table headers repeating, backgrounds present where required.
- If the page has dynamic data, test the extremes: empty state, one row, and a dataset long enough to cross at least three pages.
- Cross-engine when it matters: Blink (Chrome/Edge) is the most capable; Gecko and WebKit
differ on
@page size, header groups, and break handling; iOS printing is the most constrained target and worth a device check if mobile users will print. - For headless pipelines, add a CI step that renders the print route to PDF and runs a visual regression against a blessed snapshot — print output regresses silently under ordinary CSS refactors.
Report results to the user in these terms ("3 pages on A4 and Letter, headers repeat, no clipping"), not as "the print styles are added."
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

