我设法通过各种搜索将HtmlComponent
添加到我的项目中。
我的下一个问题是我不知道如何将其添加到JasperDesign
。
我根本找不到任何将HtmlComponent
添加到JasperDesign
的方法(甚至没有通过组等)。
我使用Jasper 5.6.1,并设法从iReport工具(5.6.0)中获取了HtmlComponent jar(5.0.1)。
我的最终目的是能够在报告中包含一个HTML表。我知道这是不可能的,但也许HTML组件是最有趣的事情。这样,表格的图像就会出现在我的报告中,没关系。
这是我当前的代码
private JasperDesign getTable(String html, JasperDesign jasperDesign) {
HtmlComponent table = new HtmlComponent();
JRDesignExpression expression = new JRDesignExpression();
expression.setText(html.replace("\n", ""));
table.setHtmlContentExpression(expression);
JRDesignGroup group = new JRDesignGroup();
group.setName(TABLE_GROUP_PREFIX);
JRDesignBand groupHeader = new JRDesignBand();
groupHeader.setHeight(200);
groupHeader.setSplitType(SplitTypeEnum.IMMEDIATE);
groupHeader.addElement(table);
((JRDesignSection) group.getGroupHeaderSection()).addBand(groupHeader);
return jasperDesign;
}
groupHeader.addElement(table)
行失败,因为HtmlComponent不是Element,而是一个Component。 最佳答案
要将组件添加到JRDesign
,您需要将其包装在JRDesignComponentElement
中
JRDesignComponentElement ce = new JRDesignComponentElement(design);
ce.setComponentKey(new ComponentKey("http://jasperreports.sourceforge.net/htmlcomponent", "hc", "html"));
ce.setComponent(table);
完整的例子
//Create the design
JasperDesign design = new JasperDesign();
design.setWhenNoDataType(WhenNoDataTypeEnum.ALL_SECTIONS_NO_DETAIL); //We will run with no data
design.setName("Html test");
//Add a title band
JRDesignBand title = new JRDesignBand();
title.setHeight(100);
design.setTitle(title);
//Create our component
HtmlComponent hc = new HtmlComponent();
JRDesignExpression expression = new JRDesignExpression();
expression.setText("\"<b>Hello</b> world\"");
hc.setHtmlContentExpression(expression);
//Wrap it in a design componenent
JRDesignComponentElement ce = new JRDesignComponentElement(design);
ce.setComponentKey(new ComponentKey("http://jasperreports.sourceforge.net/htmlcomponent", "hc", "html"));
ce.setComponent(hc);
ce.setHeight(100);
ce.setWidth(100);
title.addElement(ce);
//Compile the design
JasperReport report = JasperCompileManager.compileReport(design);
//Generate the print (passing no datasource, empty)
JasperPrint print = JasperFillManager.fillReport(report, new HashMap<String,Object>());
//Export to pdf
JRPdfExporter exporter = new JRPdfExporter();
exporter.setExporterInput(new SimpleExporterInput(print));
exporter.setExporterOutput(new SimpleOutputStreamExporterOutput("pdf/htmlComponent.pdf"));
SimplePdfExporterConfiguration configuration = new SimplePdfExporterConfiguration();
exporter.setConfiguration(configuration);
exporter.exportReport();
输出量
Hello World的大量代码,用jrxml编写报告通常更快
关于java - 如何将HtmlComponent添加到JasperDesign,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42560528/