php - 在 FPDF 中换行
问题描述
我正在 FPDF 库的帮助下生成 PDF。它从 MYSQL 数据库中获取数据。当任何列中的文本大小很大时,它会穿过该列并与下一列的文本重叠。我希望我的文本只包含在该列中。当我尝试使用 Multicell 功能时,PDF 完全变形了。我已经浏览了这个论坛中的不同帖子,但我无法实现它请帮助我实现这个我的代码。
function viewTable()
foreach($results as $result){
$this->cell(75,10,$result->user,1,0,'L');
$this->cell(80,10,$result->affiliation,1,0,'L');
$this->cell(34,10,$result->type,1,0,'L');
$this->cell(30,10,$result->sampleid,1,0,'L');
}
$pdf = new mypdf();
$pdf->AliasNbPages();
$pdf->AddPage('L','A4',0);
$pdf->Header1();
$pdf->headerTable();
$pdf->viewTable();
$pdf->footer();
$pdf->output();
解决方案
fpdf
似乎对表格的支持非常有限。该函数cell()
像在表格中一样创建单元格,但没有像 HTML 中那样自动调整大小。在这个问题中可以看到一个例子。
因此,即使您设法限制可见单元格的长度,您也会偶然发现单元格重叠且难以调整的问题。
缺少的是一个真实的表格正在计算添加内容时新单元格的度量。这可以通过两次渲染代码来完成,一次在虚拟表中,如果在获得多个换行符后渲染文本,则该虚拟表仅用于获取一些度量或使用的行数。
因此,对您的问题的简短回答是:fpdf
使用另一个库,只要它包含根据您的要求的附加功能,它是否基于它并不重要。
下面首先我写你的代码,但更正:
require('fpdf.php');
class mypdf extends FPDF
{
public function viewTable($results)
{
foreach($results as $result){
$this->cell(75,10,$result->user,1,0,'L');
$this->cell(80,10,$result->affiliation,1,0,'L');
$this->cell(34,10,$result->type,1,0,'L');
$this->cell(30,10,$result->sampleid,1,0,'L');
// add line break at the end of one data-set
$this->Ln();
}
}
// ... other methods below ...
public function Header1()
{
...
}
public function headerTable()
{
...
}
public function footer()
{
...
}
private function calculateSomething()
{
// Here you can calculate something but you can't
// call the function from outside with $pdf->calculateSomething()
}
protected function calculateSomethingElse()
{
// Here you can calculate something but you can't
// call the function from outside with $pdf->calculateSomethingElse()
// Nevertheless you could extend this class and call this function
// from the extending class.
}
}
// some example data
$results = [
'user cell, user cell, user cell, user cell, user cell',
'affiliation cell, affiliation cell, affiliation cell, affiliation cell',
'type cell',
'sampleid cell, sampleid cell'
]
$pdf = new mypdf();
$pdf->AliasNbPages();
$pdf->AddPage('L','A4',0);
$pdf->Header1();
$pdf->headerTable();
$pdf->viewTable($results);
$pdf->footer();
$pdf->output();
就像在链接的答案中一样,您可能想在每个数据集(行)的末尾添加一个换行符:
$pdf->Ln();
。
您甚至可以自己计算内容的长度并在内容中添加换行符。
但是您也可以尝试使用其他功能write()
来获得所需的行为,只是没有进一步的计算,您将无法显示正确的表格。
推荐阅读
- c - 如何用 C 创建一个随机字符串?
- python - 在 Google Colab 中使用 TPU
- python - 如何获取字典中特定键的计数
- css - Vuetify 右侧的 v-text-field 标签
- c# - C#泛型类:从可空类型参数推断不可空类型
- powershell - Powershell:通过邮件查找由一个人管理的所有帐户
- c++ - 为什么 C++ 模板实例化失败?
- python - 读取grb2文件很慢
- javascript - 如何将此网址替换为我想要的格式ID,谢谢
- javascript - useContext 未在子组件中显示更新的状态(当从全局文件中的 useEffect 挂钩中的 firebase 检索数据时)