The most reliable way to convert modern HTML to PDF is to render it in a headless Chromium browser, wait for the page, images, and fonts to finish loading, then call the browser’s PDF API. Playwright and Puppeteer preserve JavaScript, web fonts, and browser CSS more faithfully than non-browser converters. For simpler, print-oriented documents, Python’s WeasyPrint or an existing wkhtmltopdf pipeline may be sufficient.
Choose the renderer before writing code
Your source determines the right conversion engine. A real web page with client-side JavaScript, responsive CSS, and web fonts generally needs Chromium. A controlled report template may not.
| Approach | Best fit | Important trade-offs |
|---|---|---|
| Playwright with Chromium | Modern pages, JavaScript applications, web fonts, and browser-faithful CSS | Browser binaries, operating-system libraries, fonts, process lifecycle, and concurrency must be managed. |
| Puppeteer with Chromium | Node.js services already built around the Chrome DevTools ecosystem | Has the same browser-runtime and resource-management requirements; PDF output uses print media by default. |
| WeasyPrint | Python services producing print-oriented HTML and CSS | It is not a browser, so CSS behavior differs. Its documentation warns that untrusted HTML or CSS can create security problems. |
| wkhtmltopdf | Existing command-line or WebKit-based conversion pipelines | It is a separate Qt WebKit executable. Validate modern CSS and JavaScript requirements before adopting it. |
| PDFKit | Documents built programmatically from text, vectors, images, and layout primitives | It constructs PDFs; it does not render arbitrary HTML as a browser does. |
There is no universally fastest library. Measure representative documents in the same runtime, browser version, fonts, and container image that you will use in production.
Node.js: convert HTML with Playwright
Install the package and browser
Create a Node project and install Playwright. The browser executable must be installed separately and kept aligned with the package version.
#1 Best Overall
- Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
- Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
- Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
- Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
- 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
npm install playwright
npx playwright install --with-deps chromium
On a developer workstation, npx playwright install chromium is usually enough. The --with-deps option also installs Linux dependencies when your environment permits it.
A complete conversion function
This function accepts an HTML string, waits for network activity to settle, waits for fonts and images, and returns a PDF buffer suitable for an HTTP response or object storage.
import { chromium } from 'playwright';
export async function htmlToPdf(html) {
const browser = await chromium.launch({ headless: true });
try {
const page = await browser.newPage({
viewport: { width: 1280, height: 900 },
deviceScaleFactor: 1
});
await page.setContent(html, { waitUntil: 'networkidle' });
await page.evaluate(async () => {
await document.fonts.ready;
const images = Array.from(document.images);
await Promise.all(images.map(image => {
if (image.complete) return Promise.resolve();
return new Promise(resolve => {
image.addEventListener('load', resolve, { once: true });
image.addEventListener('error', resolve, { once: true });
});
}));
});
return await page.pdf({
format: 'A4',
printBackground: true,
preferCSSPageSize: true,
margin: {
top: '16mm',
right: '14mm',
bottom: '16mm',
left: '14mm'
}
});
} finally {
await browser.close();
}
}
const pdf = await htmlToPdf('<!doctype html><html><body><h1>Invoice</h1></body></html>');
await import('node:fs/promises').then(fs => fs.writeFile('document.pdf', pdf));
For a web endpoint, set Content-Type: application/pdf, set Content-Disposition to inline or attachment, and write the returned buffer to the response. Always close the browser in a finally block, including when navigation or PDF generation fails.
Use an existing page instead of an HTML string
When the document is already hosted, navigate to its absolute URL and wait for the application-specific ready state. A fixed delay can be useful as a last resort, but waiting for a selector is more deterministic.
Do these 3 things before closing this tab:
1Clear out junk files and repair common Windows errors2Fix the driver behind crashes, sound loss and screen glitches3Repair Windows errors before they cause bigger problemsawait page.goto('https://example.com/invoice/123', {
waitUntil: 'domcontentloaded',
timeout: 60000
});
await page.waitForSelector('[data-pdf-ready]', { timeout: 30000 });
await page.evaluate(() => document.fonts.ready);
const pdf = await page.pdf({ format: 'A4', printBackground: true });
If the page requires authentication, set cookies or headers on the browser context rather than embedding secrets in visible HTML. Use a dedicated service account with only the permissions needed to render the document.
Rank #2
- 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
- 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
- Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
- 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
- What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
Control paper size, colors, and page breaks with print CSS
Chromium PDF generation uses the print CSS media type by default. If your screen layout is the intended output, call page.emulateMediaType('screen') before generating the PDF. Otherwise, define print-specific rules explicitly.
@page {
size: A4;
margin: 16mm 14mm;
}
@media print {
nav, .toolbar, .no-print {
display: none !important;
}
a {
color: inherit;
text-decoration: none;
}
h1, h2, h3 {
break-after: avoid;
}
table, figure, .card {
break-inside: avoid;
}
.chapter {
break-before: page;
}
}
- Backgrounds: set
printBackground: truewhen colored panels, gradients, or background images matter. - Sheet size: use
format, or use CSS@pageand keeppreferCSSPageSize: trueso CSS controls the paper. - Custom dimensions: provide
widthandheightinstead of a named format for labels or receipts. - Margins: specify top, right, bottom, and left values; reserve space if you add headers or footers.
- Page ranges: Playwright can emit only selected ranges such as
1-3or2,4. - Scale: use the PDF scale option sparingly. CSS page sizing is usually more predictable.
- Headers and footers: provide header and footer templates when page numbers or dates are required, and test their available height.
- Tagged output: Playwright exposes a tagged-PDF option. Validate the resulting file with an accessibility checker; the option alone does not prove conformance.
Make dynamic content deterministic
networkidle does not guarantee that a single-page application has finished rendering. Prefer an application signal such as [data-pdf-ready], a completed API request, or a known status element. Wait for document.fonts.ready; otherwise fallback fonts can change line wrapping and page count.
Use absolute asset URLs or inline images and stylesheets. A renderer running in a container must be able to resolve every permitted host. If an image is lazy-loaded, scroll it into view or use the page’s full-page capture logic before converting. Disable animations and transitions for repeatable output, for example by injecting a print stylesheet that sets animation: none and transition: none.
For repeatability, pin the Playwright package, browser binaries, operating-system image, and installed fonts. Keep representative HTML fixtures and compare page count, text placement, images, links, and margins after upgrades.
Puppeteer equivalent
Puppeteer follows the same browser pattern: launch, navigate, wait, call page.pdf(), and close. Its PDF guide notes that PDF generation waits for fonts by default.
Rank #3
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
import puppeteer from 'puppeteer';
const browser = await puppeteer.launch({ headless: true });
try {
const page = await browser.newPage();
await page.setContent(html, { waitUntil: 'networkidle0' });
await page.evaluate(() => document.fonts.ready);
await page.pdf({
path: 'document.pdf',
format: 'A4',
printBackground: true,
preferCSSPageSize: true,
margin: { top: '16mm', right: '14mm', bottom: '16mm', left: '14mm' }
});
} finally {
await browser.close();
}
Call page.emulateMediaType('screen') when screen media, rather than print media, is what your design expects.
Python and command-line alternatives
WeasyPrint
For a Python service with controlled, print-oriented templates, WeasyPrint provides a direct API.
Quick wins for a faster PC:
Scan for outdated or missing drivers - takes under a minuteDriver Scan →Clear out junk files and repair common Windows errorsFree Scan →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →from weasyprint import HTML
HTML(string=html, base_url='https://your-app.example/').write_pdf('document.pdf')
base_url lets relative images, fonts, and stylesheets resolve. WeasyPrint’s CSS behavior is not identical to Chromium, so test flexbox, grid, JavaScript-dependent content, and advanced web APIs before switching. Never pass arbitrary user HTML or CSS into a privileged process: isolate the worker, restrict outbound requests, and enforce CPU, memory, and time limits.
wkhtmltopdf
An existing pipeline can invoke the Qt WebKit-based executable:
wkhtmltopdf --print-media-type --enable-local-file-access input.html document.pdf
Only enable local-file access when the input directory is trusted. Validate modern CSS and JavaScript behavior on your actual documents; a successful command does not mean the layout matches a Chromium render.
Rank #4
- Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
- Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
- Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
- Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
- Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
PDFKit
Use PDFKit when you want to place text, vectors, and images yourself. It streams a PDF but does not parse arbitrary HTML, so adopting it usually means rebuilding layout rules in application code.
Free tools Windows power users keep installed
One-click scans. No signup required.
Security boundaries for HTML-to-PDF services
HTML and CSS are executable input. A malicious document can request internal URLs, consume excessive resources, or exploit browser and operating-system capabilities.
- Run conversion in an isolated worker or container without application secrets.
- Apply navigation, CPU, memory, and output-size limits.
- Allow-list outbound hosts and block cloud metadata endpoints and private network ranges.
- Validate image, stylesheet, font, iframe, and redirect URLs before fetching them.
- Do not expose authenticated cookies, bearer tokens, or environment variables to page content.
- Sanitize user data before inserting it into HTML and disable unnecessary browser features.
- Delete temporary files and close every page, context, and browser on success or failure.
Deployment, throughput, and cost considerations
Browser startup is expensive compared with rendering a second document in an already-running process. For sustained traffic, keep a bounded browser pool and create isolated contexts or pages per job. Do not create unlimited tabs: cap concurrency according to available CPU and memory, then queue excess requests.
Set an end-to-end timeout that includes navigation, asset loading, font readiness, and PDF writing. Return a clear error when the deadline expires rather than leaving a worker running. In containers, install browser binaries, shared libraries, and all required fonts in the image; keep package and browser versions aligned.
Cost is driven by your infrastructure, job duration, concurrency, and storage. Benchmark typical short, long, image-heavy, and JavaScript-heavy documents in the target environment. No official documentation establishes a universal speed winner.
Recommended Free Tools
Best Value
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
Troubleshooting common failures
| Symptom | Likely cause | Fix |
|---|---|---|
| Browser executable not found | The Playwright or Puppeteer package is installed but its browser binary is not. | Run the matching browser install command during image build and verify the cache path used at runtime. |
| Blank or half-rendered pages | Conversion began before application data, images, or fonts finished loading. | Wait for a ready selector, await document.fonts.ready, and explicitly wait for image completion. |
| Missing backgrounds | Background printing is disabled. | Set printBackground: true and check that print CSS does not remove the background. |
| Unexpected paper size or margins | CSS @page rules conflict with API options. |
Choose one source of truth and use preferCSSPageSize: true when CSS should win. |
| Screen layout differs from PDF | Print media rules are being applied. | Adjust @media print, or call page.emulateMediaType('screen') deliberately. |
| Fonts wrap differently in production | The required font is unavailable, blocked, or not ready. | Install the font in the image, use reachable or embedded assets, and wait for the font set before printing. |
| Navigation timeout | A third-party request, long poll, or unreachable asset prevents the chosen wait condition. | Use an application-ready selector, set a bounded timeout, and block unnecessary requests. |
| Out-of-memory crashes | Too many concurrent pages or oversized images. | Limit pool size, reject unreasonable input, resize images, and recycle unhealthy browser workers. |
| WeasyPrint output lacks interactive content | WeasyPrint does not execute browser JavaScript. | Pre-render the data into HTML or use Chromium for JavaScript-dependent pages. |
Verify every generated PDF
Automated checks should open the file and verify that it is a valid PDF, has the expected page count and paper size, contains required text, and includes links and images. Review representative pages visually for clipping, widows and orphans, broken tables, header overlap, and incorrect colors. If accessibility is a requirement, inspect reading order, headings, language metadata, text alternatives, and tagged structure with a dedicated PDF validator.
Or skip the browser setup
If the HTML is already reachable at a URL, ScreenshotNeo can return a PDF from one GET request without you packaging Chromium. Its capture flow accepts consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each cleanup step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the result with X-Page-Verdict and X-Billed headers.
curl -G "https://api.screenshotneo.com/v1/shot"
-d access_key=YOUR_API_KEY
--data-urlencode url=https://example.com/invoice/123
-o invoice.pdf
See the ScreenshotNeo API documentation for output and option details. The equivalent Node.js and Python calls are:
import requests
r = requests.get(
'https://api.screenshotneo.com/v1/shot',
params={'access_key': 'YOUR_API_KEY', 'url': 'https://example.com/invoice/123'},
timeout=90
)
r.raise_for_status()
open('invoice.pdf', 'wb').write(r.content)
const q = new URLSearchParams({
access_key: 'YOUR_API_KEY',
url: 'https://example.com/invoice/123'
});
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`ScreenshotNeo request failed: ${res.status}`);
await Bun.write('invoice.pdf', res);
ScreenshotNeo also provides an MCP server with take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. It supports full-page capture, CSS-selector element capture, dark mode, device and viewport settings, retina scale, paper size, margins, landscape mode, page ranges, custom CSS and JavaScript, click and wait actions, request blocking, headers, cookies, user agents, authorization, timezone, geolocation, caching, signed links, asynchronous jobs, webhooks, bulk capture of up to 100 URLs per call, usage reporting, and an OpenAPI specification. Parameter names used by other screenshot APIs also work.
Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallOutdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchEvery feature is included on every plan: Free provides 1,000 shots per month with no card; Starter is $5 for 3,000; Growth is $15 for 15,000; Pro is $39 for 60,000; Scale is $99 for 250,000; and Business is $249 for 1,000,000. Yearly billing gives two months free. Create a free ScreenshotNeo account to start with 1,000 screenshots a month and no card.
Frequently Asked Questions
Should I use a URL or an HTML string as the input?
Use an HTML string when your service owns the complete template and assets. Use a URL when an application route already assembles authentication, data, and browser-side rendering; then wait for an explicit ready signal before printing.
How do I keep PDFs stable after browser updates?
Pin the renderer package, browser binary, operating-system image, and fonts, and run fixture-based visual and text checks before upgrading any of them.
Can a PDF contain only selected pages?
Yes. Playwright exposes page-range selection, so a service can emit ranges such as 1-3 or 2,4 after the complete document has rendered.
The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →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.

