October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk7 min

How to Call wkhtmltopdf from Node.js

Use Node’s asynchronous child-process APIs to run the separately installed wkhtmltopdf binary, handle failures, and secure the renderer in production.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To call wkhtmltopdf from Node.js, install the wkhtmltopdf command-line executable separately, then run it asynchronously with node:child_process. The npm package named wkhtmltopdf is a wrapper; it does not bundle the renderer. For a server application, pass arguments as an array, handle process errors and exit status, and avoid shell execution with untrusted input.

What you need before calling wkhtmltopdf

The converter is an external program, not a Node library. Install a binary that matches the operating system and architecture where your application runs, and make sure the Node process can execute it. If you prefer the npm wrapper, install that as well; the wrapper still needs the binary.

  1. Install wkhtmltopdf for the deployment environment. The project download page lists 0.12.6 as its stable series, released June 11, 2020; its download matrix is specific to that release and does not guarantee compatibility with every current OS or runtime. Official downloads.
  2. Check that the binary is available to the application process, for example by running wkhtmltopdf --version in the same container or host environment.
  3. Test with the actual fonts, templates, permissions, asset paths, and binary you intend to deploy.

The npm page describes wrapper version 0.4.0 and is old; the reviewed materials do not establish a current compatibility promise for modern Node.js versions. Verify the wrapper and binary together in your environment. npm package documentation.

Run the executable directly with Node.js

For a URL-to-PDF conversion, execFile launches the named executable with an argument array and does not invoke a shell by default. This keeps command construction separate from data and avoids shell interpretation of URL text.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import { execFile } from 'node:child_process';

execFile(
  'wkhtmltopdf',
  ['--quiet', 'https://example.test/report', '/tmp/report.pdf'],
  { timeout: 30_000 },
  (error, stdout, stderr) => {
    if (error) {
      // Log a safe diagnostic; do not expose sensitive input or output to users.
      console.error('wkhtmltopdf failed:', error.message, stderr);
      return;
    }
    console.log('PDF written to /tmp/report.pdf');
  }
);

This example writes to a fixed path and illustrates the invocation pattern; choose a unique, controlled output path and adapt the timeout and error handling to your workload. Node’s child-process documentation describes execFile, its options, and errors. Node.js child_process.

Set an explicit executable path when needed

If the binary is installed outside the application’s PATH, pass its full path as the first argument to execFile, such as /usr/local/bin/wkhtmltopdf. If you supply a replacement env object, preserve PATH when the command still relies on path lookup; Node resolves commands using the environment provided to the child process.

Handle failures and cancellation

Check the callback’s error; a nonzero exit status is reported as a process error, while stderr often contains converter diagnostics. Also handle process startup errors, including missing executables and permission failures. Set a timeout suitable for expected page complexity, and define what the application should do when it expires: terminate the child, remove partial output, and report a failure rather than serving an incomplete PDF.

Do not use synchronous child-process methods in a server request path: they block Node’s event loop. For large output or HTTP delivery, use an asynchronous stream-oriented design and propagate child-process failure so a partial PDF is not mistaken for a successful document. The wrapper’s README demonstrates piping output to a writable stream. Wrapper usage examples.

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

Use the npm wrapper when its API suits your application

The wrapper can accept a URL, an HTML string, or a readable stream as input, and its output can be piped to a writable stream or written to a file. It also accepts wkhtmltopdf options and an optional callback. The executable remains a separate prerequisite.

const wkhtmltopdf = require('wkhtmltopdf');
const fs = require('node:fs');

// If PATH cannot locate the separately installed binary:
wkhtmltopdf.command = '/usr/local/bin/wkhtmltopdf';

wkhtmltopdf('https://example.test/report', { pageSize: 'letter' })
  .pipe(fs.createWriteStream('/tmp/report.pdf'));

Consult the package README for the wrapper’s supported option names and input/output patterns, then verify the resulting command against the binary installed in production. wkhtmltopdf npm README.

Control rendering, assets, and page layout

The command-line manual documents options that can materially change the output. They are renderer controls, not a guarantee that a modern web application will render like a current browser.

  • JavaScript: JavaScript is enabled by default, and the documented default delay is 200 ms. You can disable JavaScript or change the delay. A fixed delay does not establish that a dynamic page has finished rendering.
  • Network and load errors: load-error behavior can be configured to abort, ignore, or skip; media-load errors have separate handling.
  • Images and styles: images can be disabled, and print or screen media styles can be selected. For layout mismatches, check the selected media stylesheet, fonts, paper size, margins, and whether CSS and other resources are reachable.
  • Local files: local-file access for a local input page reading other local files is disabled by default in the documented behavior. The --allow option can grant specific paths. Limit access to the directories the document actually needs, and verify the behavior of the exact packaged binary.

See the wkhtmltopdf usage manual for the command’s documented flags. The project suggests considering Puppeteer for sites that depend on dynamic JavaScript; this is a project recommendation, not a comparative benchmark. Project status and recommendations.

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

Protect the server from untrusted HTML

The wkhtmltopdf project warns: “Do not use wkhtmltopdf with any untrusted HTML – be sure to sanitize any user-supplied HTML/JS, otherwise it can lead to complete takeover of the server it is running on!” Treat conversion as execution of complex, potentially hostile content, not as a harmless formatting step. Project warning.

  • Prefer controlled templates and application data; do not treat HTML escaping alone as a complete sandbox.
  • Run the converter with minimal privileges and restrict its filesystem and network access through deployment controls appropriate to your environment.
  • Do not place user-controlled command fragments in a shell command. Node warns that shell-enabled execution with unsanitized input can allow arbitrary command execution; argument arrays with execFile avoid a shell by default.
  • Keep any --allow paths narrow. A template that loads CSS, images, or fonts from disk may need explicit access, but broad local-file permission increases exposure.
  • Consider mandatory access controls such as AppArmor or SELinux where available; the project status page recommends these types of controls.

Troubleshoot common Node.js and PDF failures

Symptom Likely cause What to check or change
ENOENT or “command not found” The binary is not installed, is outside the child process’s PATH, or the configured path is wrong. Install the executable in the target image, test it as the application user, or pass its full path. Preserve PATH if you override the child environment. Node child-process path behavior.
Permission denied The executable or a required directory is not executable or accessible to the service account. Check file and directory permissions, ownership, container restrictions, and the identity used by Node. Grant only the access required.
Nonzero exit code or missing PDF The converter failed, an input resource could not load, or output could not be written. Record the exit status and safe portions of stderr; check URL reachability, write permissions, disk space, and the command’s load-error policy. Do not return a partial file as success.
Missing local CSS, images, or fonts Local-file access is restricted, a path is incorrect, or the service user cannot read the asset. Use accessible paths and explicitly allow only required directories with the documented local-file controls. Test under the production account.
Dynamic content is absent or incomplete The page has not finished rendering when conversion proceeds; the documented default JavaScript delay is 200 ms. Test whether the content depends on JavaScript, adjust the delay if appropriate, and consider a renderer intended for dynamic JavaScript sites. A longer fixed delay is not a reliable completion signal.
Layout differs from the browser Different fonts, print-versus-screen CSS, unsupported layout behavior, paper dimensions, margins, or resource failures. Check the exact binary and fonts in production, choose the intended media style and page settings, and inspect whether required assets loaded.
Conversion hangs or exceeds request time A slow page, blocked resource, or expensive rendering task outlasts the request budget. Set a timeout and cancellation policy, isolate conversion from latency-sensitive event-loop work, and decide whether a failed job should be retried or reported. Avoid unlimited concurrent child processes.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Check maintenance and alternatives before adopting it

The project’s downloads page lists 0.12.6, released June 11, 2020, as the stable series. Its status page says Qt 4 has been unsupported since 2015 and the WebKit version in it had not been updated since 2012. Those dates make it important to verify security posture, platform support, and output fidelity for your own workload; conditional future plans on the status page should not be read as a shipped release. wkhtmltopdf status.

The project names WeasyPrint or commercial Prince for reports generated from HTML under your control, and Puppeteer for sites that use dynamic JavaScript. These are suggestions from the project, not comparative test results. Compare rendering fidelity on your templates, JavaScript completion behavior, security maintenance and isolation, native dependencies and fonts, current platform support, streaming behavior, and licensing or commercial terms before switching.

Or skip the browser setup

If your goal is a screenshot rather than a PDF, ScreenshotNeo is a website screenshot API and MCP server. One GET request returns a PNG, JPEG, WebP, or PDF. Its clean-capture steps can accept cookie or consent banners and remove more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be turned off. Only clean shots are billed: bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and responses include X-Page-Verdict and X-Billed headers.

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.
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. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000. Sign up for 1,000 free screenshots a month, with no card required.

Frequently Asked Questions

Does installing the npm package install wkhtmltopdf itself?

No. The npm package is a wrapper; the executable must be installed separately.

Can wkhtmltopdf reliably render every modern JavaScript application?

No such compatibility is established; its documented delay is not proof that dynamic rendering has completed.

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.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

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

More from the Wire

  1. Shenzhen desk3 min
    HONOR Expands Beyond Smartphones With Humanoid Robot RevealHONOR said it unveiled its first humanoid robot at MWC 2026 and named shopping assistance, workplace inspections, and supportive companionship as intended uses. Later Robotics D1 claims and a reported…
  2. Cupertino desk5 min
    Apple Unveils AirPods Max 2: The Upgrade That Should Have Happened Years AgoAirPods Max 2 adds H2-powered audio features and Apple claims up to 1.5× more effective ANC, but its design, Smart Case, and 20-hour battery rating are unchanged. Wired lossless audio…
  3. Cupertino desk4 min
    Apple’s OLED Touch MacBooks Are Coming—but the Dynamic Island Is the Real GambleApple has not announced an OLED touchscreen MacBook, but reports point to high-end models arriving in late 2026 or early 2027. The reported Mac Dynamic Island could be useful, but…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.