FPDF - 如何使文本显示在页面中间?

问题描述

我正在使用 FPDF 库生成 PDF 文件

文件中的每页为 100mm x 100mm,所有边距为 10mm。

每个页面显示的文本各不相同(但应始终最多 200 个字)。

我真的希望文本能够完美地居中显示页面中间。

目前,我可以让文本居中对齐,但我很难定位它,因此它每次都位于页面中间。到目前为止,这是我的代码

$pdf->AddPage();
$pdf->SetMargins($card_margin,$card_margin,$card_margin);
$pdf->SetAutopageBreak(true,$card_margin);
$pdf->SetFont('Avenir','','10');
$pdf->SetAutopageBreak(false);
    
$pdf->MultiCell(80,5,$text_to_print,'C');

$pdf->SetFont('Alex Brush','13');
$pdf->MultiCell(80,10,$signee_text_to_print,'C');

这是由上述代码生成的 PDF 页面的屏幕截图:

PDF screenshot

任何想法或建议将不胜感激!

解决方法

在调用 SetY 之前使用 MultiCell 以“下推”页面上文本开始的位置。由于您指出它永远不会超过 200 个字符,因此您应该能够估计高度并为 X 使用固定值,这将使您每次都非常接近垂直中心。

$pdf->SetAutoPageBreak(false);
$pdf->SetY(100);  // for example ... value will need to be changed of course
$pdf->MultiCell(80,5,$text_to_print,'C');