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

For an existing HTML/CSS template, render the template with your data, load the finished HTML in Puppeteer, wait until the content and assets you need are ready, and save it with page.pdf(). Chromium handles the browser layout and print operation, so this approach is a natural fit for invoices, reports, certificates, and other documents whose design already lives in HTML and CSS. If you need to draw a PDF directly from code rather than render a template, PDFKit may be a better fit.

Why Puppeteer is the best fit for an HTML template

Puppeteer controls Chromium from Node.js. That gives an HTML template a browser’s CSS layout, font handling, and print behavior, rather than requiring you to rebuild the design from lower-level PDF drawing commands. The core sequence is simple: compile the template with its data, load the resulting HTML in a page, then call page.pdf() to produce the file.

This is especially useful when a document has branded styling, tables, web fonts, or page-specific CSS. The output is still a printed document, however—not an exact copy of the browser viewport. Puppeteer uses print CSS media by default, so styles under @media print apply unless you deliberately emulate screen media.

Install Puppeteer and generate a PDF

Install Puppeteer in your Node.js project:

npm install puppeteer

Use an HTML string that has already been rendered from your template. This complete ES module example loads that HTML, waits for network activity to settle, and writes an A4 PDF:

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 puppeteer from 'puppeteer';

const renderedHtml = `
  <!doctype html>
  <html>
    <head>
      <meta charset="utf-8">
      <style>
        body { font: 12pt Arial, sans-serif; }
        h1 { color: #18324b; }
        @media print {
          .screen-only { display: none; }
          * { -webkit-print-color-adjust: exact; }
        }
      </style>
    </head>
    <body>
      <h1>Invoice</h1>
      <p>Invoice number: INV-1042</p>
    </body>
  </html>
`;

const browser = await puppeteer.launch();
try {
  const page = await browser.newPage();
  await page.setContent(renderedHtml, { waitUntil: 'networkidle0' });
  await page.pdf({
    path: 'output.pdf',
    format: 'A4',
    printBackground: true,
    margin: { top: '20mm', right: '15mm', bottom: '20mm', left: '15mm' }
  });
} finally {
  await browser.close();
}

The try/finally closes Chromium even if loading or PDF generation throws an error. In a template-driven application, replace the sample string with the HTML produced by your template engine. The example’s networkidle0 wait is useful when the page loads resources over the network, but it is not a universal guarantee that every chart, image, or client-side component is ready; add an application-specific readiness check where needed.

Render template data safely

Compile the template before passing it to page.setContent(). Template engines such as Handlebars or EJS can render document data into HTML; Puppeteer does not require a particular template engine. Keep ordinary user-controlled values escaped using the engine’s normal escaping behavior. Do not interpolate untrusted strings as raw HTML unless they have been deliberately sanitized: otherwise, content intended as text can become executable markup or script.

For predictable output, treat the rendered HTML as an input artifact. Check that required fields exist, use stable formatting for dates and currency, and ensure the template has the document’s intended page structure before launching Chromium. This separates template/data defects from browser and PDF-generation failures.

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.

Choose print styling, page size, and color behavior

page.pdf() prints with print media by default. That is usually what you want for a document: it allows print-specific rules to hide navigation, adjust widths, or control page breaks. If the template is deliberately designed only for screen presentation, call await page.emulateMediaType('screen') before generating the PDF. Doing so changes which media rules apply; it does not otherwise make the PDF a screenshot of the current viewport.

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.

Specify a paper format such as A4 when the document needs a known page size. Set margins in the page.pdf() options to reserve space around content. Use printBackground: true when background fills or images are part of the design. For color-sensitive print output, add -webkit-print-color-adjust: exact in print CSS. Check representative documents after changing any of these settings: margins, paper size, and print styles can affect line wrapping and pagination.

Wait for fonts, images, and client-side content

Puppeteer’s PDF generation waits for fonts by default, but that alone does not establish that every asset or asynchronous component is ready. Images, remote stylesheets, charts, data-driven widgets, and client-side rendering may need their own readiness strategy. The waitUntil: 'networkidle0' option in the example waits for network activity to settle during setContent(); applications with long-lived requests or delayed rendering should use an explicit signal from the page instead of assuming network quiet means the document is finished.

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.

For a chart or application component, expose a page-level condition that becomes true only after it has rendered, then wait for that condition before calling page.pdf(). For images, verify that the intended sources loaded and have dimensions. For remote fonts, make sure the font files are accessible to Chromium in the deployment environment. Missing or late assets can produce a valid PDF that nevertheless looks incomplete.

Decide between Puppeteer, PDFKit, and a wrapper

Approach Best fit Main trade-off
Puppeteer with HTML/CSS Invoices, reports, certificates, branded layouts, and repeated page styling Requires Chromium and browser-process operations
PDFKit Code-defined drawings, text, and stream output when browser layout is unnecessary Layout and pagination must be expressed in PDF primitives
pdf-creator-node Teams seeking a Handlebars-to-HTML wrapper around PDF generation Still inherits Puppeteer’s browser cost; its documentation requires Node.js 18 or newer

PDFKit is not a shortcut for converting an HTML template: it is appropriate when you want to define the page’s text and graphics directly in code. Its documented workflow uses PDFDocument and stream output. A wrapper such as pdf-creator-node can reduce integration glue for a Handlebars template, but it still passes through Puppeteer, so it does not remove Chromium’s deployment or startup requirements.

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

Make generation reliable in production

Reuse Chromium when throughput matters

Launching a new browser for every document adds avoidable browser-process work. For a service that generates multiple PDFs, reuse a browser process and create and close a page for each job. Keep page lifecycle management explicit so failed jobs do not leave pages open. The right concurrency limit depends on your workload and available resources; there is no benchmark figure established here that applies to every deployment.

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

Pin and prepare the browser runtime

Pin the Puppeteer version used by the application and deploy its compatible Chromium runtime consistently. In continuous integration, cache the browser binary when practical so builds do not repeatedly download it. Verify that the runtime used in production can access required local and remote assets; a template that works on a developer’s machine may render differently if fonts, network access, or browser versions differ.

Review page breaks using real data

Test representative short and long records, including tables that span pages and text fields near the maximum lengths your application accepts. Confirm the page count, margins, repeated headers or footers if your design uses them, and that important content is not clipped. Browser print layout can paginate content differently as data length, font availability, or CSS changes.

Isolate untrusted documents

If users can supply HTML or templates can load external URLs, treat rendering as a security boundary. Isolate untrusted HTML and restrict its network access to what the job genuinely needs. Otherwise, a document can trigger requests to unintended hosts or load uncontrolled content while Chromium renders it. Keep the data passed into templates escaped and avoid giving untrusted page code access to application secrets.

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

Troubleshoot common PDF problems

  • The PDF is blank or content is missing: confirm the template rendered the expected HTML before calling Puppeteer. If content appears only after client-side code runs, wait for an application-level ready condition rather than relying only on initial page setup.
  • Images or charts are absent: check that resource URLs are reachable from the Chromium process and wait for the relevant image or chart readiness condition. Network quiet is not proof that every visual asset rendered.
  • The font is wrong or text wraps differently: confirm the intended font files are available to the browser in the target environment, and wait for font loading before capture. Compare output under the same pinned browser runtime used in deployment.
  • Backgrounds or colors disappear: enable printBackground: true and use -webkit-print-color-adjust: exact in print CSS when exact color fidelity matters. Also check whether the styles are defined for print media.
  • The PDF uses unexpected styles: remember that print media is the default. Remove or revise conflicting @media print rules, or explicitly emulate screen media before generating the PDF if the design calls for screen styling.
  • Content is clipped or page breaks look wrong: inspect paper format, margins, and print CSS with representative long data. Adjust the document layout and rerun the same cases rather than relying on a short sample.
  • Generation is slow or the service uses too many browser processes: avoid launching Chromium for every job when throughput matters. Reuse a browser process, close pages after each job, and limit concurrent work to what the deployment can support.
  • It works locally but fails in deployment: verify the deployed Chromium/Puppeteer pairing, browser binary availability, font files, and permitted network access. Cache the browser binary in CI and pin versions to reduce environment drift.

Or skip the browser setup

If your input is a public web page rather than a local HTML template, ScreenshotNeo can capture the page as an image or PDF through its screenshot API. A single request looks like this for an image capture:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo API documentation for request options, including PDF output. It is not a replacement for compiling a local template: use Puppeteer when your Node.js code must render that template and control the document layout.

  • Cookie banners are accepted and 60+ known consent platforms, newsletter popups, and chat widgets are removed before capture; each step can be turned off.
  • Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed; response headers indicate the page verdict and billing status.
  • An MCP server provides take_screenshot, get_page_info, and capture_pdf tools for AI agents and MCP clients.
  • The free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots.

Sign up for ScreenshotNeo’s free plan: 1,000 screenshots a month, no card required.

Conclusion

For a Node.js PDF generated from an HTML/CSS template, use Puppeteer’s page.pdf(): compile the template first, wait for the assets and client-side content your document needs, and verify print styling and page breaks with representative data. Choose PDFKit for documents composed directly from drawing and text primitives. For a web page that already exists at a URL, ScreenshotNeo offers a separate API-based capture route rather than a local-template renderer.

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

Frequently Asked Questions

Can I use EJS or Handlebars with Puppeteer?

Yes. Render the data into HTML with the template engine first, then give the rendered HTML to Puppeteer. Keep ordinary user-controlled values escaped.

Does PDFKit render HTML and CSS templates?

PDFKit is suited to composing PDF content from code-defined text and graphics, not rendering an HTML/CSS template through a browser.

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.