ScreenshotNeo

BlogHTML to image & PDF

How to Remove Gray Borders Around Images in wkhtmltopdf

Diagnose gray image edges in wkhtmltopdf by isolating CSS, transparency, scaling, JPEG conversion, and renderer build differences.

By the ScreenshotNeo team1 October 20266 min read

There is no documented wkhtmltopdf switch that universally removes gray borders around images. The edge can come from CSS, PNG transparency compositing, image enlargement, JPEG conversion, or differences between wkhtmltopdf builds. Isolate one variable at a time, then keep the smallest change that removes the artifact.

1. Start with a controlled reproduction

Save the exact HTML, source image, command, wkhtmltopdf version, operating system, and output format. A reproducible baseline prevents unrelated changes from hiding the cause.

 wkhtmltopdf --version
wkhtmltopdf input.html output.pdf

Use a minimal document while diagnosing:

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <style>
    html, body { margin: 0; padding: 0; }
    img { display: block; border: 0; outline: 0; box-shadow: none; }
  </style>
</head>
<body>
  <img src="image.png" alt="">
</body>
</html>

If the gray line remains in this page, CSS is less likely to be the source. This does not prove that every original layout rule is innocent; it only narrows the test.

2. Check for a real CSS border or effect

Inspect the image and its ancestors for border, outline, box-shadow, background colors, and pseudo-elements. Temporarily apply:

img,
figure,
.image-wrapper {
  border: 0 !important;
  outline: 0 !important;
  box-shadow: none !important;
  background: transparent !important;
}

Also check whether a parent has a contrasting background that shows through transparent pixels. Remove one rule at a time and render again. If the line does not move or change, stop treating CSS as the confirmed cause.

3. Test PNG transparency and alpha compositing

A transparent PNG may acquire a light fringe when the renderer composites or resamples it against a PDF or JPEG background. Compare the original file with a copy flattened against the intended background.

# ImageMagick diagnostic: flatten onto white
magick image.png -background white -alpha remove -alpha off image-flat-white.png

# Flatten onto a dark background if that is the page color
magick image.png -background '#202124' -alpha remove -alpha off image-flat-dark.png

Replace the image in the HTML with each copy and render the same command. If only the flattened copy removes the edge, transparency handling is implicated. A community answer recommends removing a PNG alpha channel and re-exporting; treat that as a diagnostic suggestion, not a guaranteed fix for every file.

When flattening is appropriate, export at the final background color and preserve the original transparent asset for other uses. Flattening permanently removes transparency.

4. Check whether the image is being enlarged

One reported case associated the artifact with enlarging an image beyond its intrinsic dimensions. Test the image at its native size first:

<img src="image.png" width="800" height="450" alt="">

Then remove explicit dimensions, or use a source file close to the displayed size:

img { max-width: 100%; height: auto; }

If the border disappears when enlargement is removed, generate a higher-resolution source or reduce the displayed size. This observation comes from a specific issue report and is not a universal explanation.

5. Separate image conversion from PDF rendering

A 2017 report described a one-pixel gray border when PNGs were converted to JPEG in wkhtmltopdf 0.12.4. That report does not establish that every gray edge has the same cause. Compare PDF output with an image output path and keep the input image constant.

wkhtmltopdf documents image controls such as --image-dpi for downscaling embedded images and --image-quality for JPEG compression. They are image-handling controls, not documented border-removal flags.

# Baseline
wkhtmltopdf page.html baseline.pdf

# Test one image setting at a time
wkhtmltopdf --image-dpi 300 page.html dpi.pdf
wkhtmltopdf --image-quality 95 page.html quality.pdf

Do not change zoom, margins, page size, image dimensions, and compression in one experiment. A result is useful only when you know which variable changed.

See the official wkhtmltopdf usage documentation for the complete option list.

6. Compare wkhtmltopdf builds

Record the exact binary and platform:

wkhtmltopdf --version
uname -a
which wkhtmltopdf

The maintainer download information notes that patched-Qt and platform-library differences can produce different behavior between builds. Compare the same HTML, image, command, and output format on another supported build. A version comparison is a controlled test, not a guaranteed cure.

The maintainer download page identifies 0.12.6 as the stable series. If you change versions, record both versions and keep all other inputs identical.

7. A repeatable diagnostic matrix

Test Change exactly one thing What a changed result suggests
CSS Remove borders, outlines, shadows, and wrapper backgrounds The document styling produced the edge
Alpha Use a flattened PNG on the intended background Transparency or resampling is involved
Scaling Render at intrinsic size or use a larger source Enlargement interpolation contributes
Conversion Compare PNG-preserving and JPEG-compressed paths Conversion or compression contributes
Build Use another recorded wkhtmltopdf build Renderer or platform libraries differ

8. Common errors and fixes

“I tried a border-removal flag, but it does not exist.”

No documented command-line option specifically removes gray image borders. Use the diagnostic sequence above instead of relying on an undocumented switch.

The line appears only on transparent PNGs

Render a copy flattened against the page background. If that works, export an intentionally flattened asset or investigate the source image’s edge pixels.

The line appears only when the image is enlarged

Remove enlargement, use a higher-resolution source, or display at intrinsic dimensions. Repeat with the same command.

Changing margins, zoom, or page size changed the artifact

Those options can alter layout and resampling, but the reports do not prove they are the root cause. Revert to a baseline and change one setting per render.

Different machines produce different PDFs

Compare wkhtmltopdf --version, operating system, installation source, patched-Qt status, and system libraries. Keep a minimal reproduction for each build.

The fix works in a browser but not in wkhtmltopdf

wkhtmltopdf uses a patched Qt rendering engine, so browser output is not a definitive reference. Test the exact wkhtmltopdf binary used in production.

9. Reporting an unresolved case

If the artifact remains, provide maintainers with:

  • Exact output of wkhtmltopdf --version
  • Operating system and version
  • The smallest HTML/CSS/JS reproduction
  • One source image, including whether it has an alpha channel
  • The complete conversion command
  • The resulting PDF and, if possible, a comparison render

This matches the project’s support guidance and makes the issue testable.

10. Performance, reliability, and output considerations

  • Performance: Large images and high DPI increase memory use and conversion time. Resize source images close to their displayed dimensions before rendering.
  • Reliability: Pin the wkhtmltopdf version and operating-system image in automated jobs. Renderer upgrades can change rasterization.
  • Quality: Test PNG and JPEG sources separately. JPEG quality can change compression artifacts but is not documented to remove borders.
  • Reproducibility: Keep HTML, CSS, assets, command-line options, and build metadata together with a failing PDF.
  • Security: If HTML loads remote assets, make network access deterministic and verify that every image URL resolves in the conversion environment.

11. Or skip the browser setup

For screenshot and PDF capture through an API, ScreenshotNeo accepts one GET request and returns a PNG, JPEG, WebP, or PDF. Its cleanup step accepts cookie and consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be disabled. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers report the page verdict and billing status.

See the ScreenshotNeo API documentation for options such as full-page capture, CSS element selection, custom CSS and JavaScript, waits, blocking, headers, cookies, user agents, PDF settings, caching, signed links, asynchronous jobs, bulk capture, and usage data.

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()));

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

12. FAQ

Is the gray edge always caused by transparency?

No. CSS, enlargement, JPEG conversion, and renderer builds are also plausible causes.

Which wkhtmltopdf version fixes the problem?

No source establishes a universal version fix. Compare recorded builds with the same reproduction.

Should I always flatten PNGs?

Only when the output background is known and the alpha test shows that compositing is involved.

Do --image-dpi or --image-quality remove borders?

They control image scaling and JPEG quality. The official documentation does not describe them as border-removal options.

What evidence should accompany a bug report?

Version, operating system, minimal HTML/CSS/JS, source image, full command, and resulting PDF.