Shuffle
Shuffle

Reputation: 13

Convert an JSON table to an PDF with mPDF

I'm trying to convert a JSON file to a PDF via mPDF, but my problem with that is that the JSON table is not displayed in the HTML after running the php. Only one empty PDF page is displayed.

EDIT: I Updated the code, so it works almost. The code create the table but it don't shows all of the JSON Data.

New PHP

ob_start();
$json = file_get_contents($url);
$json_decoded= json_decode($json);

foreach ($json_decoded as $result) {
$html = '
  <!DOCTYPE html>
  <html>
  <head>
      <title>Convert JSON Data to HTML Table</title>
      <link href="style.css" rel="stylesheet">
      <meta  charset="UTF-8">
  </head>
  <body >
      <table>
          <tr>
              <th>driverno</th>
              <th>name</th>
              <th>objectno</th>
              <th>tagId</th>
              <th>lastScanDate</th>
          </tr>
          <tr>
            <td>'.$result->driverno.'</td>
            <td>'.$result->name.'</td>
            <td>'.$result->objectno.'</td>
            <td>'.$result->tagID.'</td>
            <td>'.$result->lastScanDate.'</td>
          </tr>
          <tr>
            <td>'.$result->driverno.'</td>
            <td>'.$result->name.'</td>
            <td>'.$result->objectno.'</td>
            <td>'.$result->tagID.'</td>
            <td>'.$result->lastScanDate.'</td>
          </tr>
      </table>
  </body>


  </html>

';

}

$mpdf->WriteHTML($html);
$mpdf->Output("demo.pdf", 'F');
$mpdf->Output();
?>

JSON

 {
  "driverno":1,
  "name":"Aragorn",
  "objectno":1,
  "tagId":1,
  "lastScanDate":"yesterday"   
 },
 {
  "driverno":2,
  "name":"Legolas",
  "objectno":2,
  "tagId":2,
  "lastScanDate":"today"  
 },
 {
  "driverno":3,
  "name":"Gimmli",
  "objectno":3,
  "tagId":3,
  "lastScanDate":"today"

 },
 {
  "driverno":4,
  "name":"Gandalf",
  "objectno":4,
  "tagId":4,
  "lastScanDate":"today" 
 }

I get the last data of the JSON file without the tagID.

Upvotes: 1

Views: 4399

Answers (1)

Finwe
Finwe

Reputation: 6745

mPDF does not support Javascript to this extent.

You have to parse the JSON directly in PHP with $table = json_decode($json, true) and then loop over it foreach ($json as $row) and build HTML table markup by yourself.

Be careful not to echo the code, but to build it as a string in a variable (see this SO answer).

Pass the string with table HTML to mPDF with $mpdf->WriteHtml() then.

Upvotes: 1

Related Questions