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

故事扮演 提交于 2020-01-12 02:19:07

问题


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


回答1:


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.




回答2:


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




回答3:


You might want to have a look at these d3 wrappers:

  • javafx-d3

https://github.com/stefaneidelloth/javafx-d3

  • gwt-d3:

https://github.com/gwtd3/gwt-d3

  • "Freecode Charts and D3 Wrapper":

https://vaadin.com/directory#!addon/freecode-charts-and-d3-wrapper



来源:https://stackoverflow.com/questions/11331076/how-to-use-a-javascript-chart-library-like-d3-js-or-rapha%c3%abl-in-server-side-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!