What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Handlebars only produces the HTML string. The PDF engine must then resolve the stylesheet URL, fetch the CSS, wait for it to finish loading, and apply print rules. A reliable pipeline is: compile the template, give the generated document a usable base URL, make every stylesheet and asset reachable from the renderer process, wait for loading (and fonts), then call the PDF method with the print options your design requires.

What actually happens between a Handlebars template and a PDF

Handlebars compiles a template and evaluates it with your data; it does not render CSS or fetch linked files. The resulting HTML is handed to a browser (such as Chromium through Puppeteer) or to a non-browser renderer (such as WeasyPrint). That second component resolves <link rel="stylesheet">, downloads the resource, parses it, and lays out the page.

Therefore, CSS that appears in a developer browser can still be absent from a server-generated PDF. The browser may have a different origin, credentials, filesystem access, cache, or network route. Treat stylesheet loading as a renderer and deployment problem, not a Handlebars compilation problem.

A dependable workflow

  1. Compile and evaluate the template. Produce the final HTML with all data substituted before starting PDF generation.
  2. Include a stylesheet link in that HTML. Use an absolute HTTPS URL when possible. If the href is relative, provide a meaningful document base with <base href="https://example.test/"> or load the page from a route with a stable origin.
  3. Make the resource reachable by the renderer. Check DNS, outbound network policy, TLS certificates, filesystem permissions, authentication, cookies, and any URL-fetcher restrictions.
  4. Wait for the page and its resources. Navigation completion alone is not proof that late CSS, fonts, or images are ready. Wait for an appropriate network-idle condition and, where necessary, explicit selectors or font readiness.
  5. Generate with print settings deliberately. PDF output normally uses print media CSS. Enable background printing if your design depends on background colors or images.

Puppeteer: complete Handlebars-to-PDF example

This Node.js pattern compiles a template, loads the generated HTML, adds a linked stylesheet, waits for the document, and writes a PDF. Replace the example stylesheet URL with one the browser process can reach.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • 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.
import fs from 'node:fs/promises';
import Handlebars from 'handlebars';
import puppeteer from 'puppeteer';

const source = await fs.readFile('./invoice.hbs', 'utf8');
const template = Handlebars.compile(source);
const html = template({
  invoiceNumber: 'INV-1042',
  customer: 'Ada Lovelace',
  total: '$240.00'
});

const browser = await puppeteer.launch({ headless: true });
try {
  const page = await browser.newPage();
  await page.setContent(html, { waitUntil: 'domcontentloaded' });

  await page.addStyleTag({
    url: 'https://example.test/assets/print.css'
  });

  await page.evaluate(() => document.fonts.ready);
  await page.waitForNetworkIdle({ idleTime: 500, timeout: 10000 });

  await page.pdf({
    path: './invoice.pdf',
    format: 'A4',
    printBackground: true,
    preferCSSPageSize: true
  });
} finally {
  await browser.close();
}

page.addStyleTag({ url }) appends a stylesheet link to the loaded page. You can instead inject CSS text with page.addStyleTag({ content: css }) when the stylesheet is bundled with your application. If you use a link in the Handlebars template, keep the same loading and waiting steps; adding the tag in Puppeteer is simply a useful way to control the operation after navigation.

Use a stable base for relative URLs

<!doctype html>
<html>
  <head>
    <base href="https://example.test/">
    <link rel="stylesheet" href="assets/print.css">
  </head>
  <body>...</body>
</html>

Without a base, a document created with page.setContent() may not have the origin you assumed. A relative CSS URL such as /assets/print.css can consequently resolve to the wrong place or nowhere. An absolute URL is the least ambiguous choice for an HTML string that is never served from your application.

When the page is already loaded

If navigation has already happened, add the stylesheet and wait for the returned promise. The promise resolves after the style element is added; you should still wait for network activity and fonts before printing.

await page.addStyleTag({ url: 'https://example.test/assets/print.css' });
await page.evaluate(() => document.fonts.ready);
await page.pdf({ path: 'output.pdf', printBackground: true });

Print CSS and PDF options that change the result

Puppeteer generates PDFs using the print CSS media type. Rules inside @media screen may therefore be ignored, while @media print rules can override the layout you saw in a normal browser tab.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Setting or rule What it changes Typical action
@media print Styles applied during PDF layout Put print-specific visibility, colors, and page-break rules here.
printBackground Whether CSS background colors and images are painted Set true; the default is false.
preferCSSPageSize Whether @page dimensions take precedence Use true when your stylesheet defines page size.
document.fonts.ready Font-loading completion before layout Await it when custom fonts affect wrapping or pagination.

For example:

@page {
  size: A4;
  margin: 16mm;
}

@media print {
  .screen-only { display: none !important; }
  .avoid-break { break-inside: avoid; }
}

WeasyPrint and other non-browser renderers

WeasyPrint also supports linked stylesheets, but its resource-fetching model is different from Chromium’s. Its URL fetcher must be able to retrieve every stylesheet, image, and font. A local file may require a file:// URL and appropriate permissions; an HTTP resource may require outbound access and a valid certificate.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 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.

When resources need cookies, authentication headers, or a private network route, the default fetch behavior may not be sufficient. Configure a custom URL fetcher or make a controlled, authenticated copy of the resource available to the rendering process. Do not assume that credentials present in your web browser are available to a background worker.

The same base-URL rule applies: relative paths need a document origin. Use an explicit <base> where supported, an absolute stylesheet URL, or a renderer configuration that establishes the document’s base URL.

Resource loading checklist

  • Log the final HTML and inspect the exact stylesheet href after Handlebars evaluation.
  • Resolve relative URLs against the renderer’s actual base, not the directory containing your template source.
  • From the PDF worker’s host or container, fetch the CSS URL with the same DNS, proxy, and firewall conditions.
  • Confirm the response is CSS (normally a successful response with a CSS content type), not a login page, redirect, or error document.
  • Check fonts and images referenced inside the CSS; those URLs need the same reachability and base.
  • Wait for network idle, explicit application-ready selectors, and document.fonts.ready when those resources affect layout.
  • Inspect print rules, page size, margins, and background settings before diagnosing a missing stylesheet.

Troubleshooting common failures

The link is present, but no styles appear

First print the evaluated HTML and verify the URL. If it is relative, add a base element or change it to an absolute URL. Then test the URL from the same machine, container, or worker identity that creates the PDF. A browser on your laptop succeeding is not a valid server-side test.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The stylesheet request returns a login page or 403

The renderer lacks the browser session or authorization required by the asset host. Serve a renderer-specific authenticated endpoint, configure request headers/cookies where your renderer supports them, or provide a controlled local copy. Avoid embedding long-lived secrets in template data.

Styles load intermittently

The PDF call is racing late network activity. Use navigation with an appropriate wait condition, then wait for network idle or an application selector that indicates rendering is complete. Add an explicit timeout only as a last resort; a fixed delay alone can be either too short or unnecessarily slow.

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • 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.

Colors or background artwork are missing

Enable printBackground: true. Also check whether a print rule intentionally changes the color and whether the asset URL inside background-image resolves from the same base as the stylesheet.

Text wraps differently or falls back to another font

Await document.fonts.ready, verify that font files are reachable, and check their cross-origin and certificate configuration. A PDF can be structurally correct while looking wrong because the intended font never loaded.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Relative images and fonts fail while CSS itself works

CSS-relative URLs resolve relative to the stylesheet URL, while document-relative URLs resolve relative to the document base. Make both locations deliberate, and use absolute asset URLs when deploying across environments.

You need to diagnose a serialized page

For difficult cases, capture network responses for stylesheets during navigation and log status codes and response URLs. Replacing links with captured CSS text can help isolate serialization problems, but it is an older diagnostic technique rather than a substitute for fixing URL reachability and authentication.

Security: validate template-controlled stylesheet URLs

Handlebars escaping protects HTML text in its intended context; it does not make untrusted data safe in URLs, CSS, JavaScript, or event-handler attributes. Escaping alone does not stop a dangerous javascript: URL in an href.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • 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

If a user or external record can influence a stylesheet URL, allow-list schemes and hosts, reject non-HTTP(S) schemes unless explicitly required, and prevent access to internal address ranges. Prefer selecting a stylesheet by an internal identifier rather than accepting an arbitrary URL. Apply the same policy to image, font, and script URLs, and run the PDF worker with least-privilege network and filesystem access.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Choosing Puppeteer or WeasyPrint

Decision point Puppeteer/Chromium WeasyPrint
HTML and CSS compatibility Browser layout and JavaScript execution Dedicated HTML/CSS-to-PDF engine; JavaScript behavior differs
Resource control Page navigation, style injection, browser request controls URL fetcher configuration, including custom fetching when needed
Print behavior Print media by default; explicit PDF options Print-oriented layout with renderer-specific feature support
Deployment concern Chromium binary, sandboxing, and network policy Python/runtime dependencies, fonts, and fetcher permissions

Choose the engine that matches your document. If the page depends on browser JavaScript and the same layout as Chrome, Puppeteer is usually the more direct fit. If you want a focused HTML/CSS-to-PDF pipeline and can provide deterministic resources, WeasyPrint can be appropriate.

Or skip the browser setup

ScreenshotNeo provides a website capture API and MCP server. It can return PNG, JPEG, WebP, or PDF from one GET request, so you do not have to package Chromium or configure a renderer worker for a publicly reachable HTML page. Its cleanup step accepts cookie/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 the response identifies the page verdict and billing status in X-Page-Verdict and X-Billed headers. An MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients.

For API parameters, see the ScreenshotNeo documentation. The following is the supplied one-call pattern (change only the target URL):

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
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}`);

Every feature is included on every plan. The Free plan provides 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account to try it.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

FAQ

Should CSS be inline for PDF generation?

Not necessarily. A linked stylesheet is reliable when its URL has a resolvable base, the renderer can fetch it, and you wait for it before printing. Inlining can remove a network dependency but makes caching and maintenance harder.

Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 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.

Does page.setContent() automatically make relative links work?

Do not rely on it to provide the origin your application expects. Add a base element or use absolute URLs, then verify the resolved request from the PDF process.

Why does the PDF differ from the browser preview?

PDF generation uses print media by default, and options such as background printing, page size, margins, and font readiness affect the result. Compare the active print rules and PDF options before changing the template.

Frequently Asked Questions

Can I use a local CSS file with Puppeteer?

Yes. Serve it from a reachable local HTTP route or use a correctly resolved file URL, then confirm the Chromium process has permission to read it. An absolute URL and an explicit base are safer across deployments.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Is waiting for network idle always enough?

No. Applications can continue making requests, and fonts or client-side rendering may finish later. Combine a sensible network-idle wait with an application-ready selector and font readiness when those affect layout.

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.