ScreenshotNeo

BlogHow-to

How to Convert HTML to JPG with wkhtmltoimage in PHP for Indian Websites

Convert generated HTML to JPG in PHP with wkhtmltoimage. Configure size, quality, scripts, fonts, and UTF-8 for Indian websites, with runnable examples.

By the ScreenshotNeo team4 October 202610 min read

To convert generated HTML to a JPG in PHP with wkhtmltoimage, install a build compatible with your server, then give it an HTML input and a .jpg output path. You can run the command-line tool from PHP, or use the wkhtmltox PHP extension if it is installed and compatible with your PHP runtime and operating system. For Indian websites, check UTF-8 encoding, installed fonts, and representative output in the actual deployment environment.

This guide covers local HTML files and the PHP binding, image size and quality, JavaScript timing, Indian-language rendering, security, operational checks, and common failures. The cited documentation does not certify accurate output for a particular Indian script or font; inspect your own rendered files.

1. Choose a PHP integration route

Route Use it when Check first
Run the wkhtmltoimage executable from PHP Your server can install and execute a compatible binary. Binary and OS compatibility, writable output directory, process exit status, and safe argument handling.
Use the wkhtmltox PHP image converter The extension and its native dependencies are available for your PHP and operating system. Extension availability, runtime compatibility, output settings, and native libraries.

Neither route is universally easier. The project publishes distribution-specific packages and notes that runtime behavior depends on libraries including libc, fontconfig, and freetype. A static Qt build can still depend on system packages, and Alpine uses musl rather than glibc. Confirm the package and its dependencies for the exact host or container where PHP runs. See the wkhtmltopdf project downloads and compatibility notes and the PHP wkhtmltox extension documentation.

2. Install and check wkhtmltoimage

Install a package appropriate for your operating system and architecture using the project’s published packages or your distribution’s package manager. Then check that the executable is on the PHP process’s PATH and can run under the same user and environment as your application:

command -v wkhtmltoimage
wkhtmltoimage --version
wkhtmltoimage --extended-help

The project identifies 0.12.6 as its stable series and dates that release June 11, 2020. Its age and packaging notes make compatibility and security review relevant before using it in a new production service. Verify the installed build and its dependencies; do not assume a development machine’s installation matches production. Project release and package information.

3. Convert HTML to JPG with the command line

The basic command accepts an input file and an output file. Set the output format to JPEG explicitly; the width and quality below are examples to adjust for your layout and file-size needs.

wkhtmltoimage --format jpg --quality 90 --width 1200 /path/to/page.html /path/to/page.jpg

The tool documents the input/output form and flags including --format, --quality, and --width. JPEG quality accepts an integer from 0 through 100. The documentation cautions that width is a guide unless smart width is disabled, so inspect the actual output dimensions and composition. wkhtmltoimage(1) options.

4. Run the converter safely from PHP

Use a process API that accepts an argument array, rather than concatenating HTML paths or user input into a shell command. The following example uses Symfony Process. Add it to the application with Composer (composer require symfony/process), then pass a controlled input file and a server-generated output path.

<?php
require __DIR__ . '/vendor/autoload.php';

use Symfony\Component\Process\Process;

$input = __DIR__ . '/rendered/page.html';
$output = __DIR__ . '/rendered/page.jpg';
$binary = '/usr/bin/wkhtmltoimage';

if (!is_file($input) || !is_readable($input)) {
    throw new RuntimeException('HTML input is missing or unreadable.');
}
if (!is_executable($binary)) {
    throw new RuntimeException('wkhtmltoimage is missing or not executable.');
}
if (!is_dir(dirname($output)) || !is_writable(dirname($output))) {
    throw new RuntimeException('Output directory is missing or not writable.');
}

$process = new Process([
    $binary,
    '--format', 'jpg',
    '--quality', '90',
    '--width', '1200',
    $input,
    $output,
]);
$process->setTimeout(60);
$process->run();

if (!$process->isSuccessful()) {
    throw new RuntimeException('wkhtmltoimage failed: ' . $process->getErrorOutput());
}
if (!is_file($output) || filesize($output) === 0) {
    throw new RuntimeException('Conversion finished without a non-empty output file.');
}

$info = getimagesize($output);
if ($info === false || $info['mime'] !== 'image/jpeg') {
    throw new RuntimeException('Output is not a valid JPEG image.');
}

echo $output;

Choose a timeout and output-size policy suitable for your application. Keep output paths application-controlled, and do not accept arbitrary filesystem paths from a request. This example reports stderr on failure; production logging should avoid recording sensitive HTML, credentials, or page contents.

5. Use the PHP wkhtmltox image converter

If the wkhtmltox extension is installed and compatible with the deployed runtime, its image converter can set JPEG format and rendering options directly. This is an API example, not a guarantee that the extension is available in a particular environment:

<?php
$html = file_get_contents(__DIR__ . '/rendered/page.html');
if ($html === false) {
    throw new RuntimeException('Could not read HTML input.');
}

$converter = new wkhtmltox\Image\Converter($html, [
    'out' => __DIR__ . '/rendered/page.jpg',
    'fmt' => 'jpg',
    'screenWidth' => 1200,
    'quality' => 90,
    'load.jsdelay' => 500,
]);
$converter->convert();

The PHP manual documents the converter, output path, fmt, screen width, JPEG quality, and JavaScript delay. It documents a default JPEG quality of 94. Set the format and quality explicitly when reproducible output matters, and check the resulting file. Consult the PHP image converter constructor reference.

6. Set capture dimensions, crop, and quality

  • Width: Set a viewport appropriate to the page. The PHP binding offers screenWidth; the CLI has --width. A wider viewport can change responsive layout, so match the intended display context.
  • Crop: The PHP binding exposes crop coordinates and dimensions such as left, top, width, and height; the CLI provides crop options. Use these when the desired JPG should show only a defined region. Check the rendered result when content height or responsive layout varies.
  • Quality: Choose JPEG quality for the balance between compression and visible artifacts. The CLI accepts 0–100; the PHP manual lists 94 as its default. The examples use 90 as an illustrative setting, not a measured optimum.
  • Format and destination: Use jpg and a .jpg output path consistently. Check the file’s actual MIME type rather than relying on its filename.

JPEG does not preserve transparency. If the page needs transparent pixels, choose a format and workflow that support them rather than expecting a JPG to retain transparency.

7. Wait for page scripts and resources

A page that depends on JavaScript may not be ready when rendering starts. The PHP binding has load.jsdelay; the CLI can wait for a specified window.status value and can run additional scripts. A fixed delay is a fallback: it may wait longer than needed or still be too short when rendering is slow. If you control the page code, signal readiness explicitly and configure the converter to wait for that signal where supported. Review the PHP loading settings and CLI JavaScript and loading options.

External stylesheets, images, and fonts must be reachable from the conversion process. A browser on your workstation may have access that the PHP server does not. Check network rules, DNS, authentication, and asset URLs from the rendering host. Keep local file access constrained; the PHP binding exposes a setting to block local files.

8. Check UTF-8 and Indian-language fonts

The title’s Indian website use case calls for deployment checks, not an assumption that wkhtmltoimage automatically has the required fonts or script shaping. The PHP manual documents UTF-8 as the default encoding when none is specified, but set encoding explicitly in the HTML and ensure the server has the fonts the page actually uses. The project notes that fontconfig and freetype affect runtime behavior. Neither reference certifies fidelity for a particular Indian language or font.

<!doctype html>
<html lang="hi">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    body { font-family: sans-serif; }
  </style>
</head>
<body>
  <p>नमस्ते — mixed Latin and Hindi text</p>
</body>
</html>

For each language and deployment image, inspect representative text in the generated JPG. Include conjuncts, vowel marks, punctuation, mixed Latin and Indian-script content, long names and addresses, and localized labels. Confirm that the page’s actual fonts are installed and available to the renderer; a CSS family name alone does not install a font. Check whether external font files can be fetched from the server.

9. Security, reliability, performance, and cost

Security

The wkhtmltopdf project warns against converting untrusted HTML: its downloads page says untrusted HTML or JavaScript can lead to complete server takeover, and advises sanitizing user-supplied content. Treat that as a serious risk. Sanitization alone is not a complete sandbox. Keep conversion inputs controlled, restrict network and local-file access where possible, run with limited permissions, bound execution time and resource use, and avoid passing request data through a shell. See the project warning.

Reliability

Check the process exit status, stderr, output existence, non-zero file size, and image MIME type. Record the executable version and deployment image so a change in native libraries or fonts can be investigated. Test using the same user, filesystem permissions, network access, and container image as production. The project’s packaging notes make host compatibility a practical concern; the sources provide no universal compatibility rate.

Performance and cost

The cited references provide no conversion-time benchmarks. Rendering work depends on page complexity, scripts, images, fonts, and network resources. Avoid needless fixed waits, set a timeout, limit concurrency and input size according to your service needs, and cache output when the source and rendering settings have not changed. The binary itself is available through the project’s packages; operational costs depend on your own compute, storage, and maintenance. No source here supports a comparative cost or speed claim.

10. Troubleshoot common failures

Symptom Likely cause What to check
wkhtmltoimage: command not found Binary is absent or not on the PHP process’s PATH. Install a package for the host; use its full executable path and check permissions as the PHP service user.
Executable starts locally but fails in production Package, architecture, libc, or native dependency mismatch. Check the project’s distribution-specific package notes and run --version in the production image.
Non-zero process exit or no output file Bad input path, unwritable destination, unsupported option, missing library, or page load failure. Capture exit status and stderr; verify paths, permissions, binary version, and the input outside PHP.
Image is blank or missing page content Scripts or external assets were not ready or reachable. Check the page from the renderer’s environment; wait for a readiness signal or adjust the delay; verify network access and asset URLs.
Text appears as boxes or the wrong glyphs Required fonts are absent, unavailable, or not selected by the page. Install and verify the intended fonts in the server image, then render representative script samples there.
Indian-language text is garbled Encoding mismatch or font/rendering behavior differs in the deployment. Use UTF-8 consistently, include the charset declaration, verify font availability, and inspect script-specific samples.
Layout is unexpectedly wide or cropped Viewport width, smart width, crop values, or responsive CSS alter composition. Set width and crop deliberately; compare against the intended viewport and inspect actual output dimensions.
JPG looks blocky or is much larger than expected JPEG quality or image dimensions do not fit the use case. Adjust quality and dimensions, then review both file size and visible artifacts for representative pages.
Conversion hangs or is terminated Slow resources, scripts that never finish, or excessive page complexity. Set a process timeout, inspect resource loading and script readiness, and bound concurrency and input size.

11. Or skip the browser setup

If you need a website screenshot without installing and maintaining a rendering binary, ScreenshotNeo is a website screenshot API and MCP server from Yorker Media. One GET request returns a PNG, JPEG, WebP, or PDF. The API parameters and options are documented at ScreenshotNeo docs.

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

ScreenshotNeo accepts cookie and consent banners like a visitor and removes 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 response headers report the page verdict and billing status. Its MCP server gives AI agents tools for screenshots, page information, and PDF capture. The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000. Every feature is on every plan. Sign up for 1,000 free screenshots a month, with no card.

12. FAQ

Can I convert a remote Indian website URL instead of a local HTML file?

The CLI accepts an input file or URL. For a PHP application, you can provide a URL that the rendering host can reach, but access to authenticated or private pages requires careful handling of credentials and network access.

Does a JPG preserve a transparent page background?

No. JPEG does not support transparency. Use a format with transparency when that is a requirement.

Is there a guaranteed Hindi, Tamil, or Bengali rendering setting?

The cited documentation gives no such guarantee. Set UTF-8, make the page’s fonts available to the renderer, and verify output using representative text in the deployment environment.

What JPEG quality should I choose?

There is no universally correct value in the cited references. The PHP binding documents a default of 94 and the CLI accepts 0–100. Compare output quality and file size for your own pages.

Sources