How to convert html with svg tags and css in to image in java

1.5k views Asked by At

We can successfully convert an SVG into an image with Batik, however, I need to convert a whole HTML div, with SVG implemented within, along with its CSS presentation code, into an image.

Is there any modules / support within Batik or some other Java API for achieving this?

3

There are 3 answers

0
Jorgeblom On

Selenium library for Java may help you. It can run a browser (ie, chrome, firefox, etc.) in background mode, and you can load an HTML and take a snapshot of the content.

Although it's designed for testing and automation, it's the only way I can offer to you.

Hope it helps.

http://www.seleniumhq.org/

0
gustavohenke On

We had the same problem, and we solved it by spawning an PhantomJS process.

Phantom takes an JavaScript file that will instruct its headless browser what to do.
You can wait until the page is fully loaded and then you can print the output into the console as a data URI.

Below is a very simple example from my PhantomJS scripts:

var page = require( "webpage" ).create();
var options = JSON.parse( phantom.args[ 0 ] );

page.open( options.url, "POST", decodeURIComponent( options.payload || "" ), function( status ) {
    if ( status === "fail" ) {
        phantom.exit( 1 );
    }

    var contents = page.renderBase64( "png" );
    require( "system" ).stderr.write( contents );
});
0
bezmax On

This is not an easy task as what you are asking is the process called "html rendering" and is basically what browsers try to implement correctly for over 2 decades.

  • If the CSS you need rendered is fairly simple (no CSS3, no fancy stuff, etc.), then there is a high chance that one of the open-source renderers would be able to handle that (PhantomJS as an example). See @gustavohenke answer for more details.

  • If the CSS is moderately complex and if you are able to modify it if needed - then there are some fast but non-free renderers, like PrinceXML and DocRaptor.

  • If the CSS could be very complex and you are not able to make it simpler - then the only option would be to render it in a real browser. You can use Selenium for that as it has a way of running the browser, rendering your HTML in it and "screenshotting" the result all in automated fashion. See @Jorgeblom answer for more details.