How to Fit Dynamic Data into an A4-Sized HTML Page
Learn how to format changing HTML data for A4 print and PDF output, handle pagination, prevent awkward splits, and capture reliable PDFs.

Direct answer: use CSS paged-media rules to define the paper, then let variable content flow across as many pages as necessary. Set @page { size: A4; margin: ... }, keep print-only changes in @media print, and use break-inside: avoid selectively for short components that should stay together. An A4 page definition does not make arbitrary dynamic data fit on one sheet. If you require exactly one sheet, you must define a limit, omit lower-priority fields, change the layout, or scale content within readable limits.
1. Decide what “fit on A4” means
There are two different requirements:
- A4 pages with natural pagination: the document uses A4 sheets and creates more pages when records, paragraphs, or table rows grow.
- Exactly one A4 sheet: all content must remain inside one physical page, so the product must define what happens when data grows.
CSS can select the page format and influence fragmentation. It cannot know which fields are safe to remove or how much text a reader is willing to compress. Treat one-page output as a product rule: cap the number of rows, shorten labels, omit optional sections, switch to landscape where appropriate, or apply a controlled typography and spacing reduction.
2. A minimal A4 print stylesheet
Start with a normal, flowing document. Do not put all content in a fixed-height box and depend on overflow. The following CSS sets A4 portrait pages with a 12 mm margin, hides screen controls, and keeps compact records together.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Invoice report</title>
<style>
@page {
size: A4 portrait;
margin: 12mm;
}
* { box-sizing: border-box; }
body {
margin: 0;
color: #1d2430;
font: 10.5pt/1.45 Arial, sans-serif;
background: #eef1f5;
}
.document {
max-width: 190mm;
margin: 0 auto;
background: white;
}
.screen-only { display: block; }
.record-card {
margin: 0 0 8mm;
padding: 5mm;
border: 0.25mm solid #ccd3dc;
break-inside: avoid;
}
.long-content { break-inside: auto; }
@media print {
body { background: white; }
.screen-only, nav, button { display: none !important; }
.document { max-width: none; }
.record-card { break-inside: avoid; }
.long-content { break-inside: auto; }
}
</style>
</head>
<body>
<nav class="screen-only">
<button type="button" onclick="window.print()">Print</button>
</nav>
<main class="document" id="report"></main>
<script>
const records = [
{ id: 'A-100', customer: 'Northwind', amount: 1250, notes: 'Paid in full.' },
{ id: 'A-101', customer: 'Contoso', amount: 980, notes: 'Awaiting approval.' },
{ id: 'A-102', customer: 'Fabrikam', amount: 2140, notes: 'Includes a long, variable note that may flow naturally.' }
];
const money = new Intl.NumberFormat('en-US', {
style: 'currency', currency: 'USD'
});
document.querySelector('#report').innerHTML = records.map(record => `
<article class="record-card">
<h2>Invoice ${record.id}</h2>
<p><strong>Customer:</strong> ${record.customer}</p>
<p><strong>Amount:</strong> ${money.format(record.amount)}</p>
<p class="long-content">${record.notes}</p>
</article>`).join('');
</script>
</body>
</html>
The screen preview is only an approximation. The @page rule is the authority for paged output; the browser’s print dialog, selected printer settings, fonts, images, and PDF pipeline can affect the final result.
3. Configure page size, margins, and orientation
@page describes the page box used for printed or PDF output. Typical declarations are:
@page {
size: A4 portrait;
margin: 12mm 14mm 16mm 14mm;
}
/* Use this only when the document requirement calls for landscape. */
@page landscape-report {
size: A4 landscape;
margin: 10mm;
}
.landscape-section {
page: landscape-report;
}
Keep margins in physical units such as mm when the output is paper or a PDF intended to represent paper. Avoid using a fixed pixel height for an A4 sheet: the CSS pixel-to-physical conversion and print scaling are renderer concerns, while dynamic content can exceed the assumed height.
4. Separate screen and print layouts
Use @media print for controls that help on screen but do not belong on paper. Navigation, filters, expand buttons, debugging details, and interactive widgets can be hidden. You can also change colors, spacing, and borders for legibility.
@media print {
.screen-only,
nav,
.filters,
button,
.debug-panel {
display: none !important;
}
a {
color: inherit;
text-decoration: none;
}
.report-header {
margin-bottom: 6mm;
}
}
Do not hide data merely because it is inconvenient to paginate. Decide explicitly which fields are optional, and make that policy visible in the product or export settings.
5. Let dynamic content paginate naturally
Long paragraphs, growing tables, and lists should be allowed to fragment. A keep-together rule is a preference, not a guarantee that an oversized block will fit on one page.

.summary-card,
.signature-block,
.short-address {
break-inside: avoid;
}
.long-paragraph,
.long-table,
.document-body {
break-inside: auto;
}
/* Legacy alias retained for older engines that still use it. */
.legacy-card {
break-inside: avoid;
page-break-inside: avoid;
}
page-break-inside is deprecated; use break-inside in new styles and retain the older declaration only when compatibility with an older renderer is necessary. Applying break-inside: avoid to every element can create large blank areas or force awkward overflow, so reserve it for short coherent units.
6. Build tables that survive changing rows
Tables are a common source of surprises because row content changes height. Keep each short row together when possible, but allow a long cell or a very large table to continue onto another page.
<table class="line-items">
<thead>
<tr><th>Item</th><th>Description</th><th>Total</th></tr>
</thead>
<tbody>
<!-- generated rows -->
</tbody>
</table>
<style>
.line-items { width: 100%; border-collapse: collapse; }
.line-items th, .line-items td {
padding: 2.5mm 2mm;
border-bottom: 0.2mm solid #d9dee5;
vertical-align: top;
overflow-wrap: anywhere;
}
.line-items tr { break-inside: avoid; }
.line-items thead { display: table-header-group; }
</style>
Use representative short, typical, and worst-case rows while reviewing output. Check long unbroken identifiers, localized dates, currency symbols, missing values, and user-entered text. If a single row is taller than the printable area, no break rule can make that row fit intact; allow it to split or redesign the row.
7. Handling the exactly-one-page requirement
If stakeholders require one A4 sheet, write the policy before writing CSS. Common policies include:
- Limit the number of records and show a “+N more” summary.
- Remove low-priority columns or optional metadata.
- Use a compact grid instead of a vertical card layout.
- Switch to landscape for wide tables.
- Reduce type size and spacing only within an agreed readability floor.
- Generate a separate appendix containing the full data.
Do not silently clip overflow. A clipped total, signature, or legal clause creates an incomplete document and is difficult to detect from the source HTML.
8. Rendering dynamic HTML to a PDF
When users print locally, let them inspect the browser preview and choose their printer or “Save to PDF” destination. For automated documents, use your chosen server-side browser or PDF pipeline and test its interpretation of @page, margins, fonts, images, and break rules. The paged-media model has implementation differences, so a stylesheet that looks correct in one environment still needs verification in the environment that produces the deliverable.
Capture a fixture set containing an empty report, a normal report, a report with many rows, long translated strings, missing images, and the largest expected record. Compare page count, clipped content, unexpected blank space, and header or footer placement after every renderer change.
9. Or skip the browser setup
For a hosted page that already contains your dynamic data, ScreenshotNeo can return a PNG, JPEG, WebP, or PDF from one GET request. It can capture full pages, load lazy images, apply custom CSS or JavaScript, wait for a selector, delay, or network idle, and set paper size, margins, landscape mode, and page ranges for PDF output. See the ScreenshotNeo API documentation for the complete option list.

Cookie banners, newsletter popups, and chat widgets are removed before the shot. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and whether it was billed. An MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients.
cURL
curl -G "https://api.screenshotneo.com/v1/shot" \
-d access_key=YOUR_API_KEY \
--data-urlencode url=https://stripe.com \
-o shot.webp
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)
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 data = Buffer.from(await res.arrayBuffer());
require('node:fs').writeFileSync('shot.webp', data);
For an A4 PDF, add the PDF format, paper size, margins, orientation, and page range parameters documented by ScreenshotNeo. You can also pass custom headers, cookies, a user agent, authorization, timezone, geolocation, a CSS selector for one element, hide selectors, resource blocking, caching with a chosen TTL, signed links, asynchronous jobs with signed webhooks, or bulk capture for up to 100 URLs per call. Every plan includes these features. The Free plan includes 1,000 shots per month without a card; paid plans start at $5 for 3,000 shots, with yearly billing providing two months free. Create a free ScreenshotNeo account.
10. Troubleshooting checklist
| Symptom | Likely cause | Fix |
|---|---|---|
| Content is clipped at the bottom | Fixed-height container or forced one-page layout | Remove the height constraint, allow normal flow, and inspect every page. |
| A card leaves a large blank area | break-inside: avoid applied to a block that is too tall |
Use the rule only for short cards; allow long content to split. |
| Controls appear in the PDF | Print selectors do not hide screen-only elements | Add them to an @media print rule with display: none !important. |
| Table columns run off the page | Unbreakable text or too many wide columns | Use overflow-wrap: anywhere, shorten labels, remove optional columns, or choose landscape. |
| Images or fonts change page count | Assets load late or have no reserved dimensions | Wait for the assets in the rendering pipeline, specify image dimensions, and test with the production fonts. |
| Different browsers paginate differently | Paged-media support and print settings vary | Test the target browser or PDF engine and pin the rendering environment for automated output. |
| ScreenshotNeo returns a blank or failed result | The page did not finish loading, requires authentication, or triggered a bot check | Use wait settings, pass the required headers or cookies, and inspect X-Page-Verdict and X-Billed; these failed results are not billed. |
11. Performance, reliability, and cost
- Performance: keep print CSS small, avoid unnecessary high-resolution assets, and wait only for the selector or network condition that proves the data is ready. Full-page captures and large tables naturally take longer than a single element.
- Reliability: test deterministic fixture data, reserve space for images, use stable fonts, and verify page count and critical fields. For asynchronous ScreenshotNeo jobs, use signed webhooks and retain the verdict headers or job result with your artifact.
- Cost: local browser printing has no API capture charge. ScreenshotNeo bills only clean shots; bot checks, blank pages, timeouts, failed loads, and cache hits cost nothing. Caching with a TTL, bulk capture, and the usage API help control repeated work.
12. FAQ
Does size: A4 force one page?
No. It selects the page format. Dynamic content can continue onto additional A4 pages.
Should every element use break-inside: avoid?
No. Apply it to short coherent units. Long text and tables should usually be allowed to fragment.
Can CSS decide which fields to omit when data grows?
No. Omitting fields is a product decision that belongs in your rendering logic or an explicit export mode.
Is page-break-inside still the preferred property?
No. It is deprecated. Use break-inside, retaining the older property only as a compatibility alias when needed.
Can I capture an A4 PDF without running Chromium myself?
Yes. ScreenshotNeo accepts a URL and PDF options through its API, while handling page loading, consent cleanup, waits, and capture for you.


