# PDF Engine Setup Guide

> **Target:** Ubuntu 22.04 / 24.04 servers (aaPanel or plain)
> **Stack:** Laravel 12 + `chrome-php/chrome` + Chrome/Chromium
> **Last updated:** 16 August 2026 — writable `HOME` for the web user (§3, §7, §8)

Everything in the panel that produces a PDF or a rendered image — fee receipts, marksheets,
datesheets, timetables, certificates, ID cards, engagement creatives, gallery thumbnails —
goes through one engine. This is how to install and verify it.

---

## 1. What it is

```
Laravel (PHP)  ──►  Chrome / Chromium  ──►  PDF or PNG
                    (DevTools Protocol, spoken natively by PHP)
```

**Node.js is not required.** PHP talks to Chrome directly over the DevTools Protocol, so
there is no Node, no npm, no Puppeteer, and no `node_modules` on the server.

If the browser engine fails, every caller falls back to **DomPDF** automatically. Nothing
errors — you simply get a lower-quality PDF. That is why the verification in §4 matters.

---

## 2. Install a browser

> [!CAUTION]
> **Do not install `chromium-browser` from apt on Ubuntu 20.04 or newer.** That package is
> a transitional stub: it installs the **snap** Chromium and leaves a shell script at
> `/usr/bin/chromium-browser` that calls `snap run chromium`.
>
> A snap cannot be launched from inside a systemd *system* service. php-fpm is one, so
> every web-request render dies with:
>
> ```
> Chrome process stopped before startup completed. Additional info:
> /system.slice/php-fpm-83.service is not a snap cgroup for tag snap.chromium.chromium
> ```
>
> The cruel part: **the CLI test still passes.** A root login shell sits in a user slice,
> which snap accepts, so `php artisan pdf:chrome --test` reports OK while every receipt,
> ID card and marksheet in the panel silently degrades to DomPDF. See §7.

**Option A — Google Chrome stable (recommended):**

```bash
wget -q -O /tmp/chrome.deb https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb && sudo apt-get install -y /tmp/chrome.deb
```

Binary: `/opt/google/chrome/google-chrome`. It is a real ELF executable with no snap
confinement, and the deb pulls its own shared libraries.

**Option B — `chrome-headless-shell` (fastest):** if Node is already on the server, this
renders roughly **1.8× faster** than full Chrome (~630 ms vs ~1130 ms measured) because it
ships without the browser UI layer:

```bash
npx @puppeteer/browsers install chrome-headless-shell@stable --path /opt/chrome
```

> [!TIP]
> If the server already carries `chrome-headless-shell` from the old Browsershot setup,
> **keep using it** — point `PDF_CHROME_PATH` at that path and install nothing.

### Confirm you got a real binary, not a snap stub

This one command is the whole check. `ELF 64-bit` is what you want; **`shell script` means
you have the snap stub** and renders will fail under php-fpm:

```bash
file /opt/google/chrome/chrome
```

To audit a path that is already configured — if `readlink -f` returns the path unchanged
*and* `file` says shell script, it is the snap wrapper:

```bash
readlink -f "$(which chromium-browser chromium google-chrome 2>/dev/null | head -1)"; snap list chromium 2>/dev/null
```

There is no need to remove an existing chromium snap. Nothing in the panel references it —
just stop pointing `PDF_CHROME_PATH` at it.

### Missing shared libraries

Chrome needs X11/graphics libraries even headless. If it fails to start, install them.
**Pick the block for your Ubuntu version — the package names differ and are not
interchangeable** (24.04 renamed three packages with a `t64` suffix). Check your version
first if unsure:

```bash
lsb_release -rs
```

**Ubuntu 24.04** (`libatk1.0-0t64`, `libcups2t64`, `libasound2t64`):

```bash
sudo apt-get install -y libnss3 libnspr4 libatk1.0-0t64 libatk-bridge2.0-0t64 libcups2t64 libdrm2 libxkbcommon0 libxcomposite1 libxdamage1 libxfixes3 libxrandr2 libgbm1 libpango-1.0-0 libcairo2 libasound2t64 libxshmfence1 fonts-liberation
```

**Ubuntu 22.04** (`libatk1.0-0`, `libcups2`, `libasound2` — no `t64`):

```bash
sudo apt-get install -y libnss3 libnspr4 libatk1.0-0 libatk-bridge2.0-0 libcups2 libdrm2 libxkbcommon0 libxcomposite1 libxdamage1 libxfixes3 libxrandr2 libgbm1 libpango-1.0-0 libcairo2 libasound2 libxshmfence1 fonts-liberation
```

To find exactly what is missing:

```bash
ldd /opt/google/chrome/chrome | grep "not found"
```

---

## 3. Configure `.env`

> [!IMPORTANT]
> **On an existing server, you usually add nothing.** Both keys have safe defaults:
> - `PDF_DRIVER` is unset → defaults to **`chrome`** (the new engine).
> - `PDF_CHROME_PATH` is unset → **falls back to your existing `BROWSERSHOT_CHROME_PATH`**,
>   then to auto-discovery.
>
> So a server provisioned with the old Browsershot guide — which already has
> `BROWSERSHOT_CHROME_PATH` pointing at `chrome-headless-shell` — is **already running the
> new engine on that binary with no `.env` edit at all.** Skip to §4 and verify; only add
> keys below if verification shows a problem or you want to be explicit.

Only two keys matter, and both are optional:

| Key | Default if absent | When to set it |
|-----|-------------------|----------------|
| `PDF_DRIVER` | `chrome` | Only to roll back — `browsershot` (see §5) |
| `PDF_CHROME_PATH` | `BROWSERSHOT_CHROME_PATH`, then auto-discover | On a **fresh** server with no `BROWSERSHOT_CHROME_PATH`, or to pin an exact binary |

**Fresh server** (no old Browsershot keys present) — set the path explicitly:

```dotenv
PDF_DRIVER=chrome
PDF_CHROME_PATH="/opt/google/chrome/google-chrome"
```

**Existing server** (already has `BROWSERSHOT_CHROME_PATH`) — nothing to add; it is reused
automatically. Set `PDF_CHROME_PATH` only if you want to move off the puppeteer cache path
onto a distro binary.

> [!WARNING]
> When you change `PDF_CHROME_PATH`, change `BROWSERSHOT_CHROME_PATH` to match. Leaving a
> stale value there is harmless *today* — `PDF_CHROME_PATH` wins — but it becomes the live
> path the moment anyone rolls back to `PDF_DRIVER=browsershot` (§5), which resurrects the
> old broken binary at the worst possible moment.

Leaving `PDF_CHROME_PATH` blank is fine — the engine finds a system Chrome. Setting it
explicitly is faster and removes ambiguity about which binary is used.

After **any** change to a `PDF_*` or `BROWSERSHOT_*` key:

```bash
php artisan config:clear && php artisan queue:restart && sudo systemctl restart php-fpm-83
```

> [!IMPORTANT]
> **The php-fpm restart is not optional, and it is the step people skip.** `config:clear`
> only drops the cached config file; the FPM workers already running still hold the old
> environment and will keep launching the old binary. Adjust `php-fpm-83` to your PHP
> version (`systemctl list-units 'php-fpm*'` if unsure). On aaPanel you can equally use
> **App Store → PHP → Service → Reload**.

### Permissions

Two separate things must be true for the web user (`www` on aaPanel): it must be able to
**execute** Chrome, and it must have a **writable home directory** for Chrome to put its
profile in.

**1. The web user needs a real, writable `HOME`.**

Chrome writes a profile, a preferences tree and a crashpad database under `$HOME` before it
will start — even headless. On aaPanel the `www` user's passwd home is `/home/www` and that
directory **is usually never created by the panel**, so Chrome dies on startup in the web
context while working perfectly from a root shell. Create it once:

```bash
getent passwd www
```

Use whatever home that reports (normally `/home/www`), then, **as root**:

```bash
mkdir -p /home/www/.local/share/applications /home/www/.config /home/www/.cache && chown -R www:www /home/www && chmod 755 /home/www
```

> [!WARNING]
> Run that as **root**, not as `sudo -u www`. `sudo -u www mkdir -p …` drops privileges
> *before* creating anything, so it fails on the first parent directory the `www` user
> cannot write — and `sudo su` first does not help, because the `-u www` still drops back
> down. Root creates the directory; `chown` then hands it over.

**2. The web user must be able to execute the binary.**

```bash
sudo -u www env HOME=/home/www /opt/google/chrome/google-chrome --headless --disable-gpu --dump-dom https://example.com | head -3
```

If that prints HTML, both permissions are correct. Setting `HOME` explicitly on the command
matters: without it you inherit *root's* `HOME`, which exists, and the test passes on a
server where the real web context would still fail.

> [!NOTE]
> Passing this test does **not** clear the binary. `sudo -u www` changes the *user* but not
> the *cgroup* — the command still runs in your login session's slice, so a snap stub can
> pass here and still fail inside php-fpm. Only §4's **Run Now** exercises the real
> php-fpm context.

### Optional keys

| Key | Default | Purpose |
|-----|---------|---------|
| `PDF_CHROME_MODE` | `launch` | `persistent` keeps one browser alive — see §6 |
| `PDF_CHROME_NO_SANDBOX` | `true` | Required as root and in most containers |
| `PDF_CHROME_STARTUP_TIMEOUT` | `30` | Seconds to wait for the browser to start |
| `PDF_CHROME_FLAGS` | *(empty)* | Comma-separated extra flags, e.g. `--disable-dev-shm-usage` on small containers |
| `PDF_CHROME_ENV_PASSTHROUGH` | *(see `config/pdf.php`)* | Environment variables forwarded to Chrome. Rarely needs changing — see §7 |

---

## 4. Verify

Three independent checks. Do all three the first time — **in this order.**

> [!CAUTION]
> **A green CLI test proves nothing on its own.** The command line and php-fpm run in
> different environments and different cgroups, and the failure modes that matter in
> production (snap confinement, a trimmed FPM environment, a `www` user that cannot execute
> the binary) affect *only* php-fpm. Check 1 below is green on a completely broken server.
> **Check 2 is the one that decides.**

**1. From the Health page — the authoritative check.**

Superadmin → **Server Health** → **Self-Tests** → **PDF Engine**, then press **Run Now**.

This renders a real PDF through the exact pipeline the panel uses, **in the php-fpm
context**. Scheduled runs of the same check use the CLI context instead, so the two
statuses are meaningful *together*:

| CLI (scheduled) | Web (Run Now) | Meaning |
|---|---|---|
| pass | pass | Healthy. |
| pass | **fail** | **The php-fpm environment, not Chrome.** Snap stub, trimmed env, or permissions — see §7. |
| fail | fail | Chrome itself: wrong path, missing libraries. |
| fail | pass | Rare — usually a stale CLI config cache. |

**2. From the command line** — useful for *what is configured*, not for whether it works:

```bash
php artisan pdf:chrome
```

Reports the driver, mode, the binary **actually being used**, and whether the engine is
available. Add `--test` to render a real PDF:

```bash
php artisan pdf:chrome --test
```

**3. From the browser** — download any marksheet or fee receipt, open DevTools →
**Network**, and look at the response header:

| Header | Meaning |
|--------|---------|
| `X-Pdf-Engine: chrome` | True browser render |
| `X-Pdf-Engine: dompdf-fallback` | **Degraded** — the browser engine failed |

> [!IMPORTANT]
> The DomPDF fallback is silent by design, so a degraded PDF looks like a working one.
> If a PDF ever "looks wrong", **check this header before debugging the template.**
> Fallbacks are also logged: grep `storage/logs/laravel-<date>.log` for
> `Falling back to DomPDF`.

---

## 5. Upgrading from the old Browsershot setup

Nothing is forced. `PDF_CHROME_PATH` falls back to `BROWSERSHOT_CHROME_PATH`, so a server
provisioned with the old guide keeps working with no `.env` edit.

To roll back to the Node/Puppeteer path at any time:

```dotenv
PDF_DRIVER=browsershot
```

That requires Node, npm and Puppeteer to still be installed, and uses the
`BROWSERSHOT_NODE_PATH` / `BROWSERSHOT_NPM_PATH` / `BROWSERSHOT_CHROME_PATH` keys. See
[`BROWSERSHOT_SETUP.md`](BROWSERSHOT_SETUP.md) for that stack. Output is identical either
way — the two paths were verified byte-for-byte on the page content stream.

---

## 6. Persistent mode (optional, ~2× faster)

By default a browser is started and closed per render. Persistent mode keeps one alive and
opens a tab per render:

```dotenv
PDF_CHROME_MODE=persistent
```

Measured ~1.9× faster on average and ~2× at the floor (327 ms vs 627 ms per render). The
browser is recycled after `PDF_CHROME_MAX_RENDERS` (200) or `PDF_CHROME_MAX_LIFETIME`
(3600 s), whichever comes first.

The shared browser outlives the request that started it, so it needs managing:

```bash
php artisan pdf:chrome --stop
```

**Run `--stop` before every deploy** and after changing any `PDF_CHROME_*` setting.
`--restart` stops, relaunches and renders a test PDF.

Leave this off until the default mode has been stable on the server for a while.

---

## 7. Troubleshooting

Both of the first two entries produce the same headline — *"Could not start the browser
(Chrome process stopped before startup completed)"* — and the same symptom, CLI green and
**Run Now** red. Read the `Additional info:` text to tell them apart:

| `Additional info:` contains | Entry |
|---|---|
| `mkdir: cannot create directory`, `chrome_crashpad_handler: --database is required` | `HOME` is not writable — below |
| `is not a snap cgroup for tag snap.chromium.chromium` | snap stub — next entry |

The distinction is worth a moment: in the first, Chrome's **real binary ran** (a crashpad
handler could only have been spawned by a genuine Chrome) and then failed to write its
profile. In the second, Chrome never executed at all.

### `mkdir: cannot create directory '/home/www': Permission denied`

The full error on the Health page reads:

```
PDF engine (chrome) failed in web/php-fpm context: Could not start the browser
(Chrome process stopped before startup completed. Additional info:
mkdir: cannot create directory '/home/www': Permission denied
touch: cannot touch '/home/www/.local/share/applications/mimeapps.list':
No such file or directory
chrome_crashpad_handler: --database is required)
```

**Cause.** The web user's `HOME` points at a directory that does not exist and that the user
cannot create. On aaPanel the `www` user's passwd home is `/home/www`, and the panel never
creates it — so Chrome cannot write its profile, its XDG data tree, or the crashpad
database (whose path resolves under `$HOME`, which is why it reports an empty `--database`).

**Signature.** CLI passes, web fails — because a root shell has `HOME=/root`, which exists.
Identical outward behaviour to the snap trap, opposite cause.

**Confirm:**

```bash
getent passwd www; ls -ld /home/www
```

A passwd home of `/home/www` plus `ls: cannot access` is the whole diagnosis.

**Fix.** Create the directory as **root** and hand it to the web user — see §3 Permissions
for why `sudo -u www mkdir` cannot do this:

```bash
mkdir -p /home/www/.local/share/applications /home/www/.config /home/www/.cache && chown -R www:www /home/www && chmod 755 /home/www
```

```bash
php artisan config:clear && php artisan queue:restart && sudo systemctl restart php-fpm-83
```

Then re-run **Run Now**.

> [!NOTE]
> **Do not try to fix this with `PDF_CHROME_ENV_PASSTHROUGH`.** That key is an allowlist of
> variable *names*; `ChromeDriver::childEnvironment()` forwards whatever `getenv()` already
> holds and invents nothing, so it cannot rewrite `HOME` to a different path. Removing
> `HOME` from the list makes things worse — Chrome then falls back to the passwd entry and
> lands on the same unwritable directory.

**Alternative, if `/home/www` cannot be created** (a locked-down or containerised host):
point the pool at a writable `HOME` instead, in the php-fpm pool config — on aaPanel,
**Website → PHP-FPM config**, or `/www/server/php/83/etc/php-fpm.d/www.conf`:

```
env[HOME] = /www/wwwroot/<your-site>/storage/app/chrome-home
```

Create that directory with the site's own ownership before restarting php-fpm. Note this is
a *pool* setting, so it applies to every site in the pool.

### `is not a snap cgroup for tag snap.chromium.chromium`

The full error on the Health page reads:

```
PDF engine (chrome) failed in web/php-fpm context: Could not start the browser
(Chrome process stopped before startup completed. Additional info:
/system.slice/php-fpm-83.service is not a snap cgroup for tag snap.chromium.chromium)
using binary [/usr/bin/chromium-browser]
```

**Cause.** `PDF_CHROME_PATH` points at the apt `chromium-browser` stub, which is a shell
script that runs the snap. `snap-confine` refuses to launch when the calling process is in
a systemd system-service cgroup, and php-fpm always is.

**Signature.** CLI passes, web fails. `php artisan pdf:chrome --test` renders fine, the
Health page's **Run Now** fails, and no PDF in the panel visibly errors — they all quietly
fall back to DomPDF.

**Confirm** — `shell script` rather than `ELF 64-bit` is the tell:

```bash
file "$(readlink -f /usr/bin/chromium-browser)"; snap list chromium
```

**Fix.** Install a real binary (§2 Option A) and repoint both keys:

```bash
wget -q -O /tmp/chrome.deb https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb && sudo apt-get install -y /tmp/chrome.deb
```

```dotenv
PDF_CHROME_PATH="/opt/google/chrome/google-chrome"
BROWSERSHOT_CHROME_PATH=/opt/google/chrome/google-chrome
```

```bash
php artisan config:clear && php artisan queue:restart && sudo systemctl restart php-fpm-83
```

Then re-run **Run Now** — not the CLI test, which was green the whole time.

> [!NOTE]
> Queue jobs may keep working throughout, because supervisor's children are not in the
> php-fpm cgroup. So bulk marksheets and bulk ID cards succeed while the equivalent
> on-screen download degrades. Two different results for "the same" PDF is itself a strong
> hint that you are looking at this bug.

### `Devtools could not start` / `Cannot start http server for devtools`

Chrome could not open its debug port. Almost always one of:

- **The web user's `HOME` does not exist or is not writable** — the most common cause on
  aaPanel; see the `/home/www` entry above.
- **The binary is a snap stub** — see the entry above; check this first if the CLI passes
  and the web context fails.
- **Chrome is missing system libraries** — see §2.
- **The web user cannot execute the binary** — run the `sudo -u www` test in §3.
- **Chrome received no usable environment.** Chrome needs real system variables (`HOME`
  on Linux, `SystemRoot` on Windows) and cannot initialise without them. The engine
  forwards an explicit allowlist (`PDF_CHROME_ENV_PASSTHROUGH`) precisely because a
  php-fpm pool with a trimmed environment would otherwise leave Chrome without `HOME` and
  unable to write its profile. If your pool is unusual, add the missing variable names to
  that key. Note this forwards variables that *exist* — if `HOME` is present but points
  somewhere unwritable, this key is not the fix; the entry above is.

The health check keeps Chrome's real stderr in its `full_error` meta field — that is where
the actual cause is, and log viewers usually truncate it.

### PDFs render but look wrong / plain

Check `X-Pdf-Engine` (§4). If it says `dompdf-fallback`, the browser engine is failing and
you are seeing DomPDF output — fix the engine rather than the template.

### A render times out

Usually an asset the page cannot load. All images must be inlined as `data:` URIs before
rendering; a single remote URL makes Chrome wait for it, and a **same-host** URL under a
single-threaded dev server deadlocks outright. In production it costs a network round-trip
per render and stalls if the asset needs authentication or a signed proxy.

### Health check warns about `PDF_CHROME_PATH`

The configured path does not exist, so auto-discovery is being used instead. Rendering
works, but the setting is stale — update it to the real path or clear it. Common after an
aaPanel upgrade moves a binary, or when an `.env` is copied between servers.

### Persistent mode behaving oddly

Look for stray browser processes first, then reset:

```bash
pgrep -af "chrome|chromium" | head
```

```bash
php artisan pdf:chrome --stop
```

An orphaned keep-alive browser holding a port can make new connections block on the
handshake.

---

## 8. Quick reference

```bash
# is the configured binary real, or a snap stub? ELF = good, shell script = broken
file "$(readlink -f /opt/google/chrome/google-chrome)"

# does the web user have a home directory at all? "cannot access" = Chrome will not start
getent passwd www; ls -ld /home/www

# create it — as ROOT, never `sudo -u www` (that drops privileges before creating)
mkdir -p /home/www/.local/share/applications /home/www/.config /home/www/.cache && chown -R www:www /home/www && chmod 755 /home/www

# does the web user actually get a browser? HOME must be set explicitly or you test root's
sudo -u www env HOME=/home/www /opt/google/chrome/google-chrome --headless --disable-gpu --dump-dom https://example.com | head -3

# status: driver, mode, binary in use, availability (CLI context — not proof)
php artisan pdf:chrome

# render a real test PDF through the active engine (CLI context — not proof)
php artisan pdf:chrome --test

# stop the shared browser (persistent mode) — run before deploys
php artisan pdf:chrome --stop

# after any PDF_* .env change — the fpm restart is the load-bearing part
php artisan config:clear && php artisan queue:restart && sudo systemctl restart php-fpm-83
```

**The only check that proves the engine works:** Superadmin → Server Health → Self-Tests →
**Run Now**. It is the sole test that runs in the php-fpm context, which is where PDFs are
actually rendered for users.
