public class BarChartReport
{
public BarChartReport() {
build();
}
private void build() {
FontBuilder boldFont = stl.fontArialBold().setFontSize(12);
StyleBuilder boldStyle = stl.style().setFontName("Arial");
StyleBuilder boldCenteredStyle = stl.style(boldStyle)
.setHorizontalAlignment(HorizontalAlignment.CENTER);
StyleBuilder columnTitleStyle = stl.style(boldCenteredStyle)
.setBorder(stl.pen1Point())
.setBackgroundColor(Color.LIGHT_GRAY);
TextColumnBuilder<String> itemColumn = col.column("Item", "item", type.stringType());
TextColumnBuilder<Integer> quantityColumn = col.column("Quantity", "quantity", type.integerType());
TextColumnBuilder<BigDecimal> unitPriceColumn = col.column("Unit price", "unitprice", type.bigDecimalType());
try {
report()
.setColumnTitleStyle(columnTitleStyle)
.setTemplate(Templates.reportTemplate)
// .columns(itemColumn, quantityColumn, unitPriceColumn)
.title(Templates.createTitleComponent("BarChart"))
.summary(
cht.barChart()
.setTitle("Bar chart")
.setTitleFont(boldFont)
.setCategory(itemColumn)
.addCustomizer(new ChartCustomizer())
.series(
cht.serie(quantityColumn), cht.serie(unitPriceColumn)).setShowValues(Boolean.TRUE).setHeight(700)
.addCustomizer(new ChartCustomizer()))
.pageFooter(Templates.footerComponent)
.setDataSource(createDataSource())
.show();
} catch (DRException e) {
e.printStackTrace();
}
}
private JRDataSource createDataSource() {
DRDataSource dataSource = new DRDataSource("item", "quantity", "unitprice");
dataSource.add("Tablet", 350, new BigDecimal(300));
dataSource.add("Laptop", 300, new BigDecimal(2000));
dataSource.add("Smartphone", 450, new BigDecimal(250));
return dataSource;
}
private class ChartCustomizer implements DRIChartCustomizer, Serializable {
public void customize(JFreeChart chart, ReportParameters reportParameters) {
ValueAxis axis = chart.getCategoryPlot().getRangeAxis();
TickUnits tickUnits = new TickUnits();
tickUnits.add(new NumberTickUnit(300)); //sets value with which y-axis gets incremented
// axis.setVerticalTickLabels(true);
axis.setStandardTickUnits(tickUnits);
//rotate x-axis value to vertical
CategoryAxis domainAxis = chart.getCategoryPlot().getDomainAxis();
domainAxis.setCategoryLabelPositions(CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 2));
//this is to rotate values on each bar generated
BarRenderer renderer = (BarRenderer) chart.getCategoryPlot().getRenderer();
renderer.setShadowPaint(Color.LIGHT_GRAY);
renderer.setShadowVisible(true);
for (int x = 0; x < 5; x++) {
renderer.setSeriesItemLabelFont(x, new Font("Times New Roman", Font.PLAIN, 10));
renderer.setSeriesPositiveItemLabelPosition(x,
// new ItemLabelPosition(ItemLabelAnchor.OUTSIDE3, TextAnchor.BOTTOM_LEFT, TextAnchor.BOTTOM_LEFT, -45.0));
new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.CENTER, TextAnchor.CENTER, -55.0));
}
}
}
public static void main(String[] args) {
new BarChartReport();
}