ScreenshotNeo

BlogHow-to

How to Fix wkhtmltopdf Memory Corruption and AccessViolationException

Diagnose wkhtmltopdf AccessViolationException, isolate memory pressure, compare 32-bit and 64-bit builds, and plan a safer migration.

By the ScreenshotNeo team30 September 20269 min read

How to Fix wkhtmltopdf Memory Corruption and AccessViolationException

Direct answer: wkhtmltopdf’s AccessViolationException usually needs investigation rather than one magic flag. First record the exact binary and wrapper versions, reduce the document to a reproducible case, measure the converter’s memory and handle usage, and compare an official 64-bit build with the 32-bit build. A 32-bit process can run out of usable virtual address space or fail because of fragmentation even when Windows still has free physical RAM. Large tables, high-resolution images, embedded fonts, JavaScript, and too much concurrency are useful variables to isolate.

This guide shows a repeatable diagnosis process for Windows and Linux deployments, explains what the available evidence can and cannot prove, and gives migration options when the workload depends on modern browser behavior. It does not assume a universal row count, RAM threshold, or command-line switch fixes every crash.

What the exception means

An access violation means the native converter or a native dependency attempted an invalid memory access. In practice, the failure can be triggered by address-space exhaustion, fragmentation, a renderer defect, an image or font decoder, JavaScript activity, a wrapper bug, or a lifecycle problem that leaves memory behind between jobs. Microsoft documents that out-of-memory failures can come from high process usage or fragmented virtual address space, and that a 32-bit process has a much smaller address space than a 64-bit process, even on a 64-bit operating system.

wkhtmltopdf’s official stable series is 0.12.6, released in June 2020. The downloads page provides Windows 32-bit and 64-bit installers and archives. The GitHub repository was archived on January 2, 2023, so old issue comments are historical evidence rather than proof that a fix applies to your binary.

Step 1: Capture the facts before changing anything

Write down the details below for every failing environment. A wrapper may invoke a different executable than the one on your command line, and a “64-bit server” may still be running a 32-bit converter.

Reduce the document and measure one input variable at a time.
Reduce the document and measure one input variable at a time.
Fact How to collect it Why it matters
wkhtmltopdf version wkhtmltopdf --version Builds can contain different renderer and dependency behavior.
Operating system Record Windows edition/build or Linux distribution and kernel. Native libraries, sandboxing, and resource limits differ.
Process architecture Check whether the executable is 32-bit or 64-bit; do not infer it from the OS. 32-bit address space is constrained and can fragment.
Wrapper and flags Save library version, complete command line, environment variables, and working directory. Timeouts, local-file access, JavaScript, and lifecycle settings can alter the result.
Input Keep the exact URL or file, assets, fonts, and authentication setup. A reproduction must include the resource that actually triggers the crash.

Use a script or deployment log to preserve this information. The project asks for the exact version, OS version, and a detailed reproducible HTML/CSS/JavaScript case when requesting support.

Step 2: Build a minimal reproduction

  1. Save the input as a local HTML file and run it with the same executable used in production.
  2. Remove JavaScript, external fonts, images, and large tables one category at a time.
  3. When the crash stops, add the removed category back in smaller pieces until the trigger is identified.
  4. Keep the smallest HTML, CSS, and JS files that still fail. Include all required assets and the exact command.

This process distinguishes a renderer or asset trigger from a general lifecycle problem. Do not treat a historical report of a roughly 3,000-row table with images as a universal limit; it is a useful test variable only.

wkhtmltopdf --version
wkhtmltopdf --enable-local-file-access --javascript-delay 0 input.html output.pdf

For a controlled baseline, disable optional work only while isolating the cause. If removing scripts makes the failure disappear, test JavaScript timing and browser compatibility separately before choosing a permanent setting.

Step 3: Measure memory, address space, and concurrency

Watch the converter process while running a small document, then increase one dimension at a time: page count, image pixel dimensions, table rows, embedded fonts, and simultaneous conversions. Record private bytes, commit size, handle count, CPU time, and the point at which the process exits. Windows guidance recommends collecting data and identifying the largest memory consumers instead of concluding that installed RAM alone explains the failure.

  • High usage during one job: reduce image dimensions, split very large documents, or simplify the DOM and tables.
  • Usage rises after every job: reduce concurrency and recycle the worker after a bounded number of conversions while you investigate a leak.
  • Intermittent failures only under load: run one conversion per worker, then increase parallelism gradually.
  • Crash near a repeatable virtual size: compare 32-bit and 64-bit binaries and inspect fragmentation.

Recycling workers and reducing concurrency are operational mitigations to validate with your own measurements, not documented wkhtmltopdf guarantees.

32-bit versus 64-bit: what to test

Install the official 64-bit build on a compatible host and run the same reduced case, flags, fonts, and assets. A 64-bit process generally has a much larger user-mode address space, so it can avoid failures caused by a 32-bit ceiling or fragmentation. It will not repair malformed HTML, a renderer defect, an image decoder crash, or an application that leaks handles. Compare:

Test Keep constant Record
32-bit baseline Input, flags, wrapper, user, temp directory Peak memory, completion time, exit code, crash point
64-bit candidate The same variables Whether the case completes and how resource use changes
Load run Fixed number of workers and identical job order Failure rate and memory trend across jobs

If your wrapper embeds or locates a specific DLL, verify that every native dependency matches the process architecture. A 64-bit executable cannot load 32-bit libraries, and a wrapper may silently continue invoking the old binary if its path is hard-coded.

Windows-specific investigation

Use Task Manager, Resource Monitor, or a performance capture to identify the converter’s private bytes, commit, handles, and thread count. Capture the values before a job, at peak usage, after completion, and immediately before a crash. Also check free space and permissions for the temporary directory, because failed writes can look like renderer instability.

When resource exhaustion or a suspected leak is involved, Microsoft recommends gathering diagnostic data and analyzing the largest consumers. An antivirus product, desktop session, or another service consuming memory can reduce the headroom available to a 32-bit process. Keep those observations separate from proof of a wkhtmltopdf defect.

Linux, files, fonts, and network resources

Test local files and network URLs independently. Confirm DNS, TLS certificates, proxy settings, authentication headers, and access to every image, stylesheet, and font. A missing font can change pagination; a blocked resource can leave JavaScript waiting; a local-file restriction can produce an incomplete page.

For Linux deployments, review the project’s AppArmor guidance and the permissions of the executable, temporary directory, fonts, and input files. Run the converter with the least privilege that still permits required reads and writes. Never pass untrusted HTML or JavaScript directly to wkhtmltopdf: the project explicitly warns that unsanitized user content can lead to complete takeover of the server running it.

Security and isolation checklist

  • Sanitize user-supplied HTML, CSS, URLs, and JavaScript.
  • Run conversion in a dedicated worker or container with restricted filesystem and network access.
  • Set job timeouts and terminate hung child processes.
  • Limit input size, image dimensions, page count, and concurrent jobs.
  • Use a separate temporary directory and clean it after each job.
  • Log the executable path, version, flags, exit code, and resource metrics.

Common errors and fixes

Symptom Likely cause to test Fix or next experiment
AccessViolationException on a large report Address-space pressure, fragmentation, or an asset trigger Reduce the document, measure peak usage, and compare the 64-bit build.
Works for one job, then crashes Leak or unreleased native resources Track memory across jobs, lower concurrency, and recycle workers.
Only image-heavy pages fail Large decoded bitmaps or an image decoder problem Resize images, test formats individually, and add them back incrementally.
Only JavaScript pages fail Timing or unsupported browser behavior Make waits deterministic, remove scripts for a baseline, and pilot a modern renderer.
Blank or incomplete PDF Blocked local/network resource or premature capture Check permissions and requests, then test an explicit delay or a local fixture.
64-bit test gives a loader error Architecture-mismatched wrapper or DLL Use a matching wrapper and native dependencies, and verify the executable path.
A clean capture removes common overlays before rendering.
A clean capture removes common overlays before rendering.

When to migrate

If the reduced case still fails, or the document depends on modern JavaScript, run a side-by-side compatibility pilot. The project points dynamic-JavaScript users toward Puppeteer and report-generation users toward WeasyPrint or commercial PrinceXML. Test your own CSS pagination, fonts, JavaScript timing, headers and footers, page breaks, and resource limits. Compare renderer age and JavaScript support, print-layout fidelity, font handling, memory behavior under concurrency, sandbox controls, licensing, deployment footprint, and maintenance activity.

Keep the old and new renderers in parallel until representative documents produce acceptable output. Record visual differences and operational metrics; do not infer equivalence from one successful page.

Or skip the browser setup

If your goal is reliable website screenshots or PDFs rather than maintaining a native converter, ScreenshotNeo provides one GET request for a clean PNG, JPEG, WebP, or PDF. Cookie and consent banners, newsletter popups, and chat widgets are removed before capture. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing result. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients.

See the ScreenshotNeo API documentation for all options. The service supports full-page capture with lazy images, CSS element selection, dark mode, device presets or custom viewports, retina scale, PDF paper size and margins, custom CSS and JavaScript, clicks, selector or network-idle waits, request blocking, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, configurable caching, signed links, asynchronous jobs, webhooks, bulk capture, usage data, and an OpenAPI specification.

cURL

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

Python

import requests

r = requests.get(
    'https://api.screenshotneo.com/v1/shot',
    params={'access_key': 'YOUR_API_KEY', 'url': 'https://stripe.com'},
    timeout=90,
)
r.raise_for_status()
open('shot.webp', 'wb').write(r.content)

Node.js

const q = new URLSearchParams({
  access_key: 'YOUR_API_KEY',
  url: 'https://stripe.com'
});
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const fs = await import('node:fs/promises');
await fs.writeFile('shot.webp', Buffer.from(await res.arrayBuffer()));

ScreenshotNeo includes 1,000 shots per month free with no card. Paid plans start at $5 for 3,000 shots; every feature is available on every plan, and yearly billing gives two months free. Create a free ScreenshotNeo account to try the API.

Performance, reliability, and cost notes

  • For wkhtmltopdf, benchmark one variable at a time and measure peak process resources, not only wall-clock time.
  • Bound concurrency and use worker recycling when measurements show growth across jobs.
  • Cache stable inputs where appropriate, but verify that cached output is valid after asset changes.
  • For ScreenshotNeo, choose a cache TTL, waits, viewport, and output format that match the page; use asynchronous jobs and bulk capture for large batches.
  • Only clean ScreenshotNeo shots are billed, while failed loads, bot checks, blank pages, timeouts, and cache hits are free according to the response verdict and billing headers.

FAQ

Is AccessViolationException always caused by low RAM?

No. High usage and fragmented address space are documented possibilities, but a renderer, dependency, asset, wrapper, or lifecycle defect can produce the same symptom.

Will adding --lowquality fix corruption?

There is no evidence here for a guaranteed switch. Test changes against a reduced reproduction and keep measurements.

Should every deployment move to 64-bit?

Compare the official 32-bit and 64-bit builds with your wrapper and workload. A larger address space can remove one class of failure, but it does not correct invalid input or unsupported rendering behavior.

Can I safely convert user-submitted HTML?

Not without sanitization and isolation. The project warns that untrusted HTML or JavaScript can result in complete server takeover.

What should I send when asking for help?

Send the exact version, OS version, process architecture, wrapper and flags, and a minimal reproducible HTML/CSS/JS case with steps to reproduce.