Write for a paginated print surface, not for a responsive browser window. Define paper size and margins with @page, add a dedicated @media print stylesheet, use semantic headings and predictable widths, control page breaks, and make every font, image, stylesheet, and link available to the converter. Then test long tables, images, unusual fonts, and section changes with the renderer you will deploy.
Start with the PDF’s geometry
A PDF has fixed pages. The browser can reflow a responsive layout indefinitely, but a PDF renderer must decide where each line and block lands on a finite sheet. Prince’s documentation describes this as the major difference between web and PDF/print formatting: PDF is paginated. Treat pagination as a design constraint from the first HTML template.
Set size, orientation, and margins explicitly
Put the page box in a print stylesheet or a stylesheet loaded only by the conversion job. This example establishes A4 portrait pages, a consistent content area, and page numbers in the footer.
@page {
size: A4 portrait;
margin: 22mm 18mm 24mm 18mm;
@bottom-right {
content: "Page " counter(page) " of " counter(pages);
font-size: 9pt;
color: #555;
}
}
@media print {
html, body { margin: 0; padding: 0; }
body {
color: #111;
background: #fff;
font: 10.5pt/1.45 "Inter", Arial, sans-serif;
}
}
@page chapter {
size: A4 portrait;
margin: 28mm 18mm 24mm 18mm;
}
.chapter { page: chapter; }
Use named pages when a cover, chapter, landscape table, or appendix genuinely needs different geometry. Do not rely on a browser’s default paper settings: defaults differ between engines and deployment environments.
#1 Best Overall
Keep screen and print rules separate
Hide navigation, cookie notices, menus, form controls, hover-only decoration, and other interactive elements under @media print. Give the printable document its own widths, colors, and spacing instead of trying to preserve every screen breakpoint. A predictable single-column flow is usually easier to paginate than a dashboard-style layout.
@media print {
.site-nav, .toolbar, .modal, .screen-only { display: none !important; }
.print-only { display: block; }
a { color: inherit; text-decoration: none; }
}
@media screen {
.print-only { display: none; }
}
Use semantic HTML as the document outline
Build one meaningful document tree: a single <h1>, followed by ordered <h2> and <h3> sections, paragraphs, lists, and real table headers. Semantic headings help readers and give renderers useful material for PDF bookmarks or outlines. WeasyPrint documents heading-based bookmarks in its PDF output.
- Use
<main>,<header>,<footer>,<section>, and<article>to describe regions. - Use
<th scope='col'>and<th scope='row'>for table relationships. - Use ordered lists for procedures and unordered lists for requirements; do not simulate lists with line breaks.
- Give images useful
alttext. Mark purely decorative images with an emptyaltattribute. - Keep heading text stable. It becomes navigation in many PDF viewers.
Control flow and page breaks deliberately
Keep related blocks together
Use modern and legacy break properties together because renderer support differs:
h1, h2, h3 { break-after: avoid; page-break-after: avoid; }
figure, table, .callout { break-inside: avoid; page-break-inside: avoid; }
.chapter { break-before: page; page-break-before: always; }
These rules are requests, not guarantees. A block taller than the printable page cannot be kept intact; it must split or overflow. Avoid placing an unbreakable card, image, or code listing inside a container that is larger than one page.
Recommended Free Tools
Make tables and code listings splittable
Long tables should use a real <thead> so the renderer can repeat column headings when a table continues. Allow rows to break only when the content makes that acceptable; a very tall row may still need to split.
table { width: 100%; border-collapse: collapse; }
thead { display: table-header-group; }
tfoot { display: table-footer-group; }
th, td { padding: 3mm 2mm; vertical-align: top; }
pre { white-space: pre-wrap; overflow-wrap: anywhere; }
Do not assume CSS flexbox or grid will paginate exactly as it does on screen. A renderer can move a flex or grid item to a later page when the remaining region is too small. For critical documents, use normal flow, fixed columns, or a tested table layout and inspect the actual PDF.
Handle widows, orphans, and section starts
Set reasonable paragraph widows and orphans where your renderer supports them, and begin major sections on a named page or with break-before. Avoid inserting dozens of manual page breaks: content edits will make them land in the wrong place. Prefer rules that express intent, such as keeping a heading with its first paragraph.
Make every asset resolvable in the conversion environment
Images and stylesheets
Use absolute URLs or a correctly configured base URL, and ensure the conversion process can reach them. A browser session that has your local cache or login is not evidence that a server-side converter can fetch the same asset. For private resources, provide the converter with the required headers or cookies through its documented configuration rather than embedding secrets in public HTML.
Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minutePC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Rank #3
- Check that each image URL returns an image, not an HTML error page.
- Set image dimensions or an aspect-ratio box to prevent large layout shifts.
- Use print-appropriate resolution and avoid files so large that rasterization exhausts memory.
- Keep CSS, images, and fonts at stable URLs or package them with the job.
Fonts and fallback behavior
Verify that the exact font files are installed or reachable by the converter and that embedding is permitted by their licenses. If a font is unavailable, line metrics change; headings wrap differently and every later page break can move. Define a deliberate fallback stack and inspect glyphs for accented characters, symbols, and non-Latin scripts.
Links and document metadata
Use normal https links and test that they remain clickable in the PDF. Decide whether the document needs a title, author, language, bookmarks, attachments, PDF/A archival conformance, or PDF/UA accessibility conformance before choosing a renderer and its options.
Choose an HTML-to-PDF renderer by capability
There is no authoritative reliability percentage or universal benchmark for these engines. Compare the capabilities that matter to your document and validate representative files in your own deployment.
| Concern | Prince | WeasyPrint |
|---|---|---|
| Core role | Converts HTML and XML to PDF by applying CSS. | HTML/CSS visual rendering engine that exports PDF. |
| Paged-media strengths | Advanced paged-media typesetting and generated content for page numbers, headers, and footers. | Page size, orientation, margins, counters, and page-margin features. |
| Links and outlines | Use the engine’s documented PDF features; exact support depends on the version and configuration. | Documents links, bookmarks, and attachments support. |
| PDF/A or PDF/UA | Confirm the required conformance in the version and license you deploy. | Documents PDF/A and PDF/UA output variants. |
| JavaScript execution | Not stated in the supplied documentation; test any script-dependent layout. | Not stated in the supplied documentation; test any script-dependent layout. |
| Deployment and cost | Choose when its paged-media feature set fits; licensing terms depend on your use. | Often selected for open-source or Python-centric automation; verify current deployment and licensing terms. |
Choose Prince when sophisticated paged-media typesetting and generated headers or footers are central. Choose WeasyPrint when a Python-oriented, open-source workflow and documented PDF features fit your requirements. If your HTML depends on client-side JavaScript, do not assume either engine will reproduce a browser session; render the data into HTML first or use an engine and configuration that you have explicitly tested.
Rank #4
A complete, repeatable conversion workflow
- Freeze the input. Generate a complete HTML document with all data present. Do not depend on a user clicking tabs or scrolling to trigger content.
- Attach print CSS. Set
@page, margins, typography, break rules, table headers, and hidden screen-only elements. - Resolve dependencies. Test every stylesheet, image, font, and link from the same machine, container, or service account that will run conversion.
- Render with a pinned engine version. Keep the renderer and its fonts consistent between development, CI, and production.
- Inspect the PDF. Check page count, clipping, blank pages, repeated headers, link targets, bookmarks, font appearance, and accessibility metadata.
- Test difficult fixtures. Include a long table, a multi-page image report, an unusual font, a section break, a very long URL, and missing or slow assets.
Python example with WeasyPrint
This script uses a local HTML file and writes a PDF. Set the base URL so relative images, CSS, and fonts resolve from the document directory.
from pathlib import Path
from weasyprint import HTML
source = Path('report.html').resolve()
output = Path('report.pdf')
HTML(filename=str(source), base_url=str(source.parent)).write_pdf(str(output))
print(f'Wrote {output.resolve()}')
For production, capture conversion logs, fail the job when required assets cannot be loaded, and keep a copy of the input HTML and CSS that produced each PDF. That makes a changed font or renderer version diagnosable.
Validate reliability before shipping
- Geometry: Confirm paper size, orientation, margins, trim-sensitive content, and page counters.
- Flow: Look for headings stranded at page bottoms, clipped content, unexpected blank pages, and split callouts.
- Tables: Verify repeated headers, readable columns, row splitting, and totals on the correct page.
- Assets: Check every image, font glyph, stylesheet, and external link in an environment without your browser cache.
- Accessibility: Inspect reading order, heading structure, language metadata, alt text, and the PDF/UA target if required.
- Archiving: Validate PDF/A only when your records policy requires it; conformance changes which fonts, colors, and metadata are acceptable.
- Regression: Keep representative PDFs or rendered page images and compare them after template, CSS, font, or engine changes.
Troubleshoot common conversion failures
| Symptom | Likely cause | Fix |
|---|---|---|
| Margins or paper size change | Browser defaults, conflicting @page rules, or a print-dialog setting. |
Set one explicit @page rule in the conversion stylesheet and configure the engine rather than relying on interactive print settings. |
| A heading is separated from its paragraph | The remaining page region is too small or the break rule is missing. | Use break-after: avoid on headings and reduce preceding spacing; accept a break when the following block cannot fit. |
| Images are blank or missing | Relative URLs, authentication, blocked network access, or an unsupported format. | Set a correct base URL, grant controlled access, verify the response content type, and test the exact conversion environment. |
| Text wraps differently in production | Different fonts, font versions, renderer versions, or fallback glyphs. | Package or install the approved fonts, pin the renderer, and inspect font-loading logs. |
| A table is clipped | Fixed widths exceed the printable area or an unbreakable row is too tall. | Use a width that fits inside margins, allow wrapping, reduce padding, or move a genuinely wide table to a named landscape page. |
| JavaScript-generated content is absent | The selected converter did not execute the script or the script timed out. | Render data into the HTML before conversion, or select and test a browser-capable workflow explicitly. |
| Links are not clickable | Malformed URLs, overlays, or a renderer/configuration limitation. | Use valid absolute links, remove intercepting overlays in print CSS, and inspect the PDF’s link annotations. |
| Unexpected blank pages | Adjacent forced breaks, oversized blocks, or named-page transitions. | Remove duplicate break-before/page-break-before rules and test the smallest fixture that reproduces the issue. |
Performance, reliability, and operating cost
Conversion time is dominated by document size, image decoding, font loading, network resources, and the renderer’s layout work. Keep assets local to the job when possible, resize images before embedding them, avoid loading screen-only media, and set explicit timeouts for external resources. Cache immutable fonts and stylesheets, but invalidate the cache when their contents change.
Run conversion in a controlled worker rather than inside a request that can be abandoned by a browser. Record renderer version, operating-system image, fonts, input hash, output hash, duration, warnings, and failure reason. Retry transient asset failures with a limit; do not silently publish a PDF with missing content. There is no meaningful single “reliability” score—your fixture suite and production observability are the evidence that matters.
The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Best Value
Or skip the browser setup
If your immediate need is a PDF or image of a public URL rather than a fully controlled HTML-to-PDF pipeline, ScreenshotNeo makes one API request. It captures a URL as PNG, JPEG, WebP, or PDF and can load lazy images, apply custom CSS or JavaScript, wait for a selector, delay, or network idle, and set paper size, margins, orientation, and page ranges for PDF output.
Its clean-capture steps accept consent banners and remove more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the page verdict and billing status in X-Page-Verdict and X-Billed headers. An MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients.
See the ScreenshotNeo documentation for parameters and response details. A direct call looks like this:
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.com/report -o report.pdf
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://example.com/report"}, timeout=90)
r.raise_for_status()
open("report.pdf", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://example.com/report' });
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());
await import('node:fs/promises').then(fs => fs.writeFile('report.pdf', data));
The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots, and every feature is on every plan. Create a free ScreenshotNeo account to try it without a card.
Free tools Windows power users keep installed
One-click scans. No signup required.
FAQ
Should I maintain separate HTML templates for web and PDF?
Usually keep one semantic document and add a dedicated print stylesheet. Split templates only when the PDF’s information architecture is fundamentally different from the interactive application.
Can CSS alone guarantee that a block never splits?
No. Break controls are hints constrained by the available page area. An element taller than a page must overflow or split, so design large tables, images, and code listings to be divisible.
When should a PDF be PDF/A or PDF/UA?
Use PDF/A for archival requirements and PDF/UA for accessibility requirements established by your organization or regulator. Decide that target before selecting and configuring the renderer, then validate the resulting file.
Is a screenshot service equivalent to semantic HTML-to-PDF conversion?
No. A screenshot service is convenient for capturing a rendered URL, while a controlled renderer gives you ownership of document structure, fonts, pagination rules, and conformance testing. Choose based on whether you need a quick capture or a reproducible publishing pipeline.
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 →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →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.

