Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a JavaScript chart library like D3.js or Raphaël in server-side Java

I would like to use D3.js (or maybe Raphaël) for backend-generated reports using XSL-FO with Java. These JavaScript libraries should be used for several reasons:

  1. They render more beautiful charts than what I've seen from Java libraries (IMO)
  2. They support both SVG and PNG (from what I know), which is needed in XSL-FO
  3. They will also be used in frontend parts of the application. Reusing them also on the backend with Java would reduce developer learning curves and codebase footprint.

So using any similar Java libraries is a less favourable option.

Now the most straight-forward way to use D3.js with Java is to use a heavy tool like selenium in order to render a dummy HTML page and execute the JavaScript in it. But that seems like overkill to me.

Is there any simpler way to execute this kind of JavaScript directly in the same Java process? I'm asking because D3.js is designed to work in the context of an HTML document. I'm not sure if that would be possible to do with Rhino or other Java scripting implementations

like image 326
Lukas Eder Avatar asked Jul 04 '12 14:07

Lukas Eder


People also ask

Is D3 a JavaScript library?

D3.js is a JavaScript library for manipulating documents based on data. D3 helps you bring data to life using HTML, SVG, and CSS.

What is D3 JavaScript used for?

D3 is a JavaScript library and framework for creating visualizations. D3 creates visualizations by binding the data and graphical elements to the Document Object Model. D3 associates (binding) the data (stuff you want to visualize) with the DOM. This allows the user to manipulate, change or add to the DOM.


2 Answers

You could use phantom.js. It's a headless browser based on webkit, which allows you to run JavaScript without the need for a browser.

Using this you could just execute a system call to run phantom.js with for your JavaScript code and inputs. It would then create your output accordingly. See this example.

like image 66
Sirko Avatar answered Oct 16 '22 14:10

Sirko


I worked on that about a year ago. I managed to have parts of HighCharts (SVG graphing in javascript) working with Rhino. I had to plugged env.js into it and ran into a lot of problems regarding canvas Element, especially around Bounding Boxes computations. Objects in Rhino doesn't implement getBBox(), which can't easily be faked.

My goal was to finally render it in PDF with Batik... It took too much time, and we decided to switch to another technology.

So, today, we're using wkhtmltopdf, which is not Java, but which is a static executable that can be embedded in a jar and launched easily from java side. By the way, xvfb is mandatory on Linux if you want to render something. That's pretty the same thing as PhantomJS

like image 27
Grooveek Avatar answered Oct 16 '22 14:10

Grooveek