将 PHP 变量传递给 FPDF 的正确方法是什么?


What is the correct way to pass a PHP variable to FPDF?

我最近才开始使用FPDF,但我仍然不确定如何传入我自己的变量。

我想做类似的事情

索引.php:

...
//set name variable
$name = $_POST["name"]
//embed the pdf
<embed width="100%" height="100%" name="plugin" src="my-fpdf.php" type="application/pdf">
....

我的-fpdf.php:

<?php
    require('fpdf.php');
    $pdf = new FPDF();
    $pdf->AddPage();
    $pdf->SetFont('Arial','B',16);
    $txt = "Hello ".$name."!" //access the variable
    $pdf->Cell(40,10,$txt);
    $pdf->Output();
?>

是否有有关如何执行此操作的最佳实践?

您需要

将其添加为查询参数:

<embed ... src="my-fpdf.php?name="<?php echo $name ?>" ...>

然后

$txt = "Hello, " . $_GET['name'];

将变量添加到您的 PDF 类中,如下所示:

public $name;

在PDF类中添加一个接受参数的函数,并使用此函数设置上面的变量:

public function setName($name){
    $this->name = $name;
}

然后,您将能够从PDF类中访问$this>名称。 不要忘记实际调用刚刚定义的函数(就在构造函数之后)。

$pdf = new PDF();
$pdf->setName('Some Name');