.Cannot export chart as image in Primefaces?

2019-08-28 18:06发布

问题:

I cannot export prime-faces chart as Image.

categoryModel is same as Prime-show Case.

Is it need dependency lib to export?

<ui:composition xmlns="http://www.w3.org/1999/xhtml"
    ......
    template="/common/commonLayout.xhtml">
    <ui:define name="content">
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <script type="text/javascript">
            //<![CDATA[
            function exportChart() {
                //export image
                $('#output').empty().append(chart.exportAsImage());

                //show the dialog
                dlg.show();
            }
            //]]>
        </script>

        <h:form enctype="multipart/form-data">
            <p:barChart id="basic" value="#{ChartActionBean.categoryModel}" legendPosition="ne"  
                        title="Bar Chart" widgetVar="chart" animate="true" yaxisLabel="Number of Count"/>
            <p:commandButton type="button" value="Export" icon="ui-icon-extlink" onclick="exportChart()"/>  

            <p:dialog widgetVar="dlg" showEffect="fade" modal="true" header="Chart as an Image">  
                <p:outputPanel id="output" layout="block" style="width:500px;height:300px"/>  
            </p:dialog>  
        </h:form>
    </ui:define>
</ui:composition>

回答1:

In Showcase and Export button and OutputPanel are not wrapped in so $('#output') is able to pick the expected element to append the image.

But in your case you have wrapped these components in so JSF will generate an id for form like j_idt10 and the component's id "output" will become "j_idt10:output".

To fix this:

<h:form id="form1">
  //chart
  // export button
  //dialog containing outputPanel
</h:form>

And in javascript:

function exportChart() {
     $('#form1\\:output').empty().append(chart.exportAsImage());
     dlg.show();
}

or simply put outside the and $('#output').empty().append(chart.exportAsImage()); will work as expected.



回答2:

I also think that to specify a model you use a model attribute and not value. So in your case it would be:

<p:barChart id="basic" model="#{ChartActionBean.categoryModel}" legendPosition="ne" title="Bar Chart" widgetVar="chart" animate="true" yaxisLabel="Number of Count"/>