2026/04/05

Laravel × PDF API 完全ガイド — DomPDF・Snappyからの移行

LaravelPHPPDF APIDomPDF代替Laravel Queue

PHPでPDFを生成するとき、DomPDF(laravel-dompdf)やwkhtmltopdf(barryvdh/laravel-snappy)を使うのが定番でした。しかし両者にはそれぞれ悩みどころがあります。DomPDFはFlexboxとGridに対応していない。Snappyはwkhtmltopdfバイナリのインストールが要り、そのwkhtmltopdfのリポジトリはすでにアーカイブ(読み取り専用)になっています。

FUNBREW PDF APIを使えば、LaravelのHttp FacadeでHTMLを送り、生成されたPDFをダウンロードするだけです。アプリケーションサーバーにPDF生成用のバイナリを入れる必要はありません。

この記事では、LaravelプロジェクトへのFUNBREW PDF API統合を、サービスクラス設計からBladeテンプレート連携、Queueによる非同期処理、Http::fake()を使ったテストまで、実践的なコード付きで解説します。他のフレームワーク・言語での統合は言語別クイックスタートを、エラーハンドリングの詳細はエラーハンドリングガイドを参照してください。

なぜAPI方式か

DomPDFの限界

DomPDFはPHPで動くため依存が少なく、人気があります。ただし公式READMEには次の制限が書かれています。

機能 DomPDF FUNBREW PDF API
Flexbox / Grid 非対応(README に明記) quality エンジン(Chromium)で利用可能
CSSの対応範囲 「(mostly) CSS 2.1 compliant」 quality はChromium、fast はwkhtmltopdf
日本語フォント Windows ANSI外の文字は外部フォントの用意が必要 quality 側のフォントに Noto Sans CJK JP を指定できる
テーブル セルはページをまたげない(1行が1ページに収まる必要) ブラウザの印刷レイアウトに従う

特にflex/gridで組んだデザインをそのままPDFにしたい場合、DomPDFではテンプレートの書き直しが必要になります。

FUNBREWの quality エンジン(Chromium)は Pro プラン以上で使えます。Free で quality を指定すると 403 になり、fast(wkhtmltopdf)を使います。

Snappy(wkhtmltopdf)の運用コスト

Snappyはwkhtmltopdfバイナリに依存するため、次の点に注意が要ります。

  • バイナリと依存ライブラリをイメージに含める必要がある: Dockerイメージのサイズや、ベースイメージ(Alpine等)との相性は使う配布物によって変わるので、自分の環境で確かめてください
  • Serverless/FaaS環境では工夫が要る: バイナリを同梱できる構成(コンテナイメージ等)を選ぶ必要があります
  • メンテナンスの停止: wkhtmltopdfのGitHubリポジトリはアーカイブ(読み取り専用)になっています

API方式ではアプリケーションサーバーにPDF生成のバイナリを置かずに済み、HTTPリクエストを送れる環境ならどこからでも呼べます。

サーバーリソースの節約

DomPDFやSnappyはPDF生成処理をアプリケーションサーバー上で実行します。複雑なHTMLや大量のPDF生成時はCPU・メモリの消費が増え、他のリクエストに影響が出ることもあります。

API方式ではPDF生成の重い処理は外部サービス側で行われます。LaravelアプリケーションはHTTPリクエストを送るだけです。

Laravelプロジェクトのセットアップ

APIキーの取得

無料アカウントを作成し、ダッシュボードからAPIキーを発行します。Freeプランは月30件まで生成できます。

# .envファイルに追加
FUNBREW_PDF_API_KEY="sk-your-api-key"
FUNBREW_PDF_BASE_URL="https://pdf.funbrew.cloud"

APIキーの安全な管理方法はセキュリティガイドで詳しく解説しています。

config/services.php に設定を追加

Laravelの慣習に従い、外部サービスの設定はconfig/services.phpにまとめます。

<?php

// config/services.php
return [
    // 既存の設定...

    'funbrew_pdf' => [
        'api_key'  => env('FUNBREW_PDF_API_KEY'),
        'base_url' => env('FUNBREW_PDF_BASE_URL', 'https://pdf.funbrew.cloud'),
        'timeout'  => env('FUNBREW_PDF_TIMEOUT', 60),
    ],
];

追加パッケージは不要

LaravelにはGuzzleをラップしたHTTPクライアント(Http Facade)が用意されており、Laravel 7以降で使えます。Guzzle本体は標準でLaravelの依存に含まれているため、この記事のコードのために追加でパッケージを入れる必要はありません。

なお公式のPHP SDK(FUNBREW/funbrew-pdf-php・funbrew/pdf-php)もあります。現在はGitHub経由のインストールなので(READMEを参照)、この記事では依存を増やさずにHttp Facadeで直接呼びます。

サービスクラスの設計

PDF生成ロジックはControllerから分離し、専用のサービスクラスに集約します。テストしやすくなり、将来的なAPIプロバイダの切り替えも容易になります。

FUNBREW PDF APIの生成は2段階です。

  1. POST /api/pdf/generate-from-html に html と options を送ると、JSON(success / data.download_url など)が返る
  2. data.download_url(/api/pdf/download/{filename})を同じAPIキーでGETすると、PDF本体が返る

options で指定できるのは page-size(A3, A4, A5, Letter, Legal)・orientation(Portrait, Landscape)・margin-top / margin-right / margin-bottom / margin-left(mm、0〜50)・engine(fast, quality)です。

app/Services/PdfService.php

<?php

namespace App\Services;

use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\Http;
use RuntimeException;

class PdfService
{
    private string $apiKey;
    private string $baseUrl;
    private int $timeout;

    public function __construct()
    {
        $this->apiKey = (string) config('services.funbrew_pdf.api_key');
        $this->baseUrl = rtrim((string) config('services.funbrew_pdf.base_url'), '/');
        $this->timeout = (int) config('services.funbrew_pdf.timeout', 60);
    }

    /**
     * HTMLからPDFを生成してバイナリを返す
     *
     * @param  string               $html    PDF化するHTMLコンテンツ
     * @param  array<string, mixed> $options APIのoptions(page-size, orientation, engine等)
     * @return string               PDFバイナリ
     *
     * @throws RuntimeException PDF生成に失敗した場合
     */
    public function generateFromHtml(string $html, array $options = []): string
    {
        $response = $this->client()->post($this->baseUrl.'/api/pdf/generate-from-html', [
            'html'    => $html,
            'options' => array_merge(['page-size' => 'A4'], $options),
        ]);

        $this->ensureSuccessful($response);

        $download = $this->client()->get($response->json('data.download_url'));

        $this->ensureSuccessful($download);

        return $download->body();
    }

    private function client(): PendingRequest
    {
        return Http::withToken($this->apiKey)
            ->acceptJson()
            ->timeout($this->timeout);
    }

    private function ensureSuccessful(Response $response): void
    {
        if ($response->failed()) {
            throw new RuntimeException(
                "PDF generation failed: HTTP {$response->status()} — ".$response->json('message', $response->body())
            );
        }
    }
}

エラー時のレスポンスは {"success": false, "message": "..."} の形です。入力の検証エラーは422で返ります(acceptJson() でJSONを受け取ります)。

サービスコンテナへの登録

シングルトンとして登録することで、同じリクエスト(ワーカー)の中で同じインスタンスを使い回せます。

// app/Providers/AppServiceProvider.php
use App\Services\PdfService;

public function register(): void
{
    $this->app->singleton(PdfService::class, function () {
        return new PdfService();
    });
}

Bladeテンプレートからのpdf生成

LaravelのBladeテンプレートエンジンと組み合わせることで、既存のビューを活用してPDFを生成できます。

テンプレートの作成

PDF用のBladeテンプレートを作成します。Webフォントを読み込みつつ、quality エンジン側にある Noto Sans CJK JP もフォールバックに指定しておきます。日本語が意図したフォントで出ているかは、生成したPDFで確認してください。

{{-- resources/views/pdf/invoice.blade.php --}}
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <link
    href="https://fonts.googleapis.com/css2?family=Noto+Sans+JP:wght@400;600;700&display=swap"
    rel="stylesheet"
  >
  <style>
    * { box-sizing: border-box; margin: 0; padding: 0; }
    body {
      font-family: 'Noto Sans JP', 'Noto Sans CJK JP', sans-serif;
      font-size: 14px;
      color: #1a1a1a;
      padding: 40px;
      line-height: 1.6;
    }
    .header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      border-bottom: 3px solid #1a56db;
      padding-bottom: 20px;
      margin-bottom: 32px;
    }
    .header h1 {
      font-size: 28px;
      color: #1a56db;
    }
    .meta { text-align: right; color: #4b5563; font-size: 13px; }
    .meta strong { color: #1a1a1a; font-size: 15px; }
    .bill-to {
      background: #f9fafb;
      border-radius: 8px;
      padding: 16px 20px;
      margin-bottom: 32px;
    }
    .bill-to h2 { font-size: 12px; color: #6b7280; margin-bottom: 8px; letter-spacing: 0.05em; }
    table {
      width: 100%;
      border-collapse: collapse;
      margin-bottom: 24px;
    }
    th {
      background: #1a56db;
      color: #fff;
      padding: 10px 12px;
      text-align: left;
      font-weight: 600;
    }
    td { padding: 10px 12px; border-bottom: 1px solid #e5e7eb; }
    tr:last-child td { border-bottom: none; }
    .amount { text-align: right; }
    .total-row {
      display: flex;
      justify-content: flex-end;
      gap: 40px;
      font-size: 16px;
      font-weight: 700;
      border-top: 2px solid #1a1a1a;
      padding-top: 16px;
    }
    .footer { margin-top: 48px; font-size: 12px; color: #9ca3af; }
  </style>
</head>
<body>
  <div class="header">
    <div>
      <h1>請求書</h1>
      <p style="color:#6b7280; margin-top:4px;">Invoice</p>
    </div>
    <div class="meta">
      <strong>#{{ $invoice['number'] }}</strong><br>
      発行日: {{ $invoice['issued_at'] }}<br>
      支払期限: {{ $invoice['due_at'] }}
    </div>
  </div>

  <div class="bill-to">
    <h2>BILL TO</h2>
    <p style="font-weight:600">{{ $customer['name'] }}</p>
    <p>{{ $customer['address'] }}</p>
    <p>{{ $customer['email'] }}</p>
  </div>

  <table>
    <thead>
      <tr>
        <th>項目</th>
        <th>数量</th>
        <th>単価</th>
        <th class="amount">金額</th>
      </tr>
    </thead>
    <tbody>
      @foreach ($invoice['items'] as $item)
      <tr>
        <td>{{ $item['name'] }}</td>
        <td>{{ $item['quantity'] }}</td>
        <td>¥{{ number_format($item['unit_price']) }}</td>
        <td class="amount">¥{{ number_format($item['quantity'] * $item['unit_price']) }}</td>
      </tr>
      @endforeach
    </tbody>
  </table>

  <div class="total-row">
    <span>合計(税込)</span>
    <span>¥{{ number_format($invoice['total']) }}</span>
  </div>

  <div class="footer">
    <p>{{ $company['name'] }} — {{ $company['address'] }} — {{ $company['email'] }}</p>
  </div>
</body>
</html>

Controllerの実装

<?php

namespace App\Http\Controllers;

use App\Services\PdfService;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\View;
use RuntimeException;

class InvoiceController extends Controller
{
    public function __construct(private readonly PdfService $pdfService)
    {
    }

    /**
     * 請求書PDFをダウンロードさせる
     */
    public function download(Request $request, int $invoiceId): Response
    {
        // 実際にはEloquentでデータを取得
        $data = [
            'invoice' => [
                'number'    => "INV-{$invoiceId}",
                'issued_at' => now()->format('Y年m月d日'),
                'due_at'    => now()->addDays(30)->format('Y年m月d日'),
                'items'     => [
                    ['name' => 'Webサイト保守(月額)', 'quantity' => 1, 'unit_price' => 4980],
                    ['name' => '追加作業(1時間)', 'quantity' => 2, 'unit_price' => 2000],
                ],
                'total' => 8980,
            ],
            'customer' => [
                'name'    => 'サンプル株式会社',
                'address' => '東京都千代田区丸の内1-1-1',
                'email'   => 'billing@example.co.jp',
            ],
            'company' => [
                'name'    => '自社名',
                'address' => '東京都新宿区西新宿2-2-2',
                'email'   => 'info@mycompany.co.jp',
            ],
        ];

        // Bladeテンプレートをレンダリングしてhtml文字列を取得
        $html = View::make('pdf.invoice', $data)->render();

        try {
            $pdfBytes = $this->pdfService->generateFromHtml($html);
        } catch (RuntimeException $e) {
            report($e);
            abort(502, 'PDF生成に失敗しました。しばらく経ってから再試行してください。');
        }

        return response($pdfBytes, 200, [
            'Content-Type'        => 'application/pdf',
            'Content-Disposition' => "attachment; filename=\"invoice-{$invoiceId}.pdf\"",
        ]);
    }
}

ルーティング

// routes/web.php
use App\Http\Controllers\InvoiceController;

Route::middleware('auth')->group(function () {
    Route::get('/invoices/{invoiceId}/pdf', [InvoiceController::class, 'download'])
        ->name('invoices.pdf');
});

テンプレート設計のコツはテンプレートエンジンガイドで詳しく解説しています。

サービスクラスの拡張

実際のプロダクションでは、PDFの種類によってオプションを変えたいケースが多いです。サービスクラスにショートカットメソッドを追加して使いやすくします(generateFromHtml などは前節のまま)。

// app/Services/PdfService.php に追加

/**
 * 請求書PDF(A4縦向き、qualityエンジン。Proプラン以上)
 */
public function generateInvoice(string $html): string
{
    return $this->generateFromHtml($html, [
        'page-size'   => 'A4',
        'orientation' => 'Portrait',
        'engine'      => 'quality',
    ]);
}

/**
 * レポートPDF(A4横向き、fastエンジン)
 */
public function generateReport(string $html): string
{
    return $this->generateFromHtml($html, [
        'page-size'   => 'A4',
        'orientation' => 'Landscape',
        'engine'      => 'fast',
    ]);
}

/**
 * 証明書PDF(Letter横向き、余白なし)
 */
public function generateCertificate(string $html): string
{
    return $this->generateFromHtml($html, [
        'page-size'     => 'Letter',
        'orientation'   => 'Landscape',
        'margin-top'    => 0,
        'margin-right'  => 0,
        'margin-bottom' => 0,
        'margin-left'   => 0,
    ]);
}

orientation は Portrait / Landscape、engine は fast / quality のいずれかで、それ以外の値(portrait や speed など)は422になります。

請求書や証明書のユースケース詳細はユースケース一覧も参考にしてください。

Laravel Queueによる非同期PDF生成

PDF生成が完了するまでユーザーをHTTPリクエストで待機させるのは、UX上好ましくありません。大量のPDFを一括生成する場合はなおさらです。Laravel Queueを使ってバックグラウンド処理にしましょう。

Jobクラスの作成

php artisan make:job GeneratePdfJob
<?php

namespace App\Jobs;

use App\Services\PdfService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\View;
use Throwable;

class GeneratePdfJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * 最大試行回数
     */
    public int $tries = 3;

    /**
     * タイムアウト(秒)。queue.php の retry_after より数秒以上短くする
     */
    public int $timeout = 90;

    /**
     * リトライ間隔(秒)
     */
    public array $backoff = [10, 30, 60];

    public function __construct(
        private readonly string $template,
        private readonly array  $data,
        private readonly string $storagePath,
        private readonly array  $options = [],
    ) {
    }

    public function handle(PdfService $pdfService): void
    {
        $html = View::make($this->template, $this->data)->render();

        $pdfBytes = $pdfService->generateFromHtml($html, $this->options);

        Storage::put($this->storagePath, $pdfBytes);
    }

    public function failed(?Throwable $e): void
    {
        // 失敗を記録・通知する(Slack, メール等)
        Log::error('PDF generation job failed', [
            'template'    => $this->template,
            'storagePath' => $this->storagePath,
            'error'       => $e?->getMessage(),
        ]);
    }
}

ジョブのリトライは生成APIへのPOSTをやり直すので、失敗の仕方によってはPDFが二重に生成され、月間の生成件数に数えられます。

Jobのディスパッチ

<?php

namespace App\Http\Controllers;

use App\Jobs\GeneratePdfJob;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ReportController extends Controller
{
    public function generateAsync(Request $request, int $reportId): JsonResponse
    {
        $data = [
            'report_id' => $reportId,
            'title'     => '月次レポート',
            'metrics'   => $this->getMetrics($reportId),
        ];

        $storagePath = "reports/report-{$reportId}-" . now()->format('Ymd') . '.pdf';

        GeneratePdfJob::dispatch(
            template:    'pdf.report',
            data:        $data,
            storagePath: $storagePath,
        )->onQueue('pdf');

        return response()->json([
            'status'       => 'processing',
            'storage_path' => $storagePath,
            'message'      => 'PDFの生成を開始しました。完了後にダウンロードできます。',
        ], 202);
    }

    private function getMetrics(int $reportId): array
    {
        // 実際にはDBから取得
        return [
            ['name' => '問い合わせ件数', 'value' => '1,234'],
            ['name' => '平均対応時間', 'value' => '2.5時間'],
            ['name' => '解決率', 'value' => '92.0%'],
        ];
    }
}

キュー設定(config/queue.php)

本番環境ではRedisキューを使う例を示します。retry_after はジョブの $timeout(ワーカーの --timeout)より数秒以上長くします。逆だと、同じジョブが二重に処理されることがあります。

// config/queue.php(Redis設定部分)
'redis' => [
    'driver'      => 'redis',
    'connection'  => 'default',
    'queue'       => env('REDIS_QUEUE', 'default'),
    'retry_after' => 120,
    'block_for'   => null,
],
# .env(本番)
QUEUE_CONNECTION=redis

# PDFキュー専用ワーカーを起動
php artisan queue:work redis --queue=pdf --tries=3 --timeout=90

バッチ処理の詳細はPDF一括生成ガイドを参照してください。

生成済みPDFのダウンロード

// app/Http/Controllers/ReportController.php に追加
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Storage;

public function download(Request $request, int $reportId): Response
{
    $storagePath = "reports/report-{$reportId}-" . now()->format('Ymd') . '.pdf';

    if (! Storage::exists($storagePath)) {
        abort(404, 'PDFがまだ生成されていません。しばらく後に再試行してください。');
    }

    return response(Storage::get($storagePath), 200, [
        'Content-Type'        => 'application/pdf',
        'Content-Disposition' => "attachment; filename=\"report-{$reportId}.pdf\"",
    ]);
}

この例はファイル名に当日の日付を使うため、日付をまたぐと見つからなくなります。実際には生成時のパスをDBに保存して引くのが確実です。

Http::fake() によるテスト

LaravelのテストではHttp::fake()を使うことで、外部APIを実際に呼び出さずにモックできます。URLパターンには * のワイルドカードが使えます。生成API(JSON)とダウンロード(PDF本体)の2つをそれぞれ偽装します。

サービスクラスのUnit Test

<?php

namespace Tests\Unit\Services;

use App\Services\PdfService;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Http;
use RuntimeException;
use Tests\TestCase;

class PdfServiceTest extends TestCase
{
    protected function setUp(): void
    {
        parent::setUp();

        config([
            'services.funbrew_pdf.api_key'  => 'test-api-key',
            'services.funbrew_pdf.base_url' => 'https://pdf.funbrew.cloud',
            'services.funbrew_pdf.timeout'  => 60,
        ]);
    }

    private function fakeApi(string $pdf = '%PDF-1.4 fake content'): void
    {
        Http::fake([
            'pdf.funbrew.cloud/api/pdf/generate-from-html' => Http::response([
                'success' => true,
                'data'    => [
                    'filename'     => 'abc123.pdf',
                    'download_url' => 'https://pdf.funbrew.cloud/api/pdf/download/abc123.pdf',
                ],
            ], 200),
            'pdf.funbrew.cloud/api/pdf/download/*' => Http::response($pdf, 200, [
                'Content-Type' => 'application/pdf',
            ]),
        ]);
    }

    public function test_generate_from_html_returns_pdf_binary(): void
    {
        $this->fakeApi('%PDF-1.4 fake content');

        $result = (new PdfService())->generateFromHtml('<h1>テスト</h1>');

        $this->assertSame('%PDF-1.4 fake content', $result);
    }

    public function test_generate_from_html_sends_correct_payload(): void
    {
        $this->fakeApi();

        (new PdfService())->generateFromHtml('<h1>テスト</h1>', ['page-size' => 'Letter']);

        Http::assertSent(function (Request $request) {
            return $request->url() === 'https://pdf.funbrew.cloud/api/pdf/generate-from-html'
                && $request['html'] === '<h1>テスト</h1>'
                && $request['options']['page-size'] === 'Letter'
                && $request->hasHeader('Authorization', 'Bearer test-api-key');
        });
    }

    public function test_generate_from_html_throws_on_api_error(): void
    {
        Http::fake([
            'pdf.funbrew.cloud/*' => Http::response(['success' => false, 'message' => 'Internal error'], 500),
        ]);

        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessageMatches('/PDF generation failed/');

        (new PdfService())->generateFromHtml('<h1>テスト</h1>');
    }

    public function test_generate_invoice_uses_portrait_quality(): void
    {
        $this->fakeApi();

        (new PdfService())->generateInvoice('<h1>Invoice</h1>');

        Http::assertSent(function (Request $request) {
            return $request['options']['orientation'] === 'Portrait'
                && $request['options']['engine'] === 'quality';
        });
    }
}

ControllerのFeature Test

<?php

namespace Tests\Feature;

use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;

class InvoiceControllerTest extends TestCase
{
    use RefreshDatabase;

    public function test_download_returns_pdf_response(): void
    {
        Http::fake([
            'pdf.funbrew.cloud/api/pdf/generate-from-html' => Http::response([
                'success' => true,
                'data'    => ['download_url' => 'https://pdf.funbrew.cloud/api/pdf/download/inv1.pdf'],
            ], 200),
            'pdf.funbrew.cloud/api/pdf/download/*' => Http::response('%PDF-1.4 fake invoice content', 200, [
                'Content-Type' => 'application/pdf',
            ]),
        ]);

        $this->actingAs(User::factory()->create())
            ->get('/invoices/1/pdf')
            ->assertStatus(200)
            ->assertHeader('Content-Type', 'application/pdf')
            ->assertHeader('Content-Disposition', 'attachment; filename="invoice-1.pdf"');
    }

    public function test_download_returns_502_on_api_failure(): void
    {
        Http::fake([
            'pdf.funbrew.cloud/*' => Http::response(['success' => false, 'message' => 'Internal error'], 500),
        ]);

        $this->actingAs(User::factory()->create())
            ->get('/invoices/1/pdf')
            ->assertStatus(502);
    }

    public function test_download_requires_authentication(): void
    {
        $this->get('/invoices/1/pdf')
            ->assertRedirect('/login');
    }
}

Jobのテスト

Jobのテストでは PdfService 自体を差し替えると、API の形に依存しないテストになります。

<?php

namespace Tests\Unit\Jobs;

use App\Jobs\GeneratePdfJob;
use App\Services\PdfService;
use Illuminate\Support\Facades\Storage;
use Mockery;
use Tests\TestCase;

class GeneratePdfJobTest extends TestCase
{
    public function test_handle_stores_pdf_to_storage(): void
    {
        Storage::fake();

        $pdfService = Mockery::mock(PdfService::class);
        $pdfService->shouldReceive('generateFromHtml')->once()->andReturn('%PDF-1.4 fake');

        $job = new GeneratePdfJob(
            template:    'pdf.invoice',
            data:        [
                'invoice'  => ['number' => 'INV-001', 'issued_at' => '', 'due_at' => '', 'items' => [], 'total' => 0],
                'customer' => ['name' => '', 'address' => '', 'email' => ''],
                'company'  => ['name' => '', 'address' => '', 'email' => ''],
            ],
            storagePath: 'reports/test.pdf',
        );

        $job->handle($pdfService);

        Storage::assertExists('reports/test.pdf');
    }
}

本番運用Tips

リトライとタイムアウト

HTTP APIは一時的な障害で失敗することがあります。LaravelのHttp::retry()で自動リトライを入れます。FUNBREWの429のうち待てば解消するのは、Retry-After ヘッダーが付く毎分のレート制限だけです。月間上限やストレージ上限の429には Retry-After が無く、待っても解消しないのでリトライしません。

// app/Services/PdfService.php の client() を差し替え
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\RequestException;

private function client(): PendingRequest
{
    return Http::withToken($this->apiKey)
        ->acceptJson()
        ->timeout($this->timeout)
        ->retry(
            3,
            function (int $attempt, \Exception $e) {
                $retryAfter = $e instanceof RequestException ? (int) $e->response->header('Retry-After') : 0;

                return $retryAfter > 0 ? $retryAfter * 1000 : $attempt * 500;
            },
            function (\Throwable $e) {
                if ($e instanceof ConnectionException) {
                    return true;
                }

                if (! $e instanceof RequestException) {
                    return false;
                }

                return $e->response->serverError()
                    || ($e->response->status() === 429 && $e->response->header('Retry-After') !== '');
            },
            throw: false,
        );
}

throw: false にすると、リトライし尽くした後は最後のレスポンスが返り、前節の ensureSuccessful() で RuntimeException になります。ただし接続エラーでリトライし尽くした場合は throw: false でも ConnectionException が投げられるので、Controller側で拾うなら ConnectionException も捕まえてください。生成のPOSTをリトライすると、サーバー側では生成済みだった場合にPDFが二重にできることがあります。

レート制限への対処

毎分のレート制限は会社(アカウント)単位で、Free 10 / Pro 120 / Business 300 リクエスト/分です。生成とダウンロードの両方が数えられるので、この記事の PdfService は1件につき2リクエストを使います。

キュー側では、Laravelのジョブミドルウェア RateLimited で投げる速さを抑えられます。制限を超えたジョブは遅延つきでキューに戻されます(戻すたびに試行回数が増えるので $tries を調整します)。

// app/Providers/AppServiceProvider.php
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Support\Facades\RateLimiter;

public function boot(): void
{
    // Proプラン(120リクエスト/分)なら、1件2リクエストで毎分50件程度に抑える
    RateLimiter::for('funbrew-pdf', fn (object $job) => Limit::perMinute(50));
}
// app/Jobs/GeneratePdfJob.php に追加
use Illuminate\Queue\Middleware\RateLimited;

public function middleware(): array
{
    return [new RateLimited('funbrew-pdf')];
}

同時に動くジョブの数は、起動する queue:work プロセスの数(またはHorizonの maxProcesses)で決まります。--max-jobs / --max-time は、指定した件数・時間を処理したらワーカーを終了させるオプションで、プロセスマネージャーと組み合わせてメモリを解放するためのものです(同時実行数の制限ではありません)。

# 1000件処理するか1時間たったら終了(Supervisor等で再起動させる)
php artisan queue:work redis --queue=pdf --max-jobs=1000 --max-time=3600

PDFのキャッシュ

同じデータから繰り返しPDFを生成する場合は、Laravelのキャッシュを活用してAPIコールを削減できます。

use Illuminate\Support\Facades\Cache;

public function getCachedPdf(string $cacheKey, string $html, array $options = []): string
{
    return Cache::remember(
        "pdf:{$cacheKey}",
        now()->addHours(24),
        fn () => $this->generateFromHtml($html, $options)
    );
}

Horizonでキュー監視

本番ではLaravel Horizon(Redisキュー用)でキューを可視化・監視できます。

composer require laravel/horizon
php artisan horizon:install
// config/horizon.php(PDF専用スーパーバイザー設定)
'environments' => [
    'production' => [
        'supervisor-pdf' => [
            'connection'   => 'redis',
            'queue'        => ['pdf'],
            'balance'      => 'auto',
            'minProcesses' => 1,
            'maxProcesses' => 5,
            'tries'        => 3,
            'timeout'      => 100,
        ],
    ],
],

Horizonの timeout はジョブ側の $timeout(90秒)より長く、かつ retry_after(120秒)より数秒以上短くします。

本番環境での運用ノウハウの詳細はプロダクション運用ガイドにまとめています。

ログとモニタリング

PDF生成のパフォーマンスをログに記録しておくと、問題の早期発見に役立ちます。

use Illuminate\Support\Facades\Log;

public function generateFromHtml(string $html, array $options = []): string
{
    $startedAt = microtime(true);

    $response = $this->client()->post($this->baseUrl.'/api/pdf/generate-from-html', [
        'html'    => $html,
        'options' => array_merge(['page-size' => 'A4'], $options),
    ]);

    if ($response->failed()) {
        Log::error('PDF generation failed', [
            'status'  => $response->status(),
            'message' => $response->json('message'),
            'job_id'  => $response->header('X-Job-Id'),
            'elapsed' => round((microtime(true) - $startedAt) * 1000).'ms',
        ]);
    }

    $this->ensureSuccessful($response);

    $download = $this->client()->get($response->json('data.download_url'));

    $this->ensureSuccessful($download);

    Log::info('PDF generated', [
        'size'    => strlen($download->body()),
        'job_id'  => $response->header('X-Job-Id'),
        'elapsed' => round((microtime(true) - $startedAt) * 1000).'ms',
    ]);

    return $download->body();
}

生成APIのレスポンスには X-Job-Id ヘッダーが付くので、問い合わせのときに使えるようログに残しておきます。

DomPDFとの機能比較

まとめとして、DomPDF・Snappy・FUNBREW PDF APIの比較表を示します。

観点 DomPDF (laravel-dompdf) Snappy (wkhtmltopdf) FUNBREW PDF API
セットアップ Composer のみ バイナリのインストールが必要 APIキーのみ
CSSサポート 「(mostly) CSS 2.1」、Flexbox・Grid非対応 Qt WebKitベース(対応範囲は版による) quality はChromium(Pro以上)、fast はwkhtmltopdf
日本語 外部フォントの用意が必要 フォントのインストールが必要 quality で Noto Sans CJK JP を指定可能(出力で確認)
Docker 容易 バイナリと依存ライブラリを含める 容易(外部API呼び出しのみ)
Serverless 動作可能 バイナリを同梱する構成が必要 HTTPを送れれば利用可能
サーバー負荷 PHP側で処理 PHP側で処理 外部サービスが処理
メンテナンス 継続中 リポジトリはアーカイブ済み 継続中
コスト 無料 無料 無料プラン(月30件)+月額の有料プラン

使い分けの目安:

  • DomPDF: 社内向けの簡単なPDF、CSSレイアウトにこだわらない場合
  • Snappy: 既存プロジェクトで使用中の場合(ただし移行を検討)
  • FUNBREW PDF API: 顧客向けのPDF、Flexbox/Gridを使ったデザイン、バイナリを置きたくない環境

まとめ

LaravelからFUNBREW PDF APIに接続するのは、Http Facadeを使えば数十行で完了します。本記事でカバーした設計パターンを適用することで、テストしやすく、本番で安心して使えるPDF生成機能を実装できます。

  1. サービスクラスに集約する — PdfService に生成(POST)とダウンロード(GET)の2段階をまとめ、Controllerは薄く保つ
  2. Bladeテンプレートを活用する — View::make()->render() でHTMLを生成し、既存のビューを再利用する
  3. Queueで非同期化する — GeneratePdfJob でバックグラウンド処理し、ユーザーを待たせない
  4. Http::fake() でテストする — 外部API呼び出しをモックして、高速・安定したテストを書く
  5. リトライとログを入れる — Retry-After 付きの429と5xxだけをリトライし、X-Job-Id を記録する

まずはPlaygroundで自分のHTMLがどんなPDFになるか確認してみてください。準備ができたらドキュメントでAPIの全オプションを確認し、料金プランで最適なプランを選びましょう。

関連記事

Powered by FUNBREW PDF