PHPackages                             html2pdfconverter/php-client - 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. [API Development](/categories/api)
4. /
5. html2pdfconverter/php-client

ActiveLibrary[API Development](/categories/api)

html2pdfconverter/php-client
============================

PHP client for the html2pdfconverter.com SaaS API

v0.1.0(6mo ago)01MITPHPPHP &gt;=8.0CI passing

Since Nov 15Pushed 6mo agoCompare

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

READMEChangelogDependencies (2)Versions (2)Used By (0)

html2pdfconverter PHP Client
============================

[](#html2pdfconverter-php-client)

A powerful, type-safe PHP client for the [html2pdfconverter.com](https://html2pdfconverter.com) SaaS API. Convert HTML, URLs, and files to PDF with ease. Supports job polling, webhooks, and direct file downloads.

Features
--------

[](#features)

- 🚀 **Simple API** – Intuitive methods for PDF conversion
- 📄 **Multiple Input Types** – Convert HTML strings, URLs, or local files
- 💾 **Flexible Output** – Save directly to disk or get raw PDF bytes
- 🔄 **Job Polling** – Automatic polling with configurable intervals and timeouts
- 🪝 **Webhook Support** – Async job handling with webhook callbacks
- ✅ **Signature Verification** – Built-in HMAC-SHA256 webhook validation
- 🧪 **Well-tested** – Includes PHPUnit tests and GitHub Actions CI
- 📋 **PHP 8.0+** – Modern PHP with strict types

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

[](#installation)

Install via Composer:

```
composer require html2pdfconverter/php-client
```

### Requirements

[](#requirements)

- PHP &gt;= 8.0
- `guzzlehttp/guzzle` ^7.0 (automatically installed)

Quick Start
-----------

[](#quick-start)

```
require 'vendor/autoload.php';
use Html2PdfConverter\PdfClient;

// Initialize the client
$client = new PdfClient([
    'apiKey' => 'your-api-key-here'
]);

// Convert HTML to PDF and save
$result = $client->convert([
    'html' => 'Hello, PDF!',
    'saveTo' => '/tmp/output.pdf'
]);

echo "Saved to: $result\n";
```

Usage
-----

[](#usage)

### Convert HTML String

[](#convert-html-string)

```
$client = new PdfClient(['apiKey' => 'YOUR_API_KEY']);

// Save to file
$filePath = $client->convert([
    'html' => 'Hello WorldThis is a test',
    'saveTo' => './output.pdf',
    'pdfOptions' => [
        'format' => 'A4',
        'margin' => '10mm'
    ]
]);

echo "Saved to: $filePath\n";
```

### Convert from URL

[](#convert-from-url)

```
$result = $client->convert([
    'url' => 'https://example.com',
    'saveTo' => './website.pdf',
    'timeoutMs' => 60000 // 60 second timeout
]);
```

### Convert Local File

[](#convert-local-file)

```
$result = $client->convert([
    'filePath' => './document.html',
    'saveTo' => './output.pdf',
    'pdfOptions' => [
        'pageSize' => 'Letter'
    ]
]);
```

### Get Raw PDF Bytes

[](#get-raw-pdf-bytes)

```
$pdfBuffer = $client->convert([
    'html' => 'Test',
    // No 'saveTo' – returns raw buffer
]);

// Send as download
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="test.pdf"');
echo $pdfBuffer;
```

### Async Conversion with Webhook

[](#async-conversion-with-webhook)

```
$jobId = $client->convert([
    'html' => 'Async Job',
    'webhookUrl' => 'https://yourapp.com/webhook/pdf-ready',
    // Don't include 'saveTo' or polling happens immediately
]);

echo "Job ID: $jobId\n";
// You'll receive a POST to webhookUrl when complete
```

### Poll Job Status

[](#poll-job-status)

```
$jobId = 'job_abc123';

$result = $client->getJob($jobId, [
    'pollIntervalMs' => 1000,    // Check every 1 second
    'timeoutMs' => 300000,       // 5 minute timeout
    'saveTo' => './result.pdf'   // Optional: save directly
]);

echo "PDF saved to: $result\n";
```

### Verify Webhook Signature

[](#verify-webhook-signature)

```
// In your webhook endpoint handler
$client = new PdfClient([
    'apiKey' => 'YOUR_API_KEY',
    'webhookSecret' => 'your-webhook-secret'
]);

$payload = file_get_contents('php://input');
$signature = $_SERVER['HTTP_X_PDF_SERVICE_SIGNATURE'] ?? '';

try {
    $data = $client->verifyWebhook($payload, $signature);

    // $data contains:
    // {
    //   "jobId": "job_abc123",
    //   "status": "completed",
    //   "downloadUrl": "https://...",
    //   "errorMessage": null
    // }

    echo "Job completed: " . $data['jobId'] . "\n";
} catch (RuntimeException $e) {
    echo "Invalid signature: " . $e->getMessage() . "\n";
    http_response_code(401);
}
```

API Reference
-------------

[](#api-reference)

### Constructor

[](#constructor)

```
$client = new PdfClient(array $options);
```

**Options:**

- `apiKey` (string, required) – Your html2pdfconverter API key
- `baseURL` (string, optional) – Custom API endpoint (default: `https://api.html2pdfconverter.com`)
- `webhookSecret` (string, optional) – Secret for webhook signature verification

### convert()

[](#convert)

```
public function convert(array $options): string|false|resource
```

Submit a PDF conversion job and optionally wait for completion.

**Options:**

- `html` (string, optional) – HTML content to convert
- `url` (string, optional) – URL to convert
- `filePath` (string, optional) – Path to HTML file to convert
- `pdfOptions` (array, optional) – PDF generation options (format, margin, etc.)
- `webhookUrl` (string, optional) – Webhook URL for async completion notification
- `saveTo` (string, optional) – File path to save PDF (returns path on success)
- `pollIntervalMs` (int, optional) – Poll interval in milliseconds (default: 2000)
- `timeoutMs` (int, optional) – Total timeout in milliseconds (default: 300000)

**Returns:**

- When `saveTo` is provided: file path (string)
- When `saveTo` is omitted: raw PDF bytes (string/resource)
- When `webhookUrl` is provided: job ID (string) – no polling occurs

**Throws:** `InvalidArgumentException`, `RuntimeException`

### getJob()

[](#getjob)

```
public function getJob(string $jobId, array $options = []): string|false|resource
```

Poll a job until completion and retrieve the PDF.

**Options:**

- `pollIntervalMs` (int, optional) – Poll interval in milliseconds (default: 2000)
- `timeoutMs` (int, optional) – Total timeout in milliseconds (default: 900000)
- `saveTo` (string, optional) – File path to save PDF

**Returns:** File path (if `saveTo` provided) or raw PDF bytes

**Throws:** `RuntimeException` on timeout or job failure

### verifyWebhook()

[](#verifywebhook)

```
public function verifyWebhook(string $rawBody, string $signature): array
```

Verify webhook authenticity using HMAC-SHA256 signature.

**Parameters:**

- `rawBody` (string) – Raw request body from webhook
- `signature` (string) – Signature header value (format: `sha256=...`)

**Returns:** Parsed JSON payload as array

**Throws:** `RuntimeException` on invalid signature or malformed JSON

PDF Options
-----------

[](#pdf-options)

Pass custom options to the PDF generator via the `pdfOptions` parameter:

```
$client->convert([
    'html' => $html,
    'pdfOptions' => [
        'format' => 'A4',              // Page format: A4, Letter, Legal, etc.
        'margin' => '10mm',            // All margins
        'marginTop' => '20mm',         // Individual margins
        'marginBottom' => '10mm',
        'marginLeft' => '15mm',
        'marginRight' => '15mm',
        'pageSize' => 'A4',            // Alternative to 'format'
        'landscape' => false,          // Orientation
        'scale' => 1.0                 // Zoom level
    ],
    'saveTo' => './output.pdf'
]);
```

See the API documentation at [html2pdfconverter.com/docs](https://html2pdfconverter.com/docs) for all supported options.

Error Handling
--------------

[](#error-handling)

```
use Html2PdfConverter\PdfClient;

$client = new PdfClient(['apiKey' => 'YOUR_API_KEY']);

try {
    $result = $client->convert([
        'url' => 'https://example.com',
        'saveTo' => './output.pdf',
        'timeoutMs' => 30000
    ]);
    echo "Success: $result\n";
} catch (InvalidArgumentException $e) {
    // Missing required parameters
    echo "Invalid input: " . $e->getMessage() . "\n";
} catch (RuntimeException $e) {
    // API error, timeout, or job failed
    echo "Conversion failed: " . $e->getMessage() . "\n";
}
```

Examples
--------

[](#examples)

See the `examples/` directory for complete working examples:

```
# Run the basic example
php examples/convert.php
```

Testing
-------

[](#testing)

Run PHPUnit tests:

```
composer install --dev
vendor/bin/phpunit
```

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

[](#development)

Clone the repository and install dependencies:

```
git clone https://github.com/html2pdfconverter/html2pdfconverter-php.git
cd html2pdfconverter-php
composer install
vendor/bin/phpunit
```

License
-------

[](#license)

MIT License – see LICENSE file for details.

Support
-------

[](#support)

- 📖 [API Documentation](https://html2pdfconverter.com/docs)
- 💬 [GitHub Issues](https://github.com/html2pdfconverter/html2pdfconverter-php/issues)
- 📧 [Contact Support](https://html2pdfconverter.com/support)

###  Health Score

27

—

LowBetter than 49% of packages

Maintenance68

Regular maintenance activity

Popularity1

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity30

Early-stage or recently created project

 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

Unknown

Total

1

Last Release

184d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/33c92350513224ece046ee0236ff9677b5a7135c3bb5b2e662a55d09edc251bc?d=identicon)[html2pdfconverter](/maintainers/html2pdfconverter)

---

Top Contributors

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

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[tencentcloud/tencentcloud-sdk-php

TencentCloudApi php sdk

3731.2M42](/packages/tencentcloud-tencentcloud-sdk-php)[convertkit/convertkitapi

Kit PHP SDK for the Kit API

2167.1k1](/packages/convertkit-convertkitapi)[mapado/rest-client-sdk

Rest Client SDK for hydra API

1125.9k2](/packages/mapado-rest-client-sdk)

PHPackages © 2026

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