FedoraRHEL Based

How To Install Wkhtmltopdf on Fedora 42

Install Wkhtmltopdf on Fedora 42

Converting HTML documents into professionally formatted PDF files is a common requirement for developers, system administrators, and content creators. Wkhtmltopdf offers a powerful, open-source solution for this task, leveraging the WebKit rendering engine to produce high-quality PDFs directly from your command line. This comprehensive guide walks you through installing wkhtmltopdf on Fedora 42, configuring it properly, and mastering its essential features to streamline your document conversion workflow.

What is Wkhtmltopdf?

Wkhtmltopdf is an open-source command-line utility that converts HTML documents and web pages into PDF files using the WebKit rendering engine—the same technology that powers Safari and Chrome browsers. Unlike basic HTML-to-PDF converters, wkhtmltopdf preserves complex layouts, CSS styling, JavaScript functionality, and multimedia elements with exceptional fidelity.

The tool excels at generating reports, creating documentation, archiving web content, and producing invoices from HTML templates. Its command-line nature makes it ideal for server-side automation and batch processing tasks. Developers appreciate its minimal dependencies and cross-platform compatibility across Linux, Windows, and macOS environments.

Compared to alternatives like Puppeteer, WeasyPrint, or PDFKit, wkhtmltopdf stands out for its lightweight footprint and straightforward implementation. It doesn’t require a full browser installation or complex Node.js dependencies. The rendering quality rivals browser-based solutions while maintaining efficient resource utilization, making it suitable for both desktop workstations and resource-constrained server environments.

Key features include support for custom headers and footers, automatic table of contents generation, batch conversion of multiple files, granular control over image quality, and flexible page sizing options. The tool handles responsive designs, web fonts, and modern CSS3 properties with remarkable accuracy.

System Requirements for Fedora 42

Before installing wkhtmltopdf on your Fedora 42 system, verify that your environment meets the necessary specifications. The software requires a 64-bit x86_64 architecture running Fedora 42. Hardware recommendations include a minimum of 2GB RAM, though 4GB or more is preferable for processing complex documents or handling batch conversions.

Allocate at least 100MB of free disk space for the application binaries and dependencies. A 64-bit processor is mandatory, as 32-bit versions are no longer supported in recent releases. Ensure you have an active internet connection for repository-based installations and root or sudo privileges to execute system-level commands.

The current stable version available in Fedora 42 repositories is wkhtmltopdf 0.12.6-6.fc42. Performance varies based on document complexity—simple HTML pages convert in seconds, while JavaScript-heavy applications or high-resolution images may require longer processing times. Server installations without graphical interfaces require additional X11 libraries to function properly, while desktop environments typically include these dependencies by default.

Prerequisites and Dependencies

Wkhtmltopdf relies on several system libraries to render HTML content accurately. The most critical dependencies include X11 font packages such as xorg-x11-fonts-75dpi and xorg-x11-fonts-Type1, which ensure proper font rendering across different document types. Image processing libraries like libpng and libjpeg handle graphics embedded in HTML documents.

SSL libraries (openssl) enable secure connections when fetching resources from HTTPS URLs. Qt dependencies provide the WebKit rendering framework, while display server components (libX11, libXext, libXrender) facilitate the rendering process even on headless servers.

Before proceeding with installation, check for existing wkhtmltopdf installations to avoid conflicts. Run wkhtmltopdf --version in your terminal—if the command returns version information, an installation already exists. Remove outdated versions using sudo dnf remove wkhtmltopdf to ensure a clean installation.

Update your system packages before installing new software: sudo dnf update -y. This command refreshes repository metadata and upgrades existing packages to their latest versions, reducing potential compatibility issues.

Font configuration significantly impacts output quality, especially when working with non-Latin character sets like Chinese, Japanese, Arabic, or Cyrillic scripts. Fedora 42 includes comprehensive font support by default, but specialized projects may require additional font packages.

Method 1: Installation via DNF Package Manager (Recommended)

The simplest and most maintainable approach involves using Fedora’s native DNF package manager. This method automatically resolves dependencies, integrates seamlessly with system updates, and provides security patches through official channels.

Begin by updating your system repositories to ensure you’re accessing the latest package metadata:

sudo dnf update -y

Install wkhtmltopdf with a single command:

sudo dnf install wkhtmltopdf -y

The -y flag automatically confirms the installation without prompting for user input. DNF downloads the package and all required dependencies, typically completing within 1-3 minutes depending on your internet connection speed.

Verify the installation by checking the installed version:

wkhtmltopdf --version

The output should display version information similar to: wkhtmltopdf 0.12.6 (with patched qt). This confirms that wkhtmltopdf is correctly installed and ready to use.

Check the binary location with:

which wkhtmltopdf

This command returns /usr/bin/wkhtmltopdf, indicating the executable’s path on your system.

The DNF installation method offers several advantages. Dependencies are automatically managed—you don’t need to manually track library requirements. System updates include wkhtmltopdf patches, ensuring your installation remains current without manual intervention. Package authenticity is verified through GPG signatures, protecting against compromised downloads. Removal and maintenance are straightforward through standard package management commands.

However, repository versions sometimes lag behind upstream releases. If you require bleeding-edge features or specific version compatibility for an application, consider the manual RPM installation method described next.

Method 2: Installation from Official RPM Package

For users requiring specific versions or the latest upstream release, installing from official RPM packages provides greater control. This approach is particularly useful when developing applications with version-specific dependencies or testing new features before they reach stable repositories.

Navigate to the official wkhtmltopdf GitHub releases page or download repository. Identify the appropriate RPM package for Fedora 42 on x86_64 architecture. Package names typically follow the format wkhtmltox-0.12.6-1.fc42.x86_64.rpm.

Download the package using wget:

wget https://github.com/wkhtmltopdf/packaging/releases/download/0.12.6-1/wkhtmltox-0.12.6-1.fc42.x86_64.rpm

Verify package integrity by comparing the downloaded file’s checksum against the published SHA256 hash on the releases page:

sha256sum wkhtmltox-0.12.6-1.fc42.x86_64.rpm

Install the RPM package with DNF, which handles dependency resolution automatically:

sudo dnf install ./wkhtmltox-0.12.6-1.fc42.x86_64.rpm -y

Using dnf install instead of rpm -i ensures proper dependency handling. If conflicts arise with existing packages, DNF displays detailed error messages. The --allowerasing flag removes conflicting packages when necessary:

sudo dnf install ./wkhtmltox-0.12.6-1.fc42.x86_64.rpm --allowerasing -y

The installation places binaries in /usr/bin/ and shared libraries in /usr/lib64/. Both wkhtmltopdf (HTML to PDF) and wkhtmltoimage (HTML to image) executables are included.

Manual RPM installation grants access to specific versions for compatibility testing, control over update timing, and immediate access to new features. The primary drawback involves manual update management—you’re responsible for monitoring new releases and applying updates yourself. Security patches won’t arrive automatically through system updates, requiring vigilance to maintain a secure installation.

Post-Installation Verification

After installing wkhtmltopdf through either method, perform comprehensive verification to ensure proper functionality. Start by confirming the binary location:

which wkhtmltopdf

Expected output: /usr/bin/wkhtmltopdf

Check the installed version:

wkhtmltopdf --version

Look for version information and the important notation (with patched qt), which indicates the build includes necessary Qt patches for optimal rendering.

Create a simple HTML test file to verify conversion capabilities:

echo "<html><body><h1>Test Document</h1><p>This is a test conversion.</p></body></html>" > test.html

Convert the HTML file to PDF:

wkhtmltopdf test.html test-output.pdf

The command should complete without errors, displaying progress information including page loading status and output file creation. Examine the generated PDF to verify proper rendering:

xdg-open test-output.pdf

Test URL conversion functionality by converting a live web page:

wkhtmltopdf https://www.example.com example.pdf

Successful completion of these tests confirms that wkhtmltopdf is properly installed with all dependencies loaded correctly. Font rendering, network connectivity, and file system permissions are all functioning as expected.

Basic Usage Examples

Wkhtmltopdf’s command-line interface provides intuitive syntax for common conversion tasks. The basic format follows: wkhtmltopdf [options] <input> <output>.

Convert a local HTML file to PDF:

wkhtmltopdf document.html document.pdf

Convert a web page directly from its URL:

wkhtmltopdf https://www.wikipedia.org wikipedia.pdf

Specify custom page size using the --page-size option:

wkhtmltopdf --page-size A4 input.html output.pdf

Available page sizes include A4, Letter, Legal, A3, A5, and custom dimensions. Set landscape orientation with --orientation:

wkhtmltopdf --orientation Landscape webpage.html landscape.pdf

Configure margins to control spacing around page edges:

wkhtmltopdf --margin-top 20mm --margin-bottom 20mm --margin-left 15mm --margin-right 15mm document.html output.pdf

Add custom headers displaying document titles or dates:

wkhtmltopdf --header-center "Document Title" --header-font-size 10 input.html output.pdf

Include page numbers in footers:

wkhtmltopdf --footer-center "Page [page] of [topage]" --footer-font-size 8 document.html numbered.pdf

The [page] and [topage] variables are automatically replaced with current and total page numbers. Additional variables include [date], [time], [title], and [webpage].

Combine multiple HTML files into a single PDF document:

wkhtmltopdf cover.html chapter1.html chapter2.html complete-book.pdf

Add a cover page with the cover option:

wkhtmltopdf cover cover.html page1.html page2.html final-document.pdf

Generate a table of contents with the toc option:

wkhtmltopdf toc --toc-header-text "Table of Contents" page1.html page2.html booklet.pdf

Advanced Configuration and Options

Mastering advanced options unlocks wkhtmltopdf’s full potential for professional document production. Control image quality with the --image-quality parameter, which accepts values from 0 to 100:

wkhtmltopdf --image-quality 95 high-quality.html output.pdf

Higher values produce larger files with better visual fidelity. Balance file size against quality requirements for your specific use case.

Adjust DPI (dots per inch) for screen versus print output:

wkhtmltopdf --dpi 300 print-ready.html professional-output.pdf

Standard screen resolution is 96 DPI, while professional printing requires 300 DPI or higher.

Enable background printing to include background colors and images:

wkhtmltopdf --background document.html styled-output.pdf

Without this flag, backgrounds are omitted to reduce ink usage in printed documents.

Control JavaScript execution timing for dynamic content:

wkhtmltopdf --javascript-delay 2000 dynamic-page.html output.pdf

The delay value (in milliseconds) allows JavaScript to execute and render dynamic content before PDF generation begins. Pages with AJAX requests or animated elements benefit from appropriate delay values.

Load external stylesheets with the --user-style-sheet option:

wkhtmltopdf --user-style-sheet custom-print.css webpage.html styled.pdf

Disable JavaScript entirely for security or performance:

wkhtmltopdf --disable-javascript simple-page.html output.pdf

Configure custom HTTP headers for authenticated requests:

wkhtmltopdf --custom-header "Authorization" "Bearer your-token-here" protected-page.html output.pdf

Set zoom factor to scale content:

wkhtmltopdf --zoom 1.5 small-text.html enlarged.pdf

Enable local file access for loading resources from the file system:

wkhtmltopdf --enable-local-file-access page-with-images.html output.pdf

Specify cache directory for improved performance with repeated conversions:

wkhtmltopdf --cache-dir /tmp/wkhtmltopdf-cache document.html output.pdf

Troubleshooting Common Issues

Even with proper installation, you may encounter issues during operation. Understanding common problems and their solutions ensures smooth workflow.

Dependency conflicts during installation manifest as error messages about package requirements. Resolve these by updating your system first (sudo dnf update -y) or using the --allowerasing flag to remove conflicting packages.

GPG key verification errors occur when repository signatures fail validation. Import missing keys manually or temporarily skip verification with --nogpgcheck (use cautiously).

“Failed loading page” errors typically indicate network connectivity issues, invalid URLs, or SSL certificate problems. Test network access with curl or wget. For self-signed certificates, use --disable-ssl-verification:

wkhtmltopdf --disable-ssl-verification https://self-signed-site.com output.pdf

File path and permission issues prevent wkhtmltopdf from reading input files or writing output. Verify file permissions with ls -l and ensure the user executing wkhtmltopdf has appropriate read/write access. Avoid spaces in filenames or wrap paths in quotes:

wkhtmltopdf "file with spaces.html" "output document.pdf"

Font rendering problems appear as missing characters or incorrect fonts in output PDFs. Install additional font packages:

sudo dnf install liberation-fonts dejavu-fonts google-noto-fonts -y

Missing images or CSS in output PDFs suggest resource loading failures. Check that external resources are accessible, use absolute URLs instead of relative paths, or enable local file access with --enable-local-file-access.

JavaScript execution failures cause dynamic content to render incorrectly. Increase --javascript-delay values or check browser console errors by testing the HTML file in a standard web browser first.

Display server issues on headless servers produce errors like “cannot connect to X server.” Install and configure Xvfb (X virtual framebuffer):

sudo dnf install xorg-x11-server-Xvfb -y
xvfb-run wkhtmltopdf document.html output.pdf

Network errors (UnknownNetworkError, ContentNotFoundError) indicate connection timeouts or unreachable resources. Verify URL accessibility and increase timeout values:

wkhtmltopdf --load-error-handling ignore --load-media-error-handling ignore problematic-page.html output.pdf

Integration with Programming Languages

Wkhtmltopdf integrates seamlessly with popular programming languages for automated PDF generation in web applications and scripts.

PHP Integration

PHP uses wrapper libraries like Snappy or php-wkhtmltopdf. Install Snappy via Composer:

composer require knplabs/knp-snappy

Basic PHP implementation:

<?php
require 'vendor/autoload.php';
use Knp\Snappy\Pdf;

$snappy = new Pdf('/usr/bin/wkhtmltopdf');
$snappy->generateFromHtml('<h1>Hello World</h1>', '/path/to/output.pdf');

Python Integration

Python leverages the pdfkit library. Install with pip:

pip install pdfkit

Python usage example:

import pdfkit

pdfkit.from_file('input.html', 'output.pdf')
pdfkit.from_url('https://example.com', 'page.pdf')
pdfkit.from_string('<h1>Hello</h1>', 'string.pdf')

Configure the wkhtmltopdf binary path explicitly:

config = pdfkit.configuration(wkhtmltopdf='/usr/bin/wkhtmltopdf')
pdfkit.from_file('input.html', 'output.pdf', configuration=config)

Other Language Bindings

Ruby integration uses the wkhtmltopdf-binary gem and PDFKit:

gem install pdfkit wkhtmltopdf-binary

Node.js wrappers include html-pdf and wkhtmltopdf-wrapper packages available through npm.

Specify the binary path consistently across different platforms to ensure portability between development and production environments.

Performance Tips and Best Practices

Optimize conversion performance and output quality by following established best practices. Structure HTML documents with PDF output in mind—avoid overly complex JavaScript animations that increase processing time without improving print quality.

Use local CSS files instead of external stylesheets to reduce network latency. Optimize images before embedding them in HTML by compressing file sizes and choosing appropriate formats (JPEG for photographs, PNG for graphics with transparency).

Minimize external resource dependencies to reduce conversion time and potential failure points. Download remote assets locally when possible, or use data URIs for small images embedded directly in HTML.

Implement caching strategies for repeated conversions of similar documents. Store rendered PDFs and regenerate only when source content changes.

Monitor conversion times during development to identify performance bottlenecks. Complex pages with hundreds of elements or high-resolution images naturally require longer processing.

Set resource limits for server environments to prevent runaway processes from consuming excessive memory:

ulimit -v 2000000  # Limit virtual memory to 2GB
wkhtmltopdf large-document.html output.pdf

Use batch processing techniques to convert multiple documents efficiently. Process files in parallel on multi-core systems, but limit concurrent conversions to prevent memory exhaustion.

Implement proper error handling and logging in automated systems. Capture stderr output to diagnose failures in production environments where direct debugging isn’t feasible.

Upgrading Wkhtmltopdf

Keep wkhtmltopdf current to benefit from bug fixes, security patches, and new features. For DNF-managed installations, check for available updates:

sudo dnf check-update wkhtmltopdf

If updates are available, upgrade with:

sudo dnf upgrade wkhtmltopdf -y

Manually installed RPM versions require downloading new packages and reinstalling. Before upgrading major versions, test thoroughly in a development environment, as rendering behavior may change.

Back up critical conversion scripts and sample outputs before upgrading. Compare new version outputs against reference PDFs to verify consistent rendering.

Roll back problematic upgrades by downgrading to previous versions:

sudo dnf downgrade wkhtmltopdf

Document your installed version in project dependencies to maintain consistency across team members and deployment environments.

Uninstalling Wkhtmltopdf

Remove wkhtmltopdf completely when it’s no longer needed. For DNF installations:

sudo dnf remove wkhtmltopdf -y

Remove automatically installed dependencies that are no longer required:

sudo dnf autoremove -y

For manually installed RPM packages, use rpm command:

sudo rpm -e wkhtmltox

Verify complete removal by checking for remaining files:

find / -name "*wkhtmltopdf*" 2>/dev/null

Delete any leftover configuration files or cache directories manually if found. Clean package cache to free disk space:

sudo dnf clean all

Security Considerations

Implementing wkhtmltopdf securely protects your systems from potential vulnerabilities. Keep the software updated with the latest security patches through regular system updates. DNF-managed installations receive patches automatically, while manual installations require monitoring release announcements.

Validate and sanitize user-supplied HTML input before conversion to prevent injection attacks. Never pass untrusted content directly to wkhtmltopdf without filtering potentially malicious scripts or file system access attempts.

Run wkhtmltopdf with minimal privileges using dedicated service accounts rather than root. Configure file system access restrictions to limit which directories the process can read or write.

Consider sandboxing conversion processes in containerized environments like Docker to isolate potential security breaches. Restrict network access when converting local files to prevent data exfiltration through external requests.

Enable SSL/TLS certificate validation when converting HTTPS URLs to prevent man-in-the-middle attacks. Only disable certificate verification for trusted internal resources.

Implement proper firewall rules for servers that convert external URLs, allowing only necessary outbound connections. Monitor conversion logs for suspicious activity or repeated failures that might indicate attack attempts.

Protect generated PDFs with appropriate file permissions and encryption when they contain sensitive information. Consider implementing access controls and audit trails for document generation in enterprise environments.

VPS Manage Service Offer
If you don’t have time to do all of this stuff, or if this is not your area of expertise, we offer a service to do “VPS Manage Service Offer”, starting from $10 (Paypal payment). Please contact us to get the best deal!

r00t

r00t is an experienced Linux enthusiast and technical writer with a passion for open-source software. With years of hands-on experience in various Linux distributions, r00t has developed a deep understanding of the Linux ecosystem and its powerful tools. He holds certifications in SCE and has contributed to several open-source projects. r00t is dedicated to sharing her knowledge and expertise through well-researched and informative articles, helping others navigate the world of Linux with confidence.
Back to top button