콘텐츠로 이동

빠른 시작 — CodeIgniter 4에서 첫 번째 PDF 만들기

컨트롤러에서 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 disposition을 사용합니다.

라우트를 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');
}
}

변형 — 직접 문서 사용과 PdfResponse

섹션 제목: “변형 — 직접 문서 사용과 PdfResponse”

이미 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를 반환하는 컨트롤러.
  • 동일한 두 진입점: 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를 반환하지 않을 때.