コンテンツにスキップ

クイックスタート — CodeIgniter 4 で作る初めての PDF

コントローラー内で pdf サービスを resolve(解決)し、そのドキュメントにコンテンツを追加して、ダウンロードレスポンスを返します。作業は 3 行、HTTP レスポンスは 1 つだけです。

Terminal window
composer require nextpdf/codeigniter

要件とパッケージ検出を確認するには、/integrations/codeigniter/install/. を参照してください。

PDF を返すコントローラーを作成します。Pdf ライブラリが新しいドキュメントをラップし、そのドキュメントを CodeIgniter の DownloadResponse に変換します。

このページのすべての PHP サンプルでは、開始タグの後の独立した行で declare(strict_types=1); を宣言します(PSR-12 §x1.x3.p11、§x1.x3.p34)。

<?php
declare(strict_types=1);
namespace App\Controllers;
use CodeIgniter\HTTP\DownloadResponse;
use NextPDF\CodeIgniter\Config\Services;
final class InvoiceController extends BaseController
{
public function download(int $id): DownloadResponse
{
$pdf = Services::pdf();
$pdf->document()->addPage();
$pdf->document()->cell(0, 10, "Invoice #{$id}");
return $pdf->download("invoice-{$id}.pdf");
}
}

Services::pdf() は新しい Pdf を返します。基盤となるドキュメントも呼び出しのたびに新規作成されます。これはパッケージの機能テストスイートで検証済みです。download() を呼び出すと、DownloadResponse が生成され、attachment ディスポジションが設定されます。

コントローラーのメソッドへのルートを app/Config/Routes.php でマッピングします。

$routes->get('invoices/(:num)/pdf', 'InvoiceController::download/$1');

ブラウザーで /invoices/42/pdf を開くと、invoice-42.pdf がダウンロードされます。レスポンスには Content-Type: application/pdf と、パッケージのレスポンス強化ヘッダーが含まれます。

グローバルな pdf() ヘルパーは Services::pdf() と同等です。PDF をダウンロードせずにブラウザーで表示するには、inline() を呼び出します。

<?php
declare(strict_types=1);
namespace App\Controllers;
use CodeIgniter\HTTP\DownloadResponse;
final class ReportController extends BaseController
{
public function preview(): DownloadResponse
{
$pdf = pdf();
$pdf->document()->addPage();
$pdf->document()->cell(0, 10, 'Monthly Report');
return $pdf->inline('report.pdf');
}
}

すでに Document を保持している場合は、PdfResponse でレスポンスを直接構築します。pdf_document() ヘルパーは、事前構成済みの新しいドキュメントを返します。

<?php
declare(strict_types=1);
namespace App\Controllers;
use CodeIgniter\HTTP\DownloadResponse;
use NextPDF\CodeIgniter\Http\PdfResponse;
final class DocumentController extends BaseController
{
public function generate(): DownloadResponse
{
$document = pdf_document();
$document->addPage();
$document->cell(0, 10, 'Hello World');
return PdfResponse::download($document, 'hello.pdf');
}
}
  • NextPDF サービスを解決し、型付きの DownloadResponse を返すコントローラー。
  • 2 つの同等のエントリーポイント。Services クラスと、pdf() / pdf_document() ヘルパーです。
  • application/pdf とパッケージのセキュリティヘッダーを含み、サニタイズ済みのファイル名を備えたレスポンス。

この入門ページをわかりやすく保つため、このチュートリアルではエラー処理を省略しています。本番向けのコントローラー(依存性注入、例外処理、可観測性、キュージョブ)については、/integrations/codeigniter/production-usage/. に進んでください。そのページでは、強化されたバリエーションを紹介しています。

  • コードサンプル内で PHP 開始タグを独立した行に配置すること(PSR-12 Extended Coding Style §x1.x3.p11)。
  • コードサンプル内での declare(strict_types=1) 文の形式(PSR-12 Extended Coding Style §x1.x3.p34)。
  • /integrations/codeigniter/overview/ — API 全体の概要。
  • /integrations/codeigniter/configuration/ — デフォルトとパスの変更。
  • /integrations/codeigniter/production-usage/ — 本番グレードのコントローラーと非同期ジョブ。
  • /integrations/codeigniter/troubleshooting/ — ルートが PDF を返さない場合。