添加 CSS 到 JasperReports 的 HTML 导出

Add CSS to JasperReports' HTML Export

我使用 JasperReports 6.4.3 创建了一份报告,该报告通常导出为 PDF。现在,我也在尝试将此报告导出到 HTML。 我不想通过 JasperExportManager 创建 HTML 文件,所以我使用 JasperReport 的 HtmlExporter 将报告直接写入输出流。

她是我的密码:

public void exportToHtml(OutputStream outputStream, JRDataSource jrDataSource, Map<String, Object> parameter, File reportFile) 
      throws IOException {
    try {
      JasperPrint jasperprint = JasperFillManager.fillReport(reportFile.getAbsolutePath(), parameter, jrDataSource);
      HtmlExporter exporter = new HtmlExporter();

      SimpleHtmlExporterOutput exporterOutput = new SimpleHtmlExporterOutput(outputStream);
      Map<String, String> images = Maps.newHashMap();
      exporterOutput.setImageHandler(new HtmlResourceHandler() {
        @Override
        public void handleResource(String id, byte[] data) {
          System.err.println("id" + id);
          images.put(id, "data:image/jpg;base64," + Base64.encodeBytes(data));
        }

        @Override
        public String getResourcePath(String id) {
          return images.get(id);
        }
      });
      exporter.setExporterOutput(exporterOutput);
      exporter.setExporterInput(new SimpleExporterInput(jasperprint));

      SimpleHtmlExporterConfiguration exporterConfiguration = new SimpleHtmlExporterConfiguration();
      exporterConfiguration.setBetweenPagesHtml("<div style='page-break-after:always'></div>");
      exporter.setConfiguration(exporterConfiguration);
      exporter.exportReport();
    } catch (JRException jrException) {
      throw new IOException(jrException);
    }
}

输出看起来不错,但我需要向 HTML 输出添加一些样式。所以我想知道是否可以将对 css 文件的引用添加到导出的 html 报告中。

与设置页面之间的方式类似 HTML,您可以对 header/footer 执行相同的操作:

exporterConfiguration.setHtmlHeader("...");
exporterConfiguration.setHtmlFooter("...");

header 的默认 HTML 代码设置为 here and the one for footer is set here

您需要在修改任何标签时匹配 opening/closing 标签。