Your Location is: Home > Php

Convert HTML table to PNG and render it on webpage

From: Yugoslavia View: 1780 Hamza Arshad 

Question

I have a html table .I want to convert that html table to png and want to render it on webpage using PHP.

<table>
   <tbody>
      <tr>
         <td>Day</td>
         <td>Timing </td>
      </tr>
      <tr>
         <td>
            Sunday 
         </td>
         <td>8:30-6:30</td>
      </tr>
      <!-- New  -->
      <tr>
         <td>
            Monday 
         </td>
         <td>8:30-6:30</td>
      </tr>
      <!-- New  -->
      <tr>
         <td>
            Tuesday 
         </td>
         <td>8:30-6:30</td>
      </tr>
      <!-- New  -->
      <tr>
         <td>
            Wednesday 
         </td>
         <td>8:30-6:30</td>
      </tr>
      <!-- New  -->
      <tr>
         <td>
            Thursday 
         </td>
      </tr>
      <!-- New  -->
      <tr>
         <td>
            Friday 
         </td>
      </tr>
      <!-- New  -->
      <tr>
         <td>
            Saturday 
         </td>
         <td>8:30-6:30</td>
      </tr>
   </tbody>
</table>

Currently this code is rendering html table on webapge . I want to show only PNG of this webpage so that there will be only image on webpage and no html table .

I have tried this code but it's only showing yellowish

 <?php

$out = "<table><tr><td>There will be data</td></tr></table>";
header('Content-type: image/png');
$png_image = imagecreate(50, 500);
$tcol = imagecolorallocate($png_image, 255, 255, 0);
imagestring($png_image, 4, 30, 25, $out, $tcol);
// echo $out;
imagepng($png_image);
imagedestroy($png_image);

 ?>

Best answer

Are you just trying to open this file directly? Or display it on a webpage? Because then you'll reference this PHP file "like" it's an image with a <img src="table_image.php" /> in your webpage.

Also, like the official example (https://www.php.net/manual/en/function.imagecreate.php), it's best to include some error handling in case you don't have access to the imagecreate function on your server.

$png_image = @imagecreate(500, 300)
or die("Cannot Initialize new GD image stream");