PHP SDK
パッケージ: printgraph/php-sdk · GitHub
PHP アプリケーションから Printgraph API を簡単に利用できる公式 SDK です。 PHP 8.1 以上が必要です。
動作要件
- PHP 8.1 以上
- Composer
インストール
composer require printgraph/php-sdk初期化
API キーを環境変数で管理することを推奨します。
PRINTGRAPH_TOKEN=your_api_key_here<?php
use Printgraph\PhpSdk\Client\ClientFactory;
use Printgraph\PhpSdk\Printgraph;
require 'vendor/autoload.php';
$printgraph = new Printgraph(
ClientFactory::createHttpClient(getenv('PRINTGRAPH_TOKEN'))
);基本的な使い方
GenerateRequest クラスでリクエストを作成し、$printgraph->pdf()->generate() で PDF を生成します。
<?php
use Printgraph\PhpSdk\Api\Pdf\Generator\GenerateRequest;
use Printgraph\PhpSdk\Client\ClientFactory;
use Printgraph\PhpSdk\Printgraph;
require 'vendor/autoload.php';
$printgraph = new Printgraph(
ClientFactory::createHttpClient(getenv('PRINTGRAPH_TOKEN'))
);
$request = new GenerateRequest(
'hello-template',
['name' => '世界']
);
$response = $printgraph->pdf()->generate($request)->expect(
new \RuntimeException('PDF の生成に失敗しました')
);
file_put_contents('hello.pdf', $response->getContents());params を使った動的なデータ埋め込み
<?php
$request = new GenerateRequest(
'invoice-template',
[
'invoiceNumber' => 'INV-001',
'customerName' => '山田太郎',
'amount' => 10000,
'items' => [
['name' => '商品A', 'price' => 5000, 'quantity' => 1],
['name' => '商品B', 'price' => 2500, 'quantity' => 2],
],
]
);
$response = $printgraph->pdf()->generate($request)->expect(
new \RuntimeException('PDF の生成に失敗しました')
);
file_put_contents('invoice.pdf', $response->getContents());API リファレンス
ClientFactory::createHttpClient(string $token)
認証済みの HTTP クライアントを生成します。$token に API キーを渡してください。
new Printgraph(ClientInterface $client)
Printgraph クライアントを初期化します。ClientFactory::createHttpClient() で生成したクライアントを渡してください。
new GenerateRequest(string $templateKey, array $params)
| 引数 | 型 | 説明 |
|---|---|---|
$templateKey | string | テンプレートキー |
$params | array | テンプレートに渡す変数の連想配列 |
$printgraph->pdf()->generate(GenerateRequest $request)
PDF を生成します。Result オブジェクトを返します。
->expect(Throwable $e) でレスポンスを取得します。 エラーが発生した場合は指定した例外をスローします。 取得したレスポンスの ->getContents() で PDF バイナリを取得できます。