快速上手 —— 在 CodeIgniter 4 產生你的第一份 PDF
在控制器中 resolve(解析) pdf 服務,將內容加入它的文件,然後回傳下載回應。這只需要三行程式碼,以及一個 HTTP 回應。
composer require nextpdf/codeigniter關於需求條件,以及如何確認套件已被自動探索,請參閱 /integrations/codeigniter/install/。
步驟 1 —— 產生一個控制器
標題為「步驟 1 —— 產生一個控制器」的區段建立一個會回傳 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。
步驟 2 —— 加入一條路由
標題為「步驟 2 —— 加入一條路由」的區段在 app/Config/Routes.php 中,將一條路由對映到控制器方法:
$routes->get('invoices/(:num)/pdf', 'InvoiceController::download/$1');步驟 3 —— 請求 PDF
標題為「步驟 3 —— 請求 PDF」的區段開啟 /invoices/42/pdf。瀏覽器會下載 invoice-42.pdf。回應會帶有 Content-Type: application/pdf 以及套件的回應強化標頭。
變化版 —— 用 helper 做內嵌預覽
標題為「變化版 —— 用 helper 做內嵌預覽」的區段全域 pdf() helper 等同於 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'); }}變化版 —— 直接操作文件與 PdfResponse
標題為「變化版 —— 直接操作文件與 PdfResponse」的區段當你已經持有一個 Document 時,可直接用 PdfResponse 建構回應。pdf_document() helper 會提供一份全新、已預先設定好的文件。
<?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。 - 兩個等價的進入點:
Services類別,以及pdf()/pdf_document()這兩個 helper。 - 一個帶有
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 時。