Jasper Reports: How to combine two report streams

2019-01-28 23:12发布

问题:

I have this code that only generates one Jasper report at a time to PDF based on a given condition. But what if I want to combine both Jaspers into one PDF file? (i.e. the PDF output should be LoadTagR2R.jasper + LoadTagR2RLandscape.jasper -- which will be one PDF output stream with multiple pages)

        if (fullHalfTag.equalsIgnoreCase("Y")){ //Read FULL_HALF_TAG value (if FULL_HALF_TAG == 'Y')
            logger.debug("Printing FULL tag...");
            reportStream = getServletConfig().getServletContext().getResourceAsStream("/reports/LoadTagR2RLandscape.jasper");

        } else {
            logger.debug("Printing HALF tag...");
            reportStream = getServletConfig().getServletContext().getResourceAsStream("/reports/LoadTagR2R.jasper");

        }

        //Report parameters
        Map parameters = new HashMap();
        parameters.put("PLT_NO", pltNo);
        parameters.put("TICKET_NO", ticketNo);

          try {

             Connection conn = ConnectionUtils.getConnection();

             JasperRunManager.runReportToPdfStream(reportStream,servletOutputStream, parameters, conn);
             response.setContentType("application/pdf");

             servletOutputStream.flush();
             servletOutputStream.close();

I have tried merging the two input streams as shown below but it didn't work. Thoughts?

        new java.io.SequenceInputStream(s1, s2).

回答1:

This is the old way to do this:

JasperPrint jasperPrint1 = JasperFillManager.fillReport(reportStream1,  parameters, conn);
JasperPrint jasperPrint2 = JasperFillManager.fillReport(reportStream2,  parameters, conn);

List<JasperPrint> list = new ArrayList<JasperPrint>();
list.add(jasperPrint1);
list.add(jasperPrint2);

JRPdfExporter exporter = new JRPdfExporter();

exporter.setParameter(JRPdfExporterParameter.JASPER_PRINT_LIST, list);
exporter.setParameter(JRPdfExporterParameter.OUTPUT_STREAM,servletOutputStream); 
exporter.exportReport();

EDIT:

In JasperReports 6.1.1 API JRPdfExporterParameter.JASPER_PRINT_LIST and JRPdfExporterParameter.OUTPUT_STREAM are deprecated adding new method.

Replace:

exporter.setParameter(JRPdfExporterParameter.JASPER_PRINT_LIST, list);
exporter.setParameter(JRPdfExporterParameter.OUTPUT_STREAM,servletOutputStream);

with

exporter.setExporterInput(SimpleExporterInput.getInstance(list));
exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(servletOutputStream));