PHPackages                             html2img/html2img-php - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [HTTP &amp; Networking](/categories/http)
4. /
5. html2img/html2img-php

ActiveLibrary[HTTP &amp; Networking](/categories/http)

html2img/html2img-php
=====================

Official PHP SDK for the html2img HTML-to-image API: render HTML or CSS to PNG, screenshot live URLs, and generate images from templates, built on Guzzle.

v1.1.0(1w ago)026↓78.4%2MITPHPPHP ^8.3CI passing

Since Jun 7Pushed 1w agoCompare

[ Source](https://github.com/html2img/html2img-php)[ Packagist](https://packagist.org/packages/html2img/html2img-php)[ Docs](https://html2img.com)[ RSS](/packages/html2img-html2img-php/feed)WikiDiscussions main Synced 1w ago

READMEChangelog (1)Dependencies (12)Versions (4)Used By (2)

[![html2img — HTML to image API, rendered in real Chrome](https://camo.githubusercontent.com/f56458281ca597b90aa9a057c211e05fc011bf71c8525b908f6cccd7c992d061/68747470733a2f2f68746d6c32696d672e636f6d2f6f672d696d6167652e706e67)](https://html2img.com)

html2img PHP client
===================

[](#html2img-php-client)

[![Packagist Version](https://camo.githubusercontent.com/f27ad05acaf405a44bc4a5b42a6936a8807ca87b1685949abf469c48bfd73cba/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f68746d6c32696d672f68746d6c32696d672d706870)](https://packagist.org/packages/html2img/html2img-php)[![PHP Version](https://camo.githubusercontent.com/5503c36687f3f1167aa57369a0b272819f81e0195e8274c1f7eb72d16feccbbc/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f68746d6c32696d672f68746d6c32696d672d706870)](https://packagist.org/packages/html2img/html2img-php)[![Total Downloads](https://camo.githubusercontent.com/a53221d0dbd90e9bb6de38bf9d4d215119408500344c0f90e3c25d119c95bc5e/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f68746d6c32696d672f68746d6c32696d672d706870)](https://packagist.org/packages/html2img/html2img-php)[![License](https://camo.githubusercontent.com/3b57f87751cd9cf31e8738fb109805fd380ff755d54737450c8186d93a2eed49/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f68746d6c32696d672f68746d6c32696d672d706870)](LICENSE)

The official PHP client for the [HTML to Image API](https://html2img.com). Turn HTML and CSS into images, capture screenshots of live URLs, and render named templates, all returning a typed response object.

Every render runs in real Chrome, so flexbox, grid, custom properties, web fonts and inline JavaScript behave exactly as they do in the browser. The package is framework-agnostic and built on Guzzle, so it works in plain PHP and inside any framework. The full API reference lives in the [documentation](https://html2img.com/docs).

What you can build
------------------

[](#what-you-can-build)

- **Open Graph and social images**, generated per page or post. See the [Open Graph image template](https://html2img.com/templates/open-graph-image) and [Twitter/X post template](https://html2img.com/templates/twitter-post).
- **Business documents** such as [invoices](https://html2img.com/templates/invoice-image), [receipts](https://html2img.com/templates/receipt-image), [event tickets](https://html2img.com/templates/event-ticket) and [certificates](https://html2img.com/templates/certificate-of-completion).
- **Developer assets** such as [code screenshots](https://html2img.com/templates/code-screenshot) and [GitHub social previews](https://html2img.com/templates/github-social-preview).
- **URL screenshots**, full page or cropped to a single element, with CSS injection to hide cookie banners and chat widgets before capture.

Browse the [full template library](https://html2img.com/templates), or try the no-signup [browser tools](https://html2img.com/tools) to see the output before you write any code.

Requirements
------------

[](#requirements)

- PHP 8.3 or newer
- A html2img API key, issued per account from your [dashboard](https://app.html2img.com/register)

Installation
------------

[](#installation)

```
composer require html2img/html2img-php
```

Quick start
-----------

[](#quick-start)

```
use Html2img\Html2imgClient;
use Html2img\Request\HtmlRequest;

$client = new Html2imgClient('your-api-key');

$response = $client->html(new HtmlRequest(
    html: 'Hello',
    width: 1200,
    height: 630,
));

echo $response->url; // https://i.html2img.com/abc123def456.png
```

The API returns a JSON envelope containing the CDN URL of the generated image, not the raw bytes, so you can cache and re-serve it from your own infrastructure. New to the API? Start with the [getting started guide](https://html2img.com/docs/getting-started).

Configuration
-------------

[](#configuration)

The constructor takes the API key plus optional overrides:

```
use Html2img\Html2imgClient;

$client = new Html2imgClient(
    apiKey: 'your-api-key',
    baseUri: 'https://app.html2img.com', // default
    timeout: 35.0,                        // seconds, default
);
```

Authentication is sent on every request as the `X-API-Key` header. See the [authentication docs](https://html2img.com/docs/authentication) for issuing and rotating keys.

### Injecting your own Guzzle client

[](#injecting-your-own-guzzle-client)

Pass a pre-configured `GuzzleHttp\ClientInterface` to reuse your own middleware, retry strategy or logging. The SDK still adds the `X-API-Key`, `Accept` and `Content-Type` headers on every request.

```
use GuzzleHttp\Client;
use Html2img\Html2imgClient;

$guzzle = new Client([
    'base_uri' => 'https://app.html2img.com',
    'timeout' => 60,
    // your own handler stack, middleware, proxy settings, etc.
]);

$client = new Html2imgClient('your-api-key', httpClient: $guzzle);
```

Usage
-----

[](#usage)

### Render HTML

[](#render-html)

`POST /api/html`. Send a complete HTML document and get back an image of the rendered result. Inline your CSS in a `` block, or reference remote stylesheets and web fonts via `` tags in the document head. See the [`html` parameter docs](https://html2img.com/docs/parameters/html) for the full input.

```
use Html2img\Enum\Format;
use Html2img\Request\HtmlRequest;

$response = $client->html(new HtmlRequest(
    html: $document,
    css: 'body { background: #0f172a; color: #fff; }', // injected after load
    width: 794,
    fullpage: true,
    dpi: 2,          // retina
    format: Format::Png,
));
```

### Capture a screenshot

[](#capture-a-screenshot)

`POST /api/screenshot`. Fetch a public URL in a real browser and capture it. Use `selector` to crop to a single element, and `css` to hide cookie banners or chat widgets before the capture. See the [`url` parameter docs](https://html2img.com/docs/parameters/url).

```
use Html2img\Request\ScreenshotRequest;

$response = $client->screenshot(new ScreenshotRequest(
    url: 'https://example.com',
    width: 1200,
    height: 630,
    selector: '#hero',
    css: '.cookie-banner, .intercom-launcher { display: none !important; }',
    dpi: 2,
));
```

### Generate a PDF

[](#generate-a-pdf)

Set `format` to `Format::Pdf` on either request and the render comes back as an A4 portrait vector PDF instead of a PNG: text stays selectable and searchable, webfonts are embedded and long content paginates automatically. The API ignores `width`, `height`, `dpi`, `fullpage` and `selector` in PDF mode, and the response `url` points at a `.pdf` file. One credit, the same as an image. See the [`format` parameter docs](https://html2img.com/docs/parameters/format/).

```
use Html2img\Enum\Format;
use Html2img\Request\HtmlRequest;

$response = $client->html(new HtmlRequest(
    html: 'Invoice #1042Due within 30 days.',
    format: Format::Pdf,
));

echo $response->url; // https://i.html2img.com/....pdf
```

### Render a template

[](#render-a-template)

`POST /api/v1/templates/{slug}`. Render one of your named templates from a JSON data payload. The data is validated server-side per template. [Browse the templates](https://html2img.com/templates) to find a slug. Templates output PNG only; `format` is not available on template renders.

```
$response = $client->template('invoice', [
    'number' => 1042,
    'amount' => '$240.00',
    'due_date' => '2026-07-01',
]);

echo $response->template; // invoice
echo $response->url;
```

Options
-------

[](#options)

Both `HtmlRequest` and `ScreenshotRequest` accept the following. Any option left null is omitted from the request, so the server applies its own default. The complete reference is in the [parameter docs](https://html2img.com/docs/parameters).

OptionTypeNotes`css`stringExtra CSS injected after the page loads.`width`intViewport width in CSS pixels (1 to 5000).`height`intViewport height in CSS pixels (1 to 5000). Ignored when `fullpage` is true.`fullpage`boolCapture the full scroll length instead of the viewport.`dpi`intDevice pixel ratio, 1 to 4. Use 2 for retina.`webhookUrl`stringSwitch to async delivery (see below).`msDelay`intWait this many milliseconds after load before capturing (1 to 5000).`waitForSelector`stringWait until this CSS selector appears before capturing.`format``Format``Format::Png` (default) or `Format::Pdf`. PDF output is A4 portrait and ignores the sizing options above.`ScreenshotRequest` also accepts `selector` (string) to crop the capture to a single element. `HtmlRequest` does not, since you control the markup.

Custom fonts are loaded by referencing them with `` tags in your HTML document head, or by linking a web font from your captured page.

The response
------------

[](#the-response)

Every method returns a readonly `Html2img\Response\RenderResponse`:

```
$response->success;          // bool
$response->id;               // string|null, the render id
$response->url;              // string|null, the CDN URL of the image
$response->creditsRemaining; // int|null, credits left after this call
$response->status;           // string|null, "processing" for async jobs
$response->message;          // string|null
$response->template;         // string|null, the template slug, when applicable
$response->isProcessing();   // bool
$response->raw();            // array, the full decoded JSON payload
```

### Asynchronous delivery

[](#asynchronous-delivery)

Synchronous requests have a 30 second budget. For captures likely to exceed it, pass a `webhookUrl`. The API responds immediately with `status: "processing"`and `url: null`, then POSTs the final image URL to your endpoint once rendering finishes. See the [`webhook_url` docs](https://html2img.com/docs/parameters/webhook-url).

```
$response = $client->screenshot(new ScreenshotRequest(
    url: 'https://example.com/long-report',
    fullpage: true,
    webhookUrl: 'https://your-app.example.com/hooks/html2img',
));

if ($response->isProcessing()) {
    // The final URL will arrive at your webhook, not on this response.
}
```

Error handling
--------------

[](#error-handling)

Every failure throws an `Html2img\Exception\Html2imgException`. Catch that single type to handle any error, or catch a specific subclass. No raw Guzzle exception escapes the client.

```
use Html2img\Exception\Html2imgException;
use Html2img\Exception\ValidationException;
use Html2img\Exception\InsufficientCreditsException;

try {
    $response = $client->html(new HtmlRequest(html: $document));
} catch (ValidationException $e) {
    // 400 or 422: inspect the per-field messages
    foreach ($e->details() as $field => $messages) {
        // ...
    }
} catch (InsufficientCreditsException $e) {
    // 402: out of credits
    $left = $e->creditsRemaining();
} catch (Html2imgException $e) {
    // anything else
    $e->statusCode(); // int|null
    $e->errorCode();  // string|null, the API "code" field
    $e->payload();    // array, the decoded body
}
```

ExceptionWhen`AuthenticationException`401, missing or invalid API key.`InsufficientCreditsException`402, no credits remaining.`NotSubscribedException`403, no active subscription.`NotFoundException`404, for example an unknown template slug.`ValidationException`400 or 422, with `details()` per field.`RateLimitException`429, rate or quota exceeded.`TimeoutException`504, the synchronous render budget was exceeded.`ServerException`5xx, an unexpected renderer error.`ConnectionException`the request never reached a response.`Html2imgException`base type for all of the above.Other languages
---------------

[](#other-languages)

Anything that can make an HTTP request works with the API. There are worked guides for [Laravel](https://html2img.com/docs/usage/laravel), [Ruby on Rails](https://html2img.com/docs/usage/rails), [Python](https://html2img.com/docs/usage/python), [JavaScript and Node.js](https://html2img.com/docs/usage/javascript), [React](https://html2img.com/docs/usage/react) and [Vue](https://html2img.com/docs/usage/vue).

Development
-----------

[](#development)

This package uses [ddev](https://ddev.com) for a containerised PHP environment. It is optional, and you can use vanilla PHP or whatever you use for local dev if you prefer.

```
ddev composer install
ddev exec vendor/bin/pest      # tests
ddev exec vendor/bin/phpstan analyse
ddev exec vendor/bin/pint --test
```

Links
-----

[](#links)

[Website](https://html2img.com) · [Documentation](https://html2img.com/docs) · [Templates](https://html2img.com/templates) · [Tools](https://html2img.com/tools) · [Features](https://html2img.com/features) · [Comparisons](https://html2img.com/compare) · [Articles](https://html2img.com/articles) · [Pricing](https://html2img.com/pricing)

Licence
-------

[](#licence)

MIT. See [LICENSE](LICENSE).

###  Health Score

44

—

FairBetter than 90% of packages

Maintenance98

Actively maintained with recent releases

Popularity8

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity51

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~18 days

Total

3

Last Release

10d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/291512758?v=4)[html2img](/maintainers/html2img)[@html2img](https://github.com/html2img)

---

Top Contributors

[![mikemike](https://avatars.githubusercontent.com/u/91627?v=4)](https://github.com/mikemike "mikemike (6 commits)")

---

Tags

api-clienthtml-to-imagehtml-to-image-converterimage-generationog-imageog-image-generatorphpscreenshot-apipdfGuzzlescreenshotapi clientopen-graphhtml-to-pdfhtml to imagehtml to pngURL to Imageog-imageimage-generationhtml2imgscreenshot-api

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/html2img-html2img-php/health.svg)

```
[![Health](https://phpackages.com/badges/html2img-html2img-php/health.svg)](https://phpackages.com/packages/html2img-html2img-php)
```

###  Alternatives

[guzzlehttp/oauth-subscriber

Guzzle OAuth 1.0 subscriber

24215.4M156](/packages/guzzlehttp-oauth-subscriber)[eslazarev/wildberries-sdk

Wildberries OpenAPI clients (generated).

293.1k](/packages/eslazarev-wildberries-sdk)[graham-campbell/guzzle-factory

Provides A Simple Guzzle Factory With Good Defaults

927.0M55](/packages/graham-campbell-guzzle-factory)[anam/phantommagick

PhantomMagick provides a simple API to ease the process of converting HTML to PDF or images

160463.6k2](/packages/anam-phantommagick)[sunchayn/nimbus

A Laravel package providing an in-browser API client with automatic schema generation, live validation, and built-in authentication with a touch of Laravel-tailored magic for effortless API testing.

33741.3k](/packages/sunchayn-nimbus)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
