Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert html & css to an image?

I'm developing an ecard-maker (I know it's awful, not my idea...). Is there any way to convert html and css of a specific dom-element to an image without using flash? I know there is image magick and the like, but it seems to be quite complicated to align and order the text properly.

Preferably I'm looking for a server-side solution, as posting an image from the client could take some time.

I found this: https://code.google.com/p/java-html2image/ but unfortunately I can only use php, ruby or client-side technologies.

like image 353
hugo der hungrige Avatar asked Dec 07 '13 14:12

hugo der hungrige


1 Answers

Client Side solution

In Client Side, you can use something like library (that uses HTML 5): http://html2canvas.hertzen.com/ =)

With it, you can use something like:

html2canvas(document.getElementById("element-id"), {
onrendered: function(canvas) {
  var image = new Image();
  image.src = canvas.toDataURL("image/png"); // This should be image/png as browsers (only) support it (to biggest compatibilty)
  // Append image (yes, it is a DOM element!) to the DOM and etc here..
}
});

Server Side solution

To get a server side solution, you can use PhantomJS (that uses Webkit) or SlimerJS (that uses Gecko).

A good library that is a wrapper to these two is CasperJS. Using CasperJS, a code that can be used is:

casper.start(casper.cli.args[0], function() {
    this.captureSelector(casper.cli.args[1], casper.cli.args[2]);
});

casper.run();

Save it as screenshot.js (just an example of name, you can choice a name too) and run it by using something like:

casperjs screenshot.js (URL) (image path) (selector)

From any language.

A (possible better) alternative to Server Side

Other option is use Selenium, but this is only valid if you can run Java in your server (and install browsers manually) (PhantomJS/SlimerJS/CasperJS, however, does not have these requeriments)

Use it only if you need to emulate a browser completely (maybe when using plugins...)

The best of Selenium is that you can use wrappers to connect to it (using Selenium Server), see the documentation to get the list: http://code.google.com/p/selenium/w/list

like image 88
Fernando Jorge Mota Avatar answered Oct 02 '22 14:10

Fernando Jorge Mota