跳转到内容

快速上手 —— 在 CodeIgniter 4 中生成你的第一份 PDF

在控制器中解析(resolve)pdf 服务,把内容写入它的文档,然后返回下载响应。整个过程只需要三行代码和一个 HTTP 响应。

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() 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');
}
}

如果你已经持有一个 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 时。