3

我在我的应用程序中使用 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。

4

2 回答 2

7

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

在 backing 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 文件现在存储在服务器中,您可以继续在代码的其他部分使用该文件。

于 2012-10-23T17:34:59.113 回答
2

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

所以答案是否定的:/

您可能会考虑使用其他一些服务器端图表生成器(查看下面的链接),它将生成更好看的图表

13、还有其他“开源”的图表库吗?(在底部)

什么是最好的开源 Java 图表库?(除了 jfreechart)

于 2012-10-17T10:03:51.237 回答