Generate PDF from dynamic php file

774 Views Asked by At

I have a php page which is dynamically populated with data, now when I press a download button I want to be able to download that page with that specific data on it, as a PDF.

I found a library called tcpdf that is working for me but I don't know how to populate the $html variable with my dynamic code as there is a string attached to that variable. I attached the code below:

<?php
require_once('tcpdf/tcpdf.php');
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
    require_once(dirname(__FILE__).'/lang/eng.php');
    $pdf->setLanguageArray($l);
}
$pdf->SetFont('helvetica', '', 9);
$pdf->AddPage();
$html = "need to puplate this dynamic";
$pdf->writeHTML($html, true, 0, true, 0);
$pdf->lastPage();
$pdf->Output('example_021.pdf', 'I');
?>
2

There are 2 best solutions below

0
On BEST ANSWER
`<?php
require_once('tcpdf/tcpdf.php');
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
    require_once(dirname(__FILE__).'/lang/eng.php');
    $pdf->setLanguageArray($l);
}
$pdf->SetFont('helvetica', '', 9);
$pdf->AddPage();
$html = "";
$sql = "SELECT * FROM TABLE_NAME";
while()
{
    $html .= "need to puplate this dynamic";
}
$html = $html;
$pdf->writeHTML($html, true, 0, true, 0);
$pdf->lastPage();
$pdf->Output('example_021.pdf', 'I');
?>`

Set html variable conceit to your existing looping.please find above sample code.

1
On

The solution was to populate each variable with content and then concatenate them inside the $pdf.