TCPDF 是一个用于生成 PDF 的 PHP 类
composer require tecnickcom/tcpdf
tcpdf_pagination.php
,并在其中引入必要的类:<?php
require_once('vendor/autoload.php');
use TCPDF;
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Your Name');
$pdf->SetTitle('Document Title');
$pdf->SetSubject('Document Subject');
$pdf->SetKeywords('TCPDF, PDF, document, pagination');
$pdf->SetFont('helvetica', '', 16, '', true);
$pdf->SetAutoPageBreak(true, PDF_PAGE_MARGIN);
$pdf->AddPage();
function printTextWithPagination($pdf, $text, $page_break = 0.3)
{
$page_count = $pdf->getPageCount();
$line = '';
$y = $pdf->GetY();
$words = explode(' ', $text);
$current_line = '';
foreach ($words as $word) {
if (strlen($current_line) + strlen($word) + 1 > PDF_PAGE_WIDTH) {
$pdf->MultiCell(0, PDF_PAGE_MARGIN, $line);
$y = $pdf->GetY();
$line = $word . ' ';
} else {
if ($line != '') {
$line .= ' ';
}
$line .= $word;
}
}
if ($line != '') {
$pdf->MultiCell(0, PDF_PAGE_MARGIN, $line);
}
if ($y + PDF_FONT_SIZE > PDF_PAGE_HEIGHT) {
$pdf->AddPage();
}
}
printTextWithPagination
函数在 PDF 中添加文本,并设置分页:$text = 'Your long text goes here. It will be divided into pages automatically.';
printTextWithPagination($pdf, $text);
$pdf->Output('tcpdf_pagination.pdf', 'I');
现在,当你运行 tcpdf_pagination.php
文件时,它将生成一个包含分页文本的 PDF 文件。你可以根据需要调整 printTextWithPagination
函数中的 $page_break
参数来控制分页的位置。