Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving a DIV as an Image

Tags:

html

php

gd

I have:

echo"
<div id=IwantToSaveThisWholeDivAsAnImage)>
  <div id=OneOfMultipleDivs>
    <table>multiple tables rendered here
    </table>
  </div>
</div>";

I have tried (one of many):

$html_code = " 
<html> 
  <head> 
   <title>Image</title> 
   <style> 
     body { 
     font-family:verdana; 
     font-size:11px; 
     color:black 
   } 
   </style> 
  </head> 
  <body> 
   my tables here
  </body> 
</html>";
$img = imagecreate("300", "600"); 
$c = imagecolorallocate($img, 0, 0, 0);
$c2 = imagecolorallocate($img, 255, 255, 255);
imageline($img,0,0,300,600,$c);
imageline($img,300,0,0,600,$c2);

$white = imagecolorallocate($img, 255, 255, 255); 
imagettftext($img, 9, 0, 1, 1, $white, "arial.tff", '$html_code'); 
header("Content-type: image/jpeg");
imagejpeg($img);

I'm not allowed to use outside libaries. Read that it can be done with GD, but I have been unsuccessful thus far. Any ideas and help would be greatly appreciated! UB

like image 262
UBES Avatar asked Dec 27 '22 16:12

UBES


2 Answers

To explain a bit further than my comment: the rendering of HTML is done by your browser. PHP is server-side, so it doesn't know how to render HTML, nor will it ever. This means that you're going to need "something" that can render HTML and save the rendered result to an image, while PHP can "talk" to it. For this, wkhtmltoimage works (give it a URL, and you end up with a JPG which you can then crop). I've heard good things about phantomjs too, which might be even better suited for your objective, as you can "select" a certain div.

If you're absolutely shut out of using any external tools, you're basically without options.

like image 101
Berry Langerak Avatar answered Dec 29 '22 09:12

Berry Langerak


You can render if by using a tool like wkhtmltoimage

Since it's not written in php, it means you are able to install it on your server and to run it from php.

like image 36
blue112 Avatar answered Dec 29 '22 09:12

blue112