Search code examples
phpfpdf

FPDF How to attach a png with a dynamic path/name


Hello my goal is create a pdf with a png file (a qr code) generated dynamically.

I use FPDF library like below:

require('fpdf/fpdf.php');


class PDF extends FPDF

{
    private $pathQR;

    function setPathQR($pathQR){
        $this->pathQR = $pathQR;
    }

// Page header

function Header()

{

    // Logo

    $this->Image('img/logo.png',10,10,-300);

    // Arial bold 15

    $this->SetFont('Helvetica','B',14);

    // Move to the right

    $this->Cell(80);

    // Title

    $this->Cell(100,10,'TITLE',0,0,'C');

    // Line break

    $this->Ln(10);

    $this->SetFont('Helvetica','',12);

    $this->Cell(85);

    $this->Cell(80,10,'Other row..',0,0,'R');

    $this->Ln(10);

    $this->SetFont('Times','B',14);

    $this->Cell(85);

    $this->Cell(80,10,'Blablabla',0,0,'C');

    $this->Ln(15);

    $this->SetFont('Courier','B',24);

    $this->Cell(85);

    $this->Cell(80,10,'V T M',1,0,'C');
    $this->Image('qrcode/'.$pathQR.'.png',10,10,-300);

    $this->Ln(15);

    $this->SetFont('Helvetica','',12);

    $this->Cell(85);

  

}

}


// Instanciation of inherited class

$pdf = new PDF();

$pdf->AliasNbPages();

$pdf->AddPage();

$pdf->SetFont('Times','',16);

$pdf->setPathQR($e_mail);

$filename="pathFix/file-".$e_mail.".pdf";

$pdf->Output($filename,'F');

I create a function within PDF class

function setPathQR($pathQR){
        $this->pathQR = $pathQR;
    }

I call that function for setting value to pathQR ($e_mail)

$pdf->setPathQR($e_mail);

but i get error Notice: Undefined variable: pathQR in C:\xampp\htdocs....

on this row

$this->Image('qrcode/'.$pathQR.'.png',10,10,-300);

Why not recognize $pathQR? what's wrong? Thank you


Solution

  • You can pass the $e_mail variable into your class by using a setter method. After you've created an instance of fPDF add something along the lines of:

    class PDF extends FPDF {
    
        public $email;
        public function setemail($input) {$this->email = $input;}
    

    When you want to set it use:

    $pdf->setemail($e_mail);
    

    In your header method reference the email address using:

    $this->Image('qrcode/'. $this->email .'.png',10,10,-300);