在 PHP 中将文本定位在 pdf 文件上

Positioning text over pdf file in PHP

我正在开发电子证书网页。 我已设法加载证书模板并在其上书写(与会者姓名、活动名称和活动日期)。 但是在定位这三个信息的时候,无论多长,我都无法将它们定位在中心。他们总是从 x 点开始。

查看我的作业结果:

代码:

<?php
require_once('fpdf.php');
require_once('fpdi.php');

$pdf =& new FPDI();
$pdf->addPage('L');
$pagecount = $pdf->setSourceFile('Certificate.pdf');
$tplIdx = $pdf->importPage(1); 
$pdf->useTemplate($tplIdx); 
$pdf->SetFont('Times','I',18);
$pdf->SetTextColor(0,0,0); 
$pdf->SetXY(120, 62); 
$pdf->Write(0, "Attendee Name"); 

$pdf->SetXY(120, 102); 
$pdf->Write(0, "Event Name"); 

$pdf->SetXY(120, 140); 
$pdf->Write(0, "Event Date"); 
$pdf->Output();
?>

无论多长的文字,是否都可以居中?

意思是没有固定x点。不过y点结果还是很不错的

所以我以前用过 2 种方法,最可能是最简单的方法: 由于该行只有 1 个条目(与会者姓名或活动名称等) 从最左边开始一个单元格,让单元格 运行 成为页面的全宽,然后指定居中选项:

$pdf->SetXY(0,62);
//0 extends full width, $height needs to be set to cell height.
$pdf->Cell(0, $height, "Attendee Name", 0, 0, 'C');

另一个选项是计算中心,并相应地设置 X:

//how wide is the page?
$midPtX = $pdf->GetPageWidth() / 2;
//now we need to know how long the write string is
$attendeeNameWidth = $pdf->GetStringWidth($attendeeName);
//now we need to divide that by two to calculate the shift
$shiftLeft = $attendeeNameWidth / 2;
//now calculate our new X value
$x = $midPtX - $shiftLeft;
//now apply your shift for the answer
$pdf->setXY($x, 62); 
$pdf->Write(0, "Attendee Name"); 

然后您可以对每个其他元素重复上述操作。

您需要一种方法来计算以字符串像素为单位的字符串长度(比如 120 像素),并且您需要知道以像素为单位的页面宽度。

此时您将字符串定位在 x = (pagewidth/2 - stringwidth/2) 并且 Bob 是您的叔叔。

在 FPDI 中,您使用 GetStringWidth and GetPageWidth 执行此操作。

您可以对高度进行相同的调整。例如,您可以将字符串拆分为单词,计算每个单词的宽度,并确定何时过多。这样您就可以将字符串一分为二,并将每个部分居中。