Cache Assets When Generating PDFs with wkhtmltopdf
In this article
Efficiently generating large batches of PDFs with wkhtmltopdf can strain server resources and slow down processing, especially when assets like CSS, JavaScript, and images are repeatedly fetched for each document. Caching these assets—especially locally stored ones—reduces I/O overhead, speeds up rendering, and improves reliability during batch processing. By preloading or reusing static assets, wkhtmltopdf renders documents faster and more consistently, particularly when generating hundreds or thousands of PDFs from HTML templates.
What You'll Need
- A working installation of wkhtmltopdf (version 0.12.6 or later recommended)
- Access to the server or environment where PDFs are being generated
- HTML templates that reference static assets (CSS, JS, images)
- Basic knowledge of command-line operations or scripting (Python, Node.js, Bash, etc.)
- Control over asset paths (preferably serving assets via a local web server or file system)
Step-by-Step
- Host static assets on a local web server or use
file://paths. Avoid external URLs (e.g., CDN links) in templates when possible. Serve assets from localhost (e.g.,http://localhost:8000/css/style.css) so they can be reused without network latency. - Ensure all asset paths in your HTML templates are absolute and point to the local server or file system. For example, use
<link rel="stylesheet" href="http://localhost:8000/css/main.css">instead of relative or external paths. - Start a lightweight local web server to serve static assets. Use Python's built-in server:
python -m http.server 8000, or Node.js withhttp-server. This ensures assets are served consistently and can be cached by wkhtmltopdf’s internal mechanisms. - Enable the
--enable-local-file-accessflag when calling wkhtmltopdf. This allows the tool to read local files and assets served viafile://orhttp://localhost. Example:wkhtmltopdf --enable-local-file-access input.html output.pdf. - Use the
--cache-diroption to specify a directory where wkhtmltopdf can store cached assets. Create a directory like/tmp/wkhtmlcacheand pass it:--cache-dir /tmp/wkhtmlcache. This allows reuse of downloaded assets across multiple PDF generations. - Batch process PDFs using a script that reuses the same asset server and cache directory. Avoid restarting the server or clearing the cache between runs. For example, in a Bash loop or Python script, generate multiple PDFs while keeping the local server active.
- Set appropriate cache headers if using a local web server. Add
Cache-Control: max-age=31536000for static assets to prevent unnecessary re-downloads. This helps wkhtmltopdf recognize assets as cacheable. - Monitor the cache directory size. Periodically clean old files to prevent disk bloat, but do not delete during active batch processing. Use a script to rotate or archive cache files after batch completion.
- Test with a small batch first. Generate 5–10 PDFs and verify assets load from cache by checking response headers or using a tool like
tcpdumpor browser dev tools (if rendering via web preview). Confirm no repeated downloads of the same asset. - Optimize asset size. Minify CSS and JS, compress images, and inline critical styles if appropriate. Smaller assets reduce initial load and cache footprint, speeding up rendering.
Common Mistakes
- Using external CDNs for assets—this prevents caching and introduces network delays and potential failures.
- Forgetting
--enable-local-file-access, which causes wkhtmltopdf to block local asset loading, resulting in missing styles or broken images. - Not specifying
--cache-dir, forcing wkhtmltopdf to use temporary directories that may not persist between runs. - Restarting the local asset server between PDF generations, breaking connection reuse and cache efficiency.
- Using relative paths that resolve differently per input file, leading to duplicate or failed asset requests.
Tips
- Run the local asset server on a dedicated port and ensure it’s not blocked by firewalls or port conflicts.
- Use symbolic links to centralize assets and avoid duplication across templates.
- Pre-generate asset URLs and validate them before starting the batch to catch broken links early.
- Log asset request counts during testing to confirm caching is working (e.g., using a logging proxy or server access logs).
- Combine
--cache-dirwith--no-stop-slow-scriptsif JavaScript assets are involved, to avoid timeouts during initial asset loading.
Troubleshooting
If assets are not being cached, first verify that the --cache-dir directory exists and is writable. Check file timestamps in the directory to confirm assets are being stored. If assets still download repeatedly, ensure the local server sends consistent URLs and cache headers. Use --debug-javascript to see if wkhtmltopdf reports asset loading errors. If styles are missing, confirm --enable-local-file-access is enabled and paths are correct. In containerized environments, ensure the cache directory is mounted as a volume to persist between runs. If using Docker, avoid ephemeral containers for long batches—use a long-lived service instead.
Frequently Asked Questions
Does wkhtmltopdf cache assets by default?
No, it does not cache assets unless you explicitly set --cache-dir. Without it, each PDF generation may re-download assets.
Can I use file:// paths for assets?
Yes, but you must enable --enable-local-file-access. Otherwise, wkhtmltopdf blocks file access for security reasons.
Is it safe to share the same cache directory across multiple processes?
Not recommended. Concurrent access can cause race conditions. Use separate cache directories or serialize PDF generation.
Why are my PDFs still slow after caching?
Check if external assets (like fonts from Google Fonts) are still being fetched. Host them locally to fully benefit from caching.
Does caching work with HTTPS or authenticated assets?
No. wkhtmltopdf does not cache assets that require authentication or use dynamic URLs. Stick to static, unauthenticated assets for reliable caching.
How do I clear the cache?
Delete files in the directory specified by --cache-dir. Do this after batch processing to free space, but not during active use.