ScreenshotNeo

BlogHow-to

How to Install wkhtmltopdf on Alpine Linux with Python 3.6

Install wkhtmltopdf safely on Alpine with Python 3.6 by matching Alpine, architecture, Qt features, libraries, and fonts.

By the ScreenshotNeo team30 September 20269 min read

How to Install wkhtmltopdf on Alpine Linux with Python 3.6

Short answer: install an Alpine-built wkhtmltopdf package or build it for the exact Alpine release and CPU architecture in your image. Do not copy a generic Linux binary into Alpine: Alpine uses musl libc, while many upstream Linux downloads expect glibc. Then verify Qt behavior, shared libraries, fonts, and a real conversion from the final container. The research available for this guide confirms historical package examples, but it does not establish a currently supported Alpine and Python 3.6 combination.

Python 3.6 is end-of-life, so keep it only when an application constraint requires it. The Python interpreter does not determine which wkhtmltopdf binary you need; the Alpine branch, architecture, and runtime libraries do.

1. Check the constraints before installing

Record these values from the image and deployment target:

  • Alpine release: for example, 3.14 or another branch used by your base image.
  • Architecture: usually x86_64 or aarch64.
  • Python version: confirm that the application really requires 3.6.
  • Rendering requirements: JavaScript, local files, custom fonts, headers and footers, and other behavior your documents need.
  • Network policy: whether the converter can reach external stylesheets, images, and APIs during rendering.

The wkhtmltopdf project explains that Alpine is different because it uses musl rather than glibc. Its download matrix does not provide Alpine as an official stable target, and generic Linux binaries are therefore not a safe default. See the project download and status information at wkhtmltopdf.org/downloads.html.

2. Inspect Alpine repositories for your own branch

Start with the package already built for your configured repositories. The package name is wkhtmltopdf. Do not assume that a package shown for another branch or architecture applies to your image.

The installation path: match the Alpine artifact, invoke the executable from Python, and validate the produced PDF.
The installation path: match the Alpine artifact, invoke the executable from Python, and validate the produced PDF.
# Show the image release and architecture
cat /etc/alpine-release
uname -m

# See enabled repositories
cat /etc/apk/repositories

# Search configured repositories
apk update
apk search -v wkhtmltopdf

# Inspect a candidate before installing it
apk policy wkhtmltopdf

The Alpine package index contains a historical 0.12.6-r0 package for Alpine v3.14 community on x86_64. That row is evidence of availability for that branch and architecture only; it is not proof of availability on your current image. Check the matching package index entry at Alpine packages.

If the candidate is appropriate for your target, install it in the image:

apk add --no-cache wkhtmltopdf fontconfig freetype
wkhtmltopdf --version

The explicit font packages make the runtime intent clear. Your package may pull libraries automatically, but you still need to validate the final image rather than relying on the dependency solver alone.

3. Understand patched Qt before choosing a package

wkhtmltopdf depends on a Qt build. The project documents that its patched Qt supplies behavior that is not present in upstream Qt. A historical Alpine container example describes the Alpine package as unpatched and replaces it with a patched-Qt binary. Treat that example as historical guidance, not as a current binary recommendation.

Choose a build by comparing the Qt features your application needs. If your templates depend on the project’s patched-Qt behavior, an unpatched package can start successfully and still render the wrong output. Test JavaScript timing, CSS, headers and footers, and any local-file behavior you use.

Check Why it matters How to validate
Alpine branch Packages are built against a particular release. cat /etc/alpine-release and inspect the matching index.
Architecture An x86_64 package is not an aarch64 package. uname -m; inspect the package filename and index.
Qt patch level Patched Qt can change rendering features. Run representative conversions and compare expected output.
Runtime closure The executable still needs system libraries and fonts. Inspect linkage and run conversion in the final image.
Provenance Old custom binaries may be difficult to maintain. Prefer a repository package or reproducible build you can rebuild.

4. Verify libraries, fonts, and the executable

A binary that prints a version can still fail when it loads a page. Check the executable and its dynamic dependencies inside the same container that runs Python.

wkhtmltopdf --version
command -v wkhtmltopdf

# On Alpine, inspect shared-library resolution
ldd "$(command -v wkhtmltopdf)" || true

# Check that fontconfig sees fonts
fc-list | head

# Convert a minimal document
cat > /tmp/input.html <<'HTML'

Alpine smoke test

Rendered by wkhtmltopdf.

HTML wkhtmltopdf /tmp/input.html /tmp/output.pdf file /tmp/output.pdf

Fontconfig and freetype are specifically called out as runtime concerns in the project material. A historical recipe also added fonts and legacy OpenSSL libraries for its particular old image. Do not copy those old version pins into a current image without checking your branch and the actual linkage of your executable.

Run a second test that resembles production: load a stylesheet, use the fonts you ship, exercise JavaScript if required, and render a page that uses the same network policy. A successful command against a trivial local file does not prove that external assets or delayed scripts work.

5. A Dockerfile pattern for Python 3.6

This pattern leaves the package version to your configured Alpine repositories. Pin and mirror dependencies according to your organization’s build policy after confirming that the selected package belongs to the exact branch and architecture.

FROM python:3.6-alpine

RUN apk add --no-cache \
      wkhtmltopdf \
      fontconfig \
      freetype \
      ttf-dejavu

WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .

RUN wkhtmltopdf --version
CMD ["python", "app.py"]

If apk add reports no package, do not silently switch to a glibc-oriented download. Check whether the repository for your branch contains the package, whether the architecture is supported, or whether you need a maintained Alpine build. The research only documents historical v3.14 x86_64 and v3.9 aarch64 examples, not a current universal recipe.

6. Call wkhtmltopdf from Python 3.6

Use subprocess.run with an argument list. Capture stderr and enforce a timeout so a stuck page cannot hold a worker indefinitely.

import subprocess
from pathlib import Path


def html_to_pdf(html_path, pdf_path, timeout_seconds=60):
    command = [
        "wkhtmltopdf",
        "--quiet",
        str(html_path),
        str(pdf_path),
    ]
    try:
        completed = subprocess.run(
            command,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            universal_newlines=True,
            timeout=timeout_seconds,
            check=False,
        )
    except subprocess.TimeoutExpired:
        raise RuntimeError("wkhtmltopdf timed out")

    if completed.returncode != 0:
        raise RuntimeError(
            "wkhtmltopdf failed with code {0}: {1}".format(
                completed.returncode, completed.stderr.strip()
            )
        )

    output = Path(pdf_path)
    if not output.exists() or output.stat().st_size == 0:
        raise RuntimeError("wkhtmltopdf produced no PDF")
    return output


html_to_pdf("/tmp/input.html", "/tmp/output.pdf")

Keep paths explicit, create a private temporary directory for each job, and treat stderr as diagnostic data. Avoid shell interpolation. If HTML comes from users, sanitize it before invoking the converter.

7. Node.js and cURL alternatives for the local executable

Python is the focus of this guide, but the same executable can be called from other runtimes. In Node.js:

const { spawn } = require('child_process');

function htmlToPdf(input, output) {
  return new Promise((resolve, reject) => {
    const child = spawn('wkhtmltopdf', ['--quiet', input, output]);
    let stderr = '';
    child.stderr.on('data', chunk => { stderr += chunk.toString(); });
    child.on('error', reject);
    child.on('close', code => {
      if (code === 0) resolve(output);
      else reject(new Error(`wkhtmltopdf exited ${code}: ${stderr}`));
    });
  });
}

htmlToPdf('/tmp/input.html', '/tmp/output.pdf').catch(console.error);

For a local command-line smoke test, cURL can save an HTML response before conversion:

curl --fail --location https://example.com -o /tmp/page.html
wkhtmltopdf /tmp/page.html /tmp/page.pdf

8. Security and isolation

The wkhtmltopdf project gives this warning: 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, local-file references, cookies, and headers as untrusted input.

  • Sanitize user-supplied HTML and remove scripts unless they are required.
  • Run conversion as a non-root user in a restricted container.
  • Limit outbound network access and prevent access to internal metadata services.
  • Use per-job temporary directories with restrictive permissions.
  • Set process and document timeouts, output-size limits, and worker concurrency.
  • Do not pass secrets in command-line arguments when a safer mechanism is available.

9. Troubleshooting

apk add wkhtmltopdf says no such package

Cause: the configured repositories do not contain the package for your Alpine branch or architecture. Fix: inspect /etc/alpine-release, uname -m, and repository configuration. Check the matching Alpine package index. Do not use a package from a different branch without validating its compatibility.

The binary reports “not found” even though it exists

Cause: a missing dynamic loader or library, often caused by using a glibc-oriented binary on musl Alpine. Fix: use an Alpine-built artifact and inspect ldd output inside the final image.

The command starts but fonts are missing

Cause: fontconfig, freetype, or the actual font files are absent. Fix: install the required runtime packages and fonts, run fc-list, and test with the same fonts used in production.

PDF output is blank or JavaScript content is absent

Cause: the page may require delayed JavaScript, unsupported browser behavior, blocked network access, or a Qt build without the needed patches. Fix: test the page in the target container, review stderr, add only the required wait behavior, and compare a patched-Qt build when your application depends on those features.

Conversion hangs

Cause: a page never finishes loading, an external request is unreachable, or JavaScript keeps running. Fix: enforce a subprocess timeout, restrict network access, and reduce the page to a reproducible fixture to identify the blocking resource.

The PDF differs between local and production

Cause: different Alpine branches, architectures, Qt builds, fonts, locales, or network responses. Fix: compare wkhtmltopdf --version, package versions, installed fonts, and the exact container image. Validate in the final runtime.

10. Performance, reliability, and cost considerations

Each conversion starts an external process and may fetch many resources. Reuse warm workers where your isolation policy permits, keep templates and assets local when possible, and avoid rendering unnecessary pages. Set a bounded worker pool so concurrent conversions do not exhaust memory.

Cache deterministic inputs by a content hash and converter configuration. Include the executable version, fonts, CSS, and relevant flags in the cache key. A cache hit is safe only when those inputs are unchanged.

For reliability, record exit code, stderr, duration, input identifier, output size, and the image or package version. Retry only failures that are plausibly transient, such as a temporary network fetch. Repeating a deterministic missing-library or unsupported-Qt failure increases load without fixing the cause.

There is no current supported Python 3.6 and Alpine pairing established by the supplied research. Plan a migration path to a maintained Python and Alpine release, or isolate this legacy renderer behind a small service while you evaluate alternatives.

11. Or skip the browser setup

If your actual goal is a clean website screenshot or PDF rather than maintaining a browser runtime in Alpine, ScreenshotNeo provides a single HTTP request. Its API accepts a URL and returns PNG, JPEG, WebP, or PDF. Cookie and consent banners, newsletter popups, and chat widgets are removed before capture. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and the response identifies the result with X-Page-Verdict and X-Billed headers. An MCP server lets Claude, Cursor, and other MCP clients call take_screenshot, get_page_info, and capture_pdf.

A clean capture removes consent banners and overlays before the final image is returned.
A clean capture removes consent banners and overlays before the final image is returned.

See the ScreenshotNeo API documentation for all options.

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)
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}`);

ScreenshotNeo includes full-page capture with lazy images, CSS element capture, dark mode, device presets, custom viewports, retina scale, PDF paper and page options, custom CSS and JavaScript, clicks, waits, blocked requests, headers, cookies, user agents, timezone, geolocation, transparent backgrounds, resizing, TTL caching, signed links, asynchronous jobs, webhooks, bulk capture, usage data, and an OpenAPI specification. 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.

12. FAQ

Can I use the official generic Linux download on Alpine?

Do not assume so. The project explains that Alpine’s musl libc makes generic glibc-oriented binaries unsuitable. Use an Alpine-built package or build and validate it.

Does Python 3.6 require a special wkhtmltopdf package?

No. The executable is an operating-system dependency. Match Alpine release, architecture, Qt behavior, libraries, and fonts; then call it from Python.

Is the historical Alpine v3.9 archive a current recipe?

No. It demonstrates that old Python 3.6.8 and wkhtmltopdf artifacts existed for aarch64, but it does not prove current compatibility or installation success.

Why can a version check pass while conversion fails?

Version output does not exercise fonts, shared libraries, Qt rendering, JavaScript, or network access. Always run a representative conversion in the final image.

What should I do with untrusted HTML?

Sanitize it and isolate the converter. The wkhtmltopdf project warns that unsanitized HTML and JavaScript can lead to complete server takeover.