Run wkhtmltopdf from PHP by installing the platform-matched wkhtmltopdf executable and starting it as a separate process. PHP does not provide this renderer as a built-in function or extension. For PHP 7.4 and newer, proc_open() with an argument array lets you launch the binary without passing a command string through a shell, then inspect its error output and exit status.
Understand what PHP is running
wkhtmltopdf is a command-line program. PHP can ask it to convert a local HTML file or a URL into a PDF, but the executable must already be installed and runnable by the same account and environment that runs the PHP code. A Composer wrapper can make the PHP interface more convenient; it does not replace the binary.
The basic flow is: prepare the input, invoke the executable with an output path, wait for it to finish, inspect the result, and only then return or serve the PDF. This separation is useful when diagnosing failures: first determine whether the command works in the deployment environment, then determine whether PHP can launch it there.
Install a build that matches the server
There is no universal Linux package that suits every server. Select a package for the deployment operating system and architecture, and follow the current installation instructions for that target. The wkhtmltopdf project explains that library, OpenSSL, libc, font and runtime differences affect compatibility; a package described as “static” should not be assumed to include every dependency.
#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.
- Identify the runtime target. Check the OS distribution and version, CPU architecture, PHP runtime, and whether PHP runs on a host, in a container, or in a managed job environment.
- Install the matching executable and dependencies. Use the project’s package information for the target rather than copying an install command for a different distribution.
- Find the executable path. Configure PHP with an absolute path, such as a deployment-specific
/usr/bin/wkhtmltopdf, rather than assuming the web worker inherits the interactive shell’sPATH. - Check access as the PHP service account. The account must be able to execute the binary and read the input and any required fonts or assets, and write to the output directory.
- Verify the installed build. Run
wkhtmltopdf -Hunder the same deployment context and consult its help output before relying on a switch.
For AWS Lambda, the project documents an Amazon Linux 2 archive that can be bundled with a function or layer, including an example setting FONTCONFIG_PATH=/opt/fonts. That is a target-specific example, not a universal recipe for every Lambda runtime generation. Likewise, wrapper documentation discusses headless-server considerations and Xvfb workarounds for some dynamically linked builds; verify whether those notes apply to the exact package rather than adding Xvfb automatically.
Prove the conversion from the command line
Start with the simplest local-file conversion:
wkhtmltopdf input.html output.pdf
The CLI synopsis is wkhtmltopdf [GLOBAL OPTION]... [OBJECT]... <output file>. A page object can be a URL or a file. Global and per-page options control such things as paper size, orientation, margins, headers and footers, JavaScript behavior, and page rendering. The exact available switches can depend on the build, including whether it uses patched Qt, so check wkhtmltopdf -H on the installed executable.
Test the chosen input and output paths from the service environment, not only from a developer workstation. If the CLI cannot fetch a URL or read a local file there, adding PHP process code will not fix the underlying access or renderer problem.
Call wkhtmltopdf safely with proc_open()
This PHP 7.4+ example takes a server-controlled input and output path, launches an explicit binary path using the array command form, writes stdout to a sink, records stderr in a temporary file, and checks both the process result and generated file. Supply the input and output paths from trusted application logic; do not accept arbitrary executable paths or wkhtmltopdf flags from a request.
Recommended Free Tools
<?php
$binary = '/usr/bin/wkhtmltopdf'; // Set this for your deployment.
$input = '/srv/app/tmp/report.html'; // Use a server-generated, validated path.
$output = '/srv/app/tmp/report.pdf'; // Use a server-generated destination.
$stderrPath = tempnam(sys_get_temp_dir(), 'wkhtmltopdf-err-');
if ($stderrPath === false) {
throw new RuntimeException('Could not create a temporary error log.');
}
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.
$stderr = fopen($stderrPath, 'wb');
$stdout = fopen('/dev/null', 'wb'); // On Windows, choose an appropriate writable sink.
if ($stderr === false || $stdout === false) {
throw new RuntimeException('Could not open process output streams.');
}
$descriptors = [
0 => ['pipe', 'r'],
1 => $stdout,
2 => $stderr,
];
$command = [$binary, $input, $output];
$process = proc_open($command, $descriptors, $pipes);
if (!is_resource($process)) {
fclose($stderr);
fclose($stdout);
@unlink($stderrPath);
throw new RuntimeException('Could not start wkhtmltopdf.');
}
fclose($pipes[0]); // No stdin is needed for this file-based example.
fclose($stderr);
fclose($stdout);
$exitCode = proc_close($process);
$errorText = file_get_contents($stderrPath);
@unlink($stderrPath);
if ($exitCode !== 0 || !is_file($output) || filesize($output) === 0) {
throw new RuntimeException('PDF conversion failed. Exit code: ' . $exitCode . '; stderr: ' . (string) $errorText);
}
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.
// The PDF is ready at $output. Serve it only after the checks above.
?>
The descriptor numbers follow PHP’s process convention: 0 is stdin, 1 stdout, and 2 stderr. This example avoids reading from two output pipes sequentially, which can block if the child fills one pipe while PHP waits on the other. It writes diagnostics to a temporary file instead. The /dev/null sink is Unix-specific; on Windows, choose a suitable writable sink or adapt the descriptor setup to that environment.
When adding options, place each option and each value in its own array element—for example, ['/usr/bin/wkhtmltopdf', '--orientation', 'Landscape', $input, $output]—and check the installed build’s help for accepted syntax. Validate any variable values against an allowlist. Do not let request data become an arbitrary option, input URL, or output path.
Use a shell-string API only with careful quoting
PHP 7.4+ array-form proc_open() is preferable because it starts the command directly instead of asking a shell to parse a constructed string. If an application must use a shell-string API such as exec(), quote each individual dynamic argument with escapeshellarg(); do not quote the entire command as one argument. PHP documents platform-specific escaping behavior on Windows, including characters that may be lost, and warns that escaping alone does not prevent every command-injection pattern.
Use fixed executable paths, server-generated filenames, and allowlisted options even when arguments are escaped. Quoting reduces shell interpretation risk; it does not validate the meaning or safety of a URL, file, option, or HTML document.
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
Choose direct invocation or a PHP wrapper
| Approach | What it gives you | What remains your responsibility |
|---|---|---|
Direct proc_open() |
Explicit argument construction, descriptor control, stderr capture and exit-status handling. | Installing and locating the binary, managing paths and permissions, and handling platform differences. |
PHP wrapper such as mikehaertl/phpwkhtmltopdf |
A convenience API; its README documents Composer installation, binary-path configuration and error retrieval. | The same external executable must work. Check wrapper compatibility with the project and your PHP/runtime versions, and review its Windows-specific notes where relevant. |
A wrapper is useful if its API fits the application, but it does not eliminate deployment requirements or make untrusted HTML safe. For a small integration that needs precise process behavior, direct invocation keeps the boundary visible.
Do these 3 things before closing this tab:
1Scan for outdated or missing drivers - takes under a minute2Clear out junk files and repair common Windows errors3Fix the driver behind crashes, sound loss and screen glitchesDiagnose failures that occur only in PHP
When a command works in an interactive terminal but not in a web request or worker, compare the two environments rather than assuming the conversion itself is at fault. Capture stderr and the exit status; a missing library or denied file can otherwise surface as a generic PDF failure.
| Symptom | Check | Practical fix |
|---|---|---|
| Executable not found or process will not start | PHP’s PATH, configured binary path, executable permissions, service account and PHP restrictions. |
Set the absolute path to the installed binary and grant the PHP account execute access. Confirm that the binary exists in the deployed container or host. |
| CLI works as a user, but web request fails | Identity, working directory, environment variables, directory permissions and service-specific restrictions. | Reproduce the command under the PHP worker or job-runner account, use absolute input/output paths, and pass only required environment configuration. |
| Process starts but exits unsuccessfully | Captured stderr and exit code; input readability, output writability, option spelling, missing shared libraries or fonts. | Fix the specific reported access, dependency or option problem, then rerun the minimal CLI conversion in the same environment. |
| PDF exists but is empty or incomplete | Whether the process finished successfully, output size, access to linked assets, and the selected build’s rendering behavior. | Do not serve the file on existence alone. Check the exit status and nonzero size, then investigate asset availability and rendering options. |
| Option works on one host but not another | Whether both machines use the same wkhtmltopdf build and Qt packaging. | Compare wkhtmltopdf -H and use only options supported by the deployed build. |
Account for security and renderer age
The wkhtmltopdf project explicitly 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 that as a serious renderer risk. Shell argument arrays protect the process-launch boundary; they do not make hostile HTML or JavaScript safe to render. If the product must render attacker-controlled content, reconsider the renderer and/or put rendering behind strong isolation with tight network and filesystem restrictions.
The project lists version 0.12.6 as its stable series, released June 11, 2020. Its status history says QtWebKit was deprecated in 2015 and removed from Qt in 2016. Those are project-published maintenance facts, not an independent security audit. Because the rendering stack is from the QtWebKit era, do not assume contemporary CSS or JavaScript behavior without validating the output your application requires.
Or skip the browser setup
If the requirement is a website screenshot or a PDF capture of a page rather than a local wkhtmltopdf installation, ScreenshotNeo offers a single-request alternative. For example, this cURL request saves a screenshot of a URL:
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 →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.
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. Cookie banners are accepted and removed before capture, along with supported newsletter popups and chat widgets; bot checks, blank pages, failed loads and cache hits are not billed. Its MCP server lets AI agents use take_screenshot, get_page_info and capture_pdf. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000.
Sign up for ScreenshotNeo’s free plan to try 1,000 screenshots a month with no card.
Frequently asked questions
Can PHP generate a PDF without wkhtmltopdf installed?
Not through a PHP wrapper for wkhtmltopdf: the wrapper still depends on the external executable. If you need to avoid installing a renderer, choose a different PDF approach suited to the application rather than assuming PHP itself includes wkhtmltopdf.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Should I use wkhtmltopdf for HTML supplied by users?
The project warns against rendering untrusted HTML or JavaScript because exploitation can compromise the server. Sanitization alone should not be treated as equivalent to isolation; assess whether a different renderer and restrictive execution environment are required.

