Generate png/jpeg image of Primefaces Charts in backing bean?

走远了吗. 提交于 2019-12-04 17:52:49
Daniel

As you already know Primefaces uses the jqPlot plugin to generate the charts , Since jqPlot is a jquery client side plugin it cannot generate anything on the server side , its a jquery plugin and not some server side api (jar)

So the answer is No :/

You might consider using some other server side chart generator (look at the links below) that will generate a better looking charts

13. Are there other "open source" chart libraries? (at the buttom)

What is the best open-source java charting library? (other than jfreechart)

As in the accepted answer provided by Daniel, Primefaces' charts are not available at the server side. I add an answer here only to show a possible workaround.

At the client side, we assign the base64 PNG encoded string to a hidden field value, an example modified from Primefaces demo source code for export charts:

<h:form id="hform">
    <p:lineChart value="#{testBean.linearModel}" legendPosition="e"
        zoom="true" title="Linear Chart" minY="0" maxY="10"
        style="width:500px;height:300px" widgetVar="chart" />
    <p:commandButton id="exp" value="Export" icon="ui-icon-extlink"
        onclick="exportChart();"
        actionListener="#{testBean.submittedBase64Str}" />
    <h:inputHidden id="b64" value="#{testBean.base64Str}" />
    <script type="text/javascript">
        function exportChart() {
        // exportAsImage() will return a base64 png encoded string
        img = chart.exportAsImage();
        document.getElementById('hform:b64').value = img.src;
        }
    </script>
</h:form>

At the backing bean, we need to decode the string, a simple example as below:

public void submittedBase64Str(ActionEvent event){
    // You probably want to have a more comprehensive check here. 
    // In this example I only use a simple check
    if(base64Str.split(",").length > 1){
        String encoded = base64Str.split(",")[1];
        byte[] decoded = org.apache.commons.codec.binary.Base64.decodeBase64(encoded);
        // Write to a .png file
        try {
            RenderedImage renderedImage = ImageIO.read(new ByteArrayInputStream(decoded));
            ImageIO.write(renderedImage, "png", new File("C:\\out.png")); // use a proper path & file name here.
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

The PNG file is now stored in the server, and you can continue to make use of that file in other parts of your codes.

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