如何查看从JapserReport到Primefaces Media Component生成的PDF?

时间:2016-03-17 07:48:11

标签: primefaces inputstream

我有以下方法从Jasper生成My PDF作为byte []。

<p:media value="#{reportingBean.myPDF}" width="100%" height="100%" player="pdf" />

我不想在新窗口中打开PDF,而是使用primefaces媒体组件,如:

public Student(int ID, String firstName, String lastName, int mark) {
        this.ID = ID;
        this.firstName = firstName;
        this.lastName = lastName;
        this.mark = mark;
    }

如何做到这一点?

1 个答案:

答案 0 :(得分:0)

我已经尝试过了,我自己通过使用Primefaces的StreamedContent找到了解决方案。

将这两行添加到ReportBean:

InputStream in = new ByteArrayInputStream(content);
myDoc = new DefaultStreamedContent(in, "application/pdf", "test.pdf");

在Bean的PostConstruct中,我初始化变量myPDF并从媒体组件中调用它。

<p:media value="#{reportingBean.myPDF}" width="100%" height="100%" player="pdf" />

以下是完整的Bean示例:

ReportingBean:

@Named
@ViewScoped
public class ReportingBean extends BasicBean {
...
private DefaultStreamedContent myPDF;
    public void generateUebersichtMaterial() throws FileNotFoundException {
        InputStream pathMaster_jrxml;
        InputStream pathSubReport_jrxml;
        pathMaster_jrxml = getClass().getResourceAsStream("/reports/mainreport.jrxml");
        pathSubReport_jrxml = getClass().getResourceAsStream("/reports/subreport.jrxml");
        try {
            getConnection();
            HashMap<String, Object> params = new HashMap<>();
            List<ReportMaterialUebersicht> list = new ArrayList<>();
            list = reportFacade.getReportMaterialUebersicht();
            JasperReport subreport = JasperCompileManager.compileReport(pathSubReport_jrxml);
            JasperReport report = JasperCompileManager.compileReport(pathMaster_jrxml);
            params.put(JRParameter.REPORT_LOCALE, Locale.FRENCH);
            params.put("subReport", subreport);
            JasperPrint jasperPrint = JasperFillManager.fillReport(report, params,
                    new JRBeanArrayDataSource(list.toArray()));
            connection.close();
            content = JasperExportManager.exportReportToPdf(jasperPrint);
            Faces.sendFile(content, "Materialuebersicht.pdf", false);
        } catch (Exception e) {
            Logger.getLogger(ReportingBean.class.getName()).log(Level.SEVERE, null, e);
        }
    }
    ...
    @PostConstruct
    private void init() {
        try {
            materialUebersichtPDF = generateUebersichtMaterial();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}