在支持bean中生成Primefaces Charts的png / jpeg图像?

时间:2012-10-17 09:05:26

标签: jsf-2 charts primefaces backing-beans

我在我的应用程序中使用Primefaces 3.1.1图表,在JSF页面中生成图表没有问题,但我试图找出是否可以为图表生成图像(png或jpeg)以便我可以将这些图像插入到java中的Excel文件(Apache POI)中。

我知道最新的Primefaces版本3.4.1具有导出图表功能,但生成的图像仅发生在客户端(它是jqPlot)。但我需要在服务器端。

目前我们在支持bean中使用jFreeChart用于此目的,因此浏览器中的图表与Excel中的图表看起来非常不同。我们试图找出升级到Primefaces 3.4.1是否可以让我们选择在浏览器中制作图表并且Excel中的图表看起来是一样的?或者还有另一种方法吗?

如果这是一个问题,请使用mojarra-2.1.3-FCS。

2 个答案:

答案 0 :(得分:6)

正如Daniel所接受的答案一样,Primefaces的图表在服务器端不可用。我在这里添加答案只是为了显示可能的解决方法。

在客户端,我们将base64 PNG编码的字符串分配给隐藏字段值,这是从Primefaces演示源代码修改导出图表的示例:

<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>

在支持bean中,我们需要解码字符串,如下所示:

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();
        }
    }
}

PNG文件现在存储在服务器中,您可以继续在代码的其他部分使用该文件。

答案 1 :(得分:2)

正如你已经知道Primefaces使用jqPlot插件生成图表,因为jqPlot是一个jquery客户端插件,它不能在服务器端生成任何东西,它是一个jquery插件而不是一些服务器端api(jar)

答案是:/

您可以考虑使用一些其他服务器端图表生成器(请查看下面的链接)来生成更好看的图表

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

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