PHPackages                             dokmatiq/docgen-sdk - 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. [Payment Processing](/categories/payments)
4. /
5. dokmatiq/docgen-sdk

ActiveLibrary[Payment Processing](/categories/payments)

dokmatiq/docgen-sdk
===================

PHP SDK for the Dokmatiq DocGen document generation API

v0.1.0(1mo ago)00MITPHPPHP &gt;=8.1

Since Apr 25Pushed 3w agoCompare

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

READMEChangelogDependenciesVersions (2)Used By (0)

DocGen PHP SDK
==============

[](#docgen-php-sdk)

[![CI](https://github.com/dokmatiq/docgen-sdks/actions/workflows/ci-php.yml/badge.svg)](https://github.com/dokmatiq/docgen-sdks/actions/workflows/ci-php.yml)

Official PHP SDK for the [Dokmatiq DocGen](https://dokmatiq.com) document generation API.

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

[](#requirements)

- PHP 8.1+
- ext-curl
- ext-json

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

[](#installation)

```
composer require dokmatiq/docgen-sdk
```

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

[](#quick-start)

```
use Dokmatiq\DocGen\DocGen;

$dg = new DocGen('your-api-key');

// HTML to PDF
$pdf = $dg->htmlToPdf('Hello, World!');
file_put_contents('hello.pdf', $pdf);

// Markdown to PDF
$pdf = $dg->markdownToPdf('# Report\n\nGenerated with DocGen.');
file_put_contents('report.pdf', $pdf);
```

Fluent Builder API
------------------

[](#fluent-builder-api)

```
use Dokmatiq\DocGen\Model\WatermarkConfig;

$pdf = $dg->document()
    ->html('Rechnung {{nr}}')
    ->template('invoice.odt')
    ->field('nr', 'RE-2026-001')
    ->field('datum', '12.04.2026')
    ->watermark('ENTWURF')
    ->asPdf()
    ->generate();
```

### With images, QR codes, and tables

[](#with-images-qr-codes-and-tables)

```
use Dokmatiq\DocGen\Model\ColumnDef;
use Dokmatiq\DocGen\Model\TableData;

$pdf = $dg->document()
    ->html('Order {{nr}}')
    ->field('nr', 'B-001')
    ->image('logo', 'logo.png', width: 200)
    ->qrCode('payment', 'BCD\n002\n1\nSCT\n...', size: 150)
    ->table('items', new TableData(
        columns: [new ColumnDef('Artikel', 80), new ColumnDef('Preis', 30)],
        rows: [['Widget', '9.99'], ['Gadget', '24.99']],
    ))
    ->asPdf()
    ->generate();
```

### Watermark with styling

[](#watermark-with-styling)

```
$pdf = $dg->document()
    ->html('Draft')
    ->watermark(new WatermarkConfig(
        text: 'CONFIDENTIAL',
        fontSize: 60,
        opacity: 0.15,
        color: '#FF0000',
    ))
    ->asPdf()
    ->generate();
```

Sub-Clients
-----------

[](#sub-clients)

All API endpoints are accessible through typed sub-clients:

```
// Templates
$dg->templates->upload('invoice.odt');
$dg->templates->list();
$dg->templates->delete('invoice.odt');

// Fonts
$dg->fonts->upload('custom-font.ttf');

// PDF Forms
$fields = $dg->pdfForms->inspectFields('form.pdf');
$filled = $dg->pdfForms->fillForm('form.pdf', ['name' => 'John Doe']);

// Digital Signatures
$dg->signatures->uploadCert('cert.p12', 'password', 'my-cert');
$signed = $dg->signatures->sign('document.pdf', 'my-cert', reason: 'Approved');
$result = $dg->signatures->verify('signed.pdf');

// PDF Tools
$merged = $dg->pdfTools->merge(['a.pdf', 'b.pdf']);
$parts  = $dg->pdfTools->split('document.pdf', ['1-3', '4-6']);
$text   = $dg->pdfTools->extractText('document.pdf');
$pdfa   = $dg->pdfTools->toPdfA('document.pdf');

// Preview
$png   = $dg->preview->previewPage('document.pdf', page: 1, dpi: 300);
$pages = $dg->preview->previewPages('document.pdf', maxPages: 5);
$count = $dg->preview->pageCount('document.pdf');

// ZUGFeRD
$zugferd  = $dg->zugferd->embed('invoice.pdf', $invoiceData);
$extracted = $dg->zugferd->extract('zugferd.pdf');
$valid    = $dg->zugferd->validate('zugferd.pdf');

// XRechnung
$xml = $dg->xrechnung->generate($invoiceData);
$parsed = $dg->xrechnung->parse($xml);
$valid  = $dg->xrechnung->validate($xml);
```

Invoice Builder (ZUGFeRD / XRechnung)
-------------------------------------

[](#invoice-builder-zugferd--xrechnung)

```
use Dokmatiq\DocGen\Model\BankAccount;
use Dokmatiq\DocGen\Model\InvoiceItem;
use Dokmatiq\DocGen\Model\InvoiceUnit;
use Dokmatiq\DocGen\Model\Party;

$invoice = $dg->invoice()
    ->number('RE-2026-001')
    ->date('2026-04-12')
    ->seller(new Party('ACME GmbH', 'Musterstr. 1', '10115', 'Berlin'))
    ->buyer(new Party('Kunde AG', 'Kundenweg 5', '20095', 'Hamburg'))
    ->item(new InvoiceItem('Beratung', 120.0, quantity: 8, unit: InvoiceUnit::HOUR))
    ->item(new InvoiceItem('Reisekosten', 350.0))
    ->bank(new BankAccount('DE89370400440532013000'))
    ->paymentTerms('Zahlbar innerhalb 14 Tagen')
    ->build();

// Embed in PDF
$zugferdPdf = $dg->zugferd->embed('invoice.pdf', $invoice);

// Or generate XRechnung XML
$xml = $dg->xrechnung->generate($invoice);
```

Multi-Part Documents (Compose)
------------------------------

[](#multi-part-documents-compose)

```
$pdf = $dg->compose()
    ->htmlPart('Cover Page')
    ->htmlPart('Chapter 1Content...')
    ->markdownPart('## Chapter 2\n\nMore content...')
    ->watermark('DRAFT')
    ->asPdf()
    ->generate();
```

Async Generation
----------------

[](#async-generation)

```
$job = $dg->document()
    ->html('Large Report')
    ->asPdf()
    ->generateAsync();

echo "Job started: {$job->jobId}\n";

// Poll until complete
$pdf = $dg->documents->waitForJob($job->jobId, pollInterval: 2.0, timeout: 300.0);
file_put_contents('report.pdf', $pdf);
```

Webhook Verification
--------------------

[](#webhook-verification)

```
use Dokmatiq\DocGen\Webhook\WebhookVerifier;

$verifier = new WebhookVerifier('your-webhook-secret');

// In your webhook handler:
$body = file_get_contents('php://input');
$signature = $_SERVER['HTTP_X_DOCGEN_SIGNATURE'] ?? '';

$payload = $verifier->verify($body, $signature);
echo "Job {$payload->jobId} completed with status: {$payload->status}\n";
```

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

[](#error-handling)

```
use Dokmatiq\DocGen\Exception\ValidationException;
use Dokmatiq\DocGen\Exception\AuthenticationException;
use Dokmatiq\DocGen\Exception\RateLimitException;

try {
    $pdf = $dg->htmlToPdf('Test');
} catch (ValidationException $e) {
    echo "Validation: {$e->getMessage()}\n";
    print_r($e->fieldErrors);     // Field-level errors
    echo $e->hint . "\n";         // Suggestion
} catch (AuthenticationException $e) {
    echo "Auth failed: {$e->getMessage()}\n";
} catch (RateLimitException $e) {
    echo "Rate limited. Retry after: {$e->retryAfter}s\n";
}
```

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

[](#configuration)

```
$dg = new DocGen(
    apiKey: 'your-api-key',
    baseUrl: 'https://api.dokmatiq.com',  // Custom base URL
    timeout: 120,                          // Request timeout in seconds
    maxRetries: 3,                         // Max retry attempts
);
```

Excel Workbooks
---------------

[](#excel-workbooks)

```
// Generate XLSX from structured data
$xlsx = $dg->excel->generate([
    'sheets' => [[
        'name' => 'Sales',
        'columns' => [
            ['header' => 'Month', 'width' => 15],
            ['header' => 'Revenue', 'width' => 12, 'format' => '#,##0.00 €'],
        ],
        'rows' => [
            ['values' => ['January', 42500.0]],
            ['values' => ['February', 38900.0]],
        ],
    ]],
]);
file_put_contents('sales.xlsx', $xlsx);

// CSV → XLSX
$xlsx = $dg->excel->fromCsv($csvContent);

// XLSX → JSON
$data = $dg->excel->toJson($excelBase64);
```

Receipt Recognition (AI)
------------------------

[](#receipt-recognition-ai)

Extract structured data from receipts, tickets, and invoices using AI vision:

```
// Extract data from a receipt image
$result = $dg->receipts->extract('/path/to/kassenbeleg.jpg');
echo $result['receiptData']['totalAmount'];   // 42.50
echo $result['receiptData']['receiptType'];    // "cash_receipt"
echo $result['receiptData']['skr03Account'];   // "4650"

// Export as DATEV-compatible CSV
$csv = $dg->receipts->exportCsv([$result['receiptData']]);

// Async extraction with webhook
$job = $dg->receipts->extractAsync('/path/to/beleg.jpg',
    callbackUrl: 'https://my-app.com/webhooks/receipts',
    callbackSecret: 'my-secret',
);
```

> **Note:** Requires AI processing consent in the [Developer Portal](https://developer.dokmatiq.com) settings (GDPR).

File Input
----------

[](#file-input)

All methods that accept PDF/file input support both file paths and raw bytes:

```
// File path
$text = $dg->pdfTools->extractText('/path/to/document.pdf');

// Raw bytes (e.g. from upload)
$text = $dg->pdfTools->extractText($uploadedFileContent);
```

License
-------

[](#license)

See [LICENSE](../LICENSE) for details.

###  Health Score

34

—

LowBetter than 75% of packages

Maintenance93

Actively maintained with recent releases

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity32

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

45d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/54bfcf9d733b1bb240413ff7847b44b9151bdce1f4d79252e9959bd30e488225?d=identicon)[OliverLieven](/maintainers/OliverLieven)

---

Top Contributors

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

---

Tags

pdfinvoiceZUGFeRDxrechnungdocument generationdocgendokmatiq

### Embed Badge

![Health badge](/badges/dokmatiq-docgen-sdk/health.svg)

```
[![Health](https://phpackages.com/badges/dokmatiq-docgen-sdk/health.svg)](https://phpackages.com/packages/dokmatiq-docgen-sdk)
```

###  Alternatives

[horstoeko/zugferd

A library for creating and reading european electronic invoices

4205.2M25](/packages/horstoeko-zugferd)[laraveldaily/laravel-invoices

Missing invoices for Laravel

1.6k1.4M4](/packages/laraveldaily-laravel-invoices)[atgp/factur-x

PHP library to manage your Factur-X / ZUGFeRD 2.0 PDF invoices files

147883.7k4](/packages/atgp-factur-x)[anam/phantommagick

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

160462.2k2](/packages/anam-phantommagick)[horstoeko/zugferd-laravel

A library for Laravel-Framework for creating and reading european electronic invoices

39116.6k2](/packages/horstoeko-zugferd-laravel)[konekt/pdf-invoice

Library to generate PDF invoices

214209.1k](/packages/konekt-pdf-invoice)

PHPackages © 2026

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