ScreenshotNeo

BlogHow-to

How to Fix wkhtmltopdf Command Errors with Responsive Chart.js Charts

Diagnose wkhtmltopdf failures and make responsive Chart.js charts render correctly in PDFs with reproducible commands, layout fixes, and debugging steps.

By the ScreenshotNeo team30 September 20269 min read

How to Fix wkhtmltopdf Command Errors with Responsive Chart.js Charts

Short answer: diagnose wkhtmltopdf failures by phase. First capture the complete command, binary path, version, permissions, and unabridged stderr. Then determine whether the failure is executable access, page or asset loading, JavaScript completion, or Chart.js sizing. For a blank chart, confirm JavaScript is enabled, wait for the chart to finish creating, and give the canvas a dedicated relatively positioned container with an explicit PDF size. Set maintainAspectRatio: false when the parent controls the height. Validate every change with the exact wkhtmltopdf binary, operating system, HTML, assets, fonts, and wrapper used in production.

This guide provides a minimal working example, complete commands, Chart.js print-layout fixes, configuration options, troubleshooting, and production notes.

1. Identify which phase is failing

A numeric exit code is only a symptom. Start by recording:

  • The exact command, including every option and input/output path.
  • Standard output and the complete, unabridged standard error stream.
  • The executable path returned by your shell and the account running it.
  • wkhtmltopdf --version, operating system and version, and installation method.
  • A minimal HTML file containing the same Chart.js version, data, CSS, and asset URLs.

The wkhtmltopdf project asks issue reporters for the version, OS/version, a detailed description, and a reproducible HTML/CSS/JavaScript case. Keep that same evidence even when debugging internally.

Failure phase Typical evidence First action
Executable or permission “Permission denied”, “not found”, status 126 Check path, execute bit, calling user, architecture, and shell access.
Page or asset loading Missing CSS, scripts, fonts, images, or load errors Test URLs and local-file access separately; inspect the installed build’s help.
JavaScript completion PDF succeeds but canvas is blank or half drawn Enable debugging, verify scripts load, and increase delay only as needed.
Chart layout Chart is clipped, tiny, stretched, or wrong on paper Fix the container dimensions and print-time resize logic.

2. Build a minimal reproducible Chart.js page

Reduce the problem before changing production templates. This example uses a dedicated container, a fixed PDF-friendly height, and an explicit aspect-ratio policy.

<!doctype html>
<html>
<head>
  <meta charset='utf-8'>
  <title>Chart test</title>
  <script src='https://cdn.jsdelivr.net/npm/chart.js'></script>
  <style>
    @page { size: A4; margin: 16mm; }
    .chart-container {
      position: relative;
      width: 100%;
      height: 90mm;
    }
  </style>
</head>
<body>
  <h1>Monthly revenue</h1>
  <div class='chart-container'>
    <canvas id='revenue-chart'></canvas>
  </div>
  <script>
    const canvas = document.getElementById('revenue-chart');
    new Chart(canvas, {
      type: 'bar',
      data: {
        labels: ['Jan', 'Feb', 'Mar', 'Apr'],
        datasets: [{
          label: 'Revenue',
          data: [12, 19, 15, 24],
          backgroundColor: '#2563eb'
        }]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        animation: false
      }
    });
  </script>
</body>
</html>

Save it as chart.html. If this file fails, remove application code until it works. If it succeeds while the real page fails, compare scripts, CSS, data size, network requests, and font loading.

3. Run wkhtmltopdf with useful diagnostics

JavaScript is enabled by default in the command-line tool, and the documented default JavaScript delay is 200 milliseconds. That delay is not proof that an asynchronous application has finished rendering.

wkhtmltopdf \
  --enable-javascript \
  --debug-javascript \
  --javascript-delay 1500 \
  --load-error-handling abort \
  chart.html chart.pdf

Use a delay appropriate to your page. Start small, inspect diagnostics, and increase it only when the chart is demonstrably still being created. Disable animation in the chart configuration when a static PDF is the goal; this removes a common source of timing variance.

If you need to test whether JavaScript is the cause, run a control conversion with --disable-javascript. A page without a chart may render successfully in that mode, confirming that the issue is in script execution or timing rather than basic PDF output.

4. Fix exit status 126 and other command errors

Exit status 126

Status 126 can accompany a shell permission-denied message. Treat the reported GitHub issue as an example, not a universal definition for every environment. Verify the selected executable exists and can be run by the same account that invokes your wrapper.

command -v wkhtmltopdf
WK=/usr/local/bin/wkhtmltopdf
ls -l "$WK"
file "$WK"
"$WK" --version
"$WK" about:blank /tmp/blank.pdf

Check that the file has an execute bit, its parent directories are searchable, and the binary architecture matches the host. Containers may also mount a filesystem with noexec. A service account can have different PATH and permissions from your interactive shell, so log the resolved path from the service itself.

“command not found” or wrong version

Use an absolute path in the wrapper, record the version at startup, and ensure your deployment image contains the intended binary. The downloads page lists 0.12.6 as the stable series released June 11, 2020. That version information does not establish compatibility with every modern JavaScript or CSS feature; reproduce on the actual binary and OS.

Load and local-file errors

Test each stylesheet, script, image, and font independently. Relative URLs may resolve differently from a local file than from a web server. If your page reads local resources, review the build’s local-file access controls and its installed help output. Do not assume an option available in one packaged build behaves identically in another.

5. Make Chart.js responsive inside a PDF

Chart.js responsiveness is container-based. Give each canvas a dedicated parent with position: relative; the documented pattern expects the container to contain only that chart. The canvas drawing dimensions and displayed dimensions are separate, so setting only a canvas width or height can produce blur, clipping, or an unexpected aspect ratio.

Chart.js follows its container, so print dimensions belong on the container and resize hooks.
Chart.js follows its container, so print dimensions belong on the container and resize hooks.
.chart-container {
  position: relative;
  width: 100%;
  height: 85mm;
}

.chart-container canvas {
  display: block;
}

responsive is enabled by default, as is maintainAspectRatio. The latter defaults to true, with an aspect-ratio default that depends on chart type: radial charts default to 1 and other chart types to 2. When the parent defines the required height, set maintainAspectRatio: false. If you explicitly set a height through an attribute or style, the aspectRatio option is ignored.

options: {
  responsive: true,
  maintainAspectRatio: false,
  animation: false
}

Multiple charts and page breaks

Use one container per canvas and assign each a deliberate height. Avoid placing a canvas directly in a flex or grid item whose height is determined only after fonts or content load. For long reports, apply page-break rules to the container rather than splitting a chart across pages.

6. Handle print CSS and explicit resizing

Print media rules can change available width after the chart has already measured its screen layout. Chart.js documents print event hooks and explicit resize dimensions for cases where automatic resizing does not match the print layout.

const chart = new Chart(document.getElementById('revenue-chart'), config);

window.addEventListener('beforeprint', () => {
  chart.resize(720, 340);
});

window.addEventListener('afterprint', () => {
  chart.resize();
});

Choose dimensions that match your PDF page and margins. If your wkhtmltopdf build does not trigger the browser print events in your flow, call a page function before capture or use a short script that performs the resize and then signals readiness.

7. Verify that JavaScript and assets finished

Use browser developer tools on the same HTML when possible. Confirm that the Chart.js script returns successfully, the canvas exists, and the chart instance is created. With wkhtmltopdf, --debug-javascript exposes console diagnostics. A useful debugging page can write a visible “ready” marker only after chart construction:

new Chart(canvas, config);
document.body.setAttribute('data-chart-ready', 'true');

Then wait for that selector through your surrounding automation, or use a page-specific delay. Do not rely on one universal wait value: network speed, dataset size, fonts, and chart plugins change completion time.

8. Security and reliability considerations

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 HTML, JavaScript, URLs, headers, and local-file access as untrusted inputs in a multi-tenant service. Run the converter with least privilege, isolate it where appropriate, restrict outbound access, and apply resource and execution time limits.

For reliability, pin the binary and OS image, keep a fixture page in continuous integration, and compare generated PDFs after upgrades. Log command arguments safely, exit code, stderr, elapsed time, input identifiers, and output size. Avoid logging secrets embedded in URLs or headers.

9. Performance and cost trade-offs

  • Disable chart animation and unnecessary plugins for deterministic output.
  • Prefer local, versioned assets when external network access is unreliable, while validating local-file permissions explicitly.
  • Use a targeted JavaScript delay instead of a large fixed delay for every page.
  • Reuse a prepared runtime where your architecture permits it, but never share mutable page state between jobs.
  • Keep datasets and DOM size bounded; very large pages increase rendering time and memory use.

Measure the whole conversion, including asset loading and PDF writing, on the deployment machine. A successful exit code does not guarantee that every chart, font, or image is present.

10. Or skip the browser setup

If you need a clean screenshot or PDF without maintaining a wkhtmltopdf runtime, ScreenshotNeo provides a single HTTP request API and an MCP server for AI agents. It accepts cookie and consent banners as a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be turned off. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and the response reports the page verdict and billing status in X-Page-Verdict and X-Billed headers.

A capture pipeline can remove page overlays before rendering the final image.
A capture pipeline can remove page overlays before rendering the final image.

See the ScreenshotNeo API documentation for all options, including full-page capture with lazy-image loading, CSS-element capture, dark mode, device presets, retina scale, PDF paper size and margins, custom CSS and JavaScript, selector waits, network-idle waits, request blocking, headers, cookies, authorization, timezone, geolocation, transparent backgrounds, resizing, caching, signed links, asynchronous jobs, bulk capture, usage, and OpenAPI compatibility.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

An MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000. Create a free ScreenshotNeo account.

11. Troubleshooting checklist

  1. Capture evidence: save the exact command, stdout, stderr, version, OS, user, and paths.
  2. Prove execution: run the absolute binary path against about:blank; fix permissions, PATH, architecture, or noexec.
  3. Reduce input: reproduce with one HTML file, one chart, and known assets.
  4. Check JavaScript: confirm the script loads, use --debug-javascript, and test with JavaScript disabled as a control.
  5. Wait for readiness: disable animation and tune a page-specific delay or readiness marker.
  6. Fix dimensions: use a relative container with explicit height and disable aspect-ratio preservation when needed.
  7. Check print behavior: resize explicitly before printing if print CSS changes the layout.
  8. Reproduce in production conditions: use the same binary, account, fonts, network policy, wrapper, and filesystem.

12. FAQ

Why does the PDF exist but the Chart.js canvas is blank?

The converter may have finished before JavaScript created the chart, the script may not have loaded, or JavaScript may be disabled. Confirm script loading, enable diagnostics, disable animation, and wait for chart creation.

Should I always use a five-second JavaScript delay?

No. The documented default is 200 milliseconds, but the correct value depends on your page. Use diagnostics and a readiness condition to choose the shortest reliable delay.

Why is my chart stretched after setting a height?

A canvas’s drawing and display dimensions are independent, and Chart.js preserves aspect ratio by default. Put the canvas in a dedicated relative container and set maintainAspectRatio: false when the container height is authoritative.

Is wkhtmltopdf 0.12.6 guaranteed to support modern web apps?

No. The project downloads page lists 0.12.6 as the stable series released June 11, 2020. Test the exact binary against your application’s JavaScript and CSS.

What should I include when reporting a wkhtmltopdf bug?

Include the version, operating system and version, complete diagnostics, exact command, and a detailed reproducible HTML/CSS/JavaScript case.

Primary references