Hello World
本範例帶您從零開始建立一份 PDF 文件。完成後,您會了解 TCPDF-Next 的基本運作流程:建立文件、新增頁面、寫入文字、輸出檔案。
前置條件
請先透過 Composer 安裝 TCPDF-Next:
bash
composer require yeee-fang/tcpdf-next完整範例
php
<?php
require_once __DIR__ . '/vendor/autoload.php';
use YeeeFang\TcpdfNext\Document\PdfDocument;
use YeeeFang\TcpdfNext\Document\PageFormat;
// 建立 PDF 文件
$pdf = PdfDocument::create()
->setTitle('我的第一份 PDF')
->setAuthor('TCPDF-Next 使用者')
->setSubject('Hello World 範例')
->setPageFormat(PageFormat::A4)
->build();
// 新增一頁
$page = $pdf->addPage();
// 寫入文字
$page->addText('Hello World! 歡迎使用 TCPDF-Next')
->setPosition(20, 30)
->setFont('Helvetica', size: 16);
// 輸出 PDF 到瀏覽器
$pdf->output('hello_world.pdf');程式碼說明
建立文件
PdfDocument::create() 回傳一個建構器,用來設定文件屬性。呼叫 build() 後才會真正產生文件物件。標題、作者等中繼資料會嵌入 PDF 檔案中,可在閱讀器的文件屬性中查看。
新增頁面與內容
php
$page = $pdf->addPage();
$page->addText('Hello World!')
->setPosition(20, 30)
->setFont('Helvetica', size: 16);addPage() 建立一個空白頁面並回傳頁面物件。透過 addText() 指定文字內容,再用 setPosition() 與 setFont() 控制位置和字型。
輸出模式
php
// 在瀏覽器中顯示
$pdf->output('hello_world.pdf');
// 強制下載
$pdf->download('hello_world.pdf');
// 儲存到伺服器檔案系統
$pdf->save('/path/to/hello_world.pdf');
// 取得 PDF 內容字串
$content = $pdf->toString();自訂頁面尺寸
php
// 預定義格式
$pdf = PdfDocument::create()
->setPageFormat(PageFormat::A4)
->build();
// 橫向
$pdf = PdfDocument::create()
->setPageFormat(PageFormat::A4_LANDSCAPE)
->build();
// 其他常見格式
PageFormat::LETTER;
PageFormat::LEGAL;
PageFormat::A3;中文字型
如需顯示中文字元,請使用支援中文的字型。TCPDF-Next 內建 CID 字型支援:
php
$page->addText('繁體中文內容')
->setFont('cid0ct', size: 12);或載入自訂 TrueType 字型,詳見 自訂字型 章節。